Ext.BLANK_IMAGE_URL = 'ext-2.1/resources/images/default/s.gif';
try { console.log(''); } catch(e) { console = { log: function(s) {} } }

var globals = {
	initialLoad : true,
	loggedIn : false,
	online : true,
	mySlidesLoaded : false,
	showingHelp : false,
	MySlidesGetError : 0,
	emailRegex : /^([\w]+)(.[\w]+)*@([\w-]+\.){1,5}([A-Za-z]){2,4}$/,
	pagingCursor : 0,
	rated : [],
	updateMySlidesTask : new Ext.util.DelayedTask()
}

Utilities = function() {
	return {
		feedback : function() {
			var feedbackWin = new Ext.Window({
			    layout :'fit',
			    title : lang.feedback_title,
			    maximizable : false,
			    width : 320,
			    height : globals.online? 450 : 250,
			    autoScroll : true,
			    closeAction : 'hide',
		    	modal: true,
		    	plain: true,
		    	buttonAlign : 'left',
		    	contentEl : globals.online? 'feedbackContainer' : 'feedbackContainer-offline',
					buttons :  globals.online? [{
					text : lang.feedback_send,
					cls: 'x-btn-text-icon',
			  	icon: 'images/icons/email.png',
					handler : function(btn) {
						btn.disable();
						Ext.fly('feedbackError').update('');
						Ext.fly('lblFeedbackMessage').removeClass('help-error');
						Ext.fly('lblFeedbackEmail').removeClass('help-error');
						
						var msg = Ext.fly('feedbackMessage').getValue();
						var email = Ext.fly('feedbackEmail').getValue();
						
						var errorMsg = '';
						
						if (!globals.emailRegex.test(email)) {
							btn.enable();
							errorMsg = lang.feedback_invalid_email + '<br/>';
							Ext.fly('lblFeedbackEmail').addClass('help-error');
							Ext.fly('feedbackLoading').setDisplayed(false);
						}
						if (msg == '') {
							btn.enable();
							errorMsg += lang.feedback_empty_msg;
							Ext.fly('lblFeedbackMessage').addClass('help-error');
							Ext.fly('feedbackLoading').setDisplayed(false);
						}
						
						if (errorMsg != '') {
							Ext.fly('feedbackError').update(errorMsg);
							return;
						}
																						
						var stp = new Ext.data.ScriptTagProxy({
						url: config.serverRoot + String.format(config.feedbackPath, config.siteId, email, msg),
						callbackParam : 'cb',
						timeout: config.serverTimeout
						});
				
						Ext.fly('feedbackLoading').show();
						
						/*always fires load exception because it has no reader 
						 * data will be true if successful. otherwise show error.
						 */
						stp.on('loadexception', function(o, data, cb, e) {
							if (data && data.sent) {
								//feedback sent ok
								Ext.fly('feedback-form').setDisplayed(false);
								Ext.fly('feedback-confirm').setDisplayed(true);
								Ext.fly('feedbackLoading').setDisplayed(false);
							}
							else {
								//error
								Ext.fly('feedbackError').update(lang.feedback_error);
								Ext.fly('feedbackLoading').setDisplayed(false);
								btn.enable();
							}
						});
						
						stp.load(null, null, function(){});
							
						}
					}] : []
			  });
			  feedbackWin.show();
				try {
					Ext.fly('feedback-form').setDisplayed(true);
					Ext.fly('feedback-confirm').setDisplayed(false);
					if (user.email) {
						Ext.fly('feedbackEmail').dom.value = user.email;
					}
					Ext.fly('feedbackError').update('');
					Ext.fly('lblFeedbackMessage').removeClass('help-error');
					Ext.fly('lblFeedbackEmail').removeClass('help-error');
				}
				catch(e) {}
		},
		
		
		help : function() {
			var helpWin = new Ext.Window({
			
				id: 'helpWindow',
				layout: 'fit',
				maximizable: false,
				width: 530,
				title : lang.help_title,
				height: 400,
				closable: true,
				closeAction: 'close',
				modal: true,
				plain: true,
				html: '<div id="helpContainer" class="windowContainer"><p class="loading-indicator">' + lang.loading + '</p></div>'
			});
			
			helpWin.show();
					
			Ext.Ajax.request({
				url: 'help.htm',
				disableCaching: true,
				success: function(r){
					try {
						//need try/catch because window could have been closed before loaded
						Ext.fly('helpContainer').update(r.responseText);
						Utilities.log('About');
					} 
					catch (e) {}
				},
				failure: function(r){
					try {
						//need try/catch because window could have been closed before loaded
						Ext.fly('helpContainer').update('<p>' + lang.help_unavailable + '</p>');
					} 
					catch (e) {}
				},
				scope: this
			});
		},
		
		
		searchFocus : function(active) {
			var o = Ext.get('txtSearch');
			if (active) {
				if (o.getValue() == lang.search_default) o.dom.value = '';
				o.removeClass('faded');
			}
			else {
				if (o.getValue() == '') {
					o.dom.value = lang.search_default;
					o.addClass('faded');
				}
			}
			return false;
		},
		
		
		
		showFigure : function(o, link) {
			var figure = link.substring(link.lastIndexOf('/')+1);
			
			//close existing window first
			var figWin = Ext.getCmp('figureWin');
			if (figWin) {
				figWin.close();
			}
						
			
			//default size
			var winWidth = 850; //-40
			var winHeight = 800; //-60
			
			//shrink to fit window
			var size = Ext.getBody().getViewSize();
			if (size['width'] < winWidth) winWidth = size['width'];
			if (size['height'] < winHeight) winHeight = size['height'];
		    			
			figureWin = new Ext.Window({
		    id : 'figureWin',
				layout:'fit',
		    title : lang.figure_title,
		    width: winWidth - 40,
		    height: winHeight - 60,
		    autoScroll: true,
		    tbar: new Ext.Toolbar(),
		    closeAction:'close',
	    	modal: true,
	    	plain: true,
	    	html : '<div id="figureContent"><p class="loading-indicator">' + lang.loading + '</p></div>'
		  });
		  
		  figureWin.show();

		  var figWinTbar = figureWin.getTopToolbar();

			if (globals.online) {

			  	figWinTbar.addButton([{
			  		text: lang.figure_email,
			  		cls: 'x-btn-text-icon',
			  		icon: 'images/icons/email.png',
			  		handler: function(){
		  				
						var idprefix = 'email';
						
						var emailWin = new Ext.Window({
						    layout :'fit',
						    title : lang.email_title,
						    maximizable : false,
						    width : 320,
						    height : 400,
						    autoScroll : true,
						    closeAction : 'hide',
					    	modal: true,
					    	plain: true,
					    	buttonAlign : 'left',
					    	contentEl : 'emailContainer',
								buttons : [{
									text : lang.email_send,
									cls: 'x-btn-text-icon',
						  		icon: 'images/icons/email.png',
									handler : function(btn) {
										
										Ext.fly('lblEmailMessage').removeClass('help-error');
										Ext.fly('lblEmailFrom').removeClass('help-error');
										Ext.fly('lblEmailTo').removeClass('help-error');
										
										var from = Ext.fly('emailFromAddress').getValue();
										var to = Ext.fly('emailToAddress').getValue();
										var msg = Ext.fly('emailMessage').getValue();
										
										var error = '';
										
										if (msg == '') {
											Ext.fly('lblEmailMessage').addClass('help-error');
											error = lang.email_message + '<br/>';
										}
										if (!globals.emailRegex.test(from)) {
											Ext.fly('lblEmailFrom').addClass('help-error');
											error += lang.email_invalid_from + '<br/>';
										}
										if (!globals.emailRegex.test(to)) {
											Ext.fly('lblEmailTo').addClass('help-error');
											error += lang.email_invalid_to;
										}
										
										if (error != '') {
											Ext.fly('emailError').update(error);
											return;
										}
										
										
										btn.disable();
										Ext.fly('emailLoading').show();
										Ext.fly('emailError').update('');	
																				
										var stp = new Ext.data.ScriptTagProxy({
											url: config.serverRoot + String.format(config.emailFigurePath, config.siteId, figure, from, to, msg),
											callbackParam : 'cb',
											timeout: config.serverTimeout
										});
							      
						            
										/*always fires load exception because it has no reader 
										 * data will be true if successful. otherwise show error.
										 */
										stp.on('loadexception', function(o, data, cb, e) {
											
											Ext.fly('emailLoading').setDisplayed(false);
											if (data && data.sent) {
												//email sent ok
												Ext.fly('email-form').setDisplayed(false);
												Ext.fly('emailLoading').setDisplayed(false);
												Ext.fly('email-confirm').setDisplayed(true);
												Utilities.log('Email', figure);
											}
											else {
												//error
												Ext.fly('emailError').update(lang.email_error);
												Ext.fly('emailLoading').setDisplayed(false);
												btn.enable();
											}
										});
										stp.load(null, null, function(){});
									}
								}]
						  });
						  emailWin.show();
							try {
								Ext.fly('email-form').setDisplayed(true);
								Ext.fly('email-confirm').setDisplayed(false);
								if (user.email) {
									Ext.fly('emailFromAddress').dom.value = user.email;
								}
								Ext.fly('emailError').update('');
								Ext.fly('lblEmailMessage').removeClass('help-error');
								Ext.fly('lblEmailFrom').removeClass('help-error');
								Ext.fly('lblEmailTo').removeClass('help-error');
							}
							catch(e) {}
						}
					}, 
					new Ext.Toolbar.Spacer(),
					{
						text: lang.add_to_slideset,
						cls: 'x-btn-text-icon',
						iconCls: 'folder-add-btn',
						hidden: !globals.loggedIn,
						handler: function(){
							Ext.getCmp('imagesTbarBtnAdd').handler();
						}
					}
				]);
					
				if (globals.online) {
					//add star rating
					var stars = new Ext.ux.StarRating({
						id : 'stars',
						totalStars: 5
					});
					
					stars.valueClicked = (globals.rated.indexOf(figure) != -1);					
					
					stars.on('rate', function(o, vote){
						Ext.fly('stars-text').update(lang.figure_rating_updating);
																	
						var stp = new Ext.data.ScriptTagProxy({
						    url: config.serverRoot + String.format(config.figureRatingPath, config.siteId, figure, vote),
						    callbackParam : 'cb',
						    timeout: config.serverTimeout
				      });
			            
						/*always fires load exception because it has no reader 
						 * data will be true if successful. otherwise show error.
						 */
						stp.on('loadexception', function(o, data, cb, e) {
							try {
								if (data) {
									if (data.votes == 0) {
										Ext.fly('stars-text').update(lang.figure_rating_befirst);
									}
									else {
										stars.average = data.rating;
										stars.resetStars();
										Ext.fly('stars-text').update(String.format(lang.figure_rating, data.rating, data.votes));	
										
										//if voted, add to array to prevent multiple votes this session
										//also disable mouseover
										if (vote) {
											globals.rated[globals.rated.length] = data.figure;
											stars.stars.addClass('disabled');
											Utilities.log('Rating', figure);
										}
									}
								}
								else {
									Ext.fly('stars-text').update(lang.figure_rating_error);
								}
							}
							catch(e) { /*do nothing - window could have been closed before callback*/}
						});
						
						stp.load(null, null, function(){});
						
					
					});
					
					figWinTbar.addSpacer();
					figWinTbar.add(stars);
					stars.fireEvent('rate', this, '');
				}
			}
			else {
				figWinTbar.hide();
			}
					  
			//get figure content
			Ext.Ajax.request({
				url: config.contentPath + link + '.html',
				success: function(r) {
					try {
						//need try/catch because window could have been closed before loaded
						Ext.fly('figureContent').update(r.responseText);
						Utilities.log('Figure', figure);
					}
					catch(e){ console.log(e); }
				},
				failure: function(r) { 
					try {
						//need try/catch because window could have been closed before loaded
						Ext.fly('figureContent').update('<p>' + lang.figure_unavailable + '</p>');
					}
					catch(e) {}
				},
				scope: this
			});
		},
		
		toggleFigureReferences : function(o) {
			var refs = Ext.get('referenceList');
			refs.toggle(true);
			try {
				if (o) o.blur();
			}
			catch(e) {}
			return false;
		},
		
		readCookie : function() {
			var param = 'IC' + config.siteId + '#';
			var ca = document.cookie.split(';');
			for(var i=0; i<ca.length; i++) {
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1, c.length);
				if (c.indexOf(param) == 0) {
					var user = c.substring(param.length, c.length).split(',');
					if (user && user.length == 2) return user;
				}
			}
			return null;
		},
		
		log : function(action, args) {
			if (globals.online) {
				try {
					var s = (arguments.length === 2 && args.toString() !== 'undefined')? action + '/' + args : action;
					pageTracker._trackPageview(s);
				}
				catch(e){}
			}
		}
		
	}
}();

