/*global JMT Ext $ BackgroundLoad*/
if (!JMT){
	var JMT;
}
JMT.startup = function(){
	var _xlt = JMT.i18n.xlt;
	var isLoading = true; // This flag indicates background loading is in progress and prevents premature login.
	var isGuest = true;
	/**
	 * Extract and return the text content from the xml response. Works either
	 * for "logon" and "logout" operations.
	 * @param xmlData The xml dom structure containing either the <logonResult>
	 * or <logoutResult> tags.
	 * @return the text inside the <logonResult> or <logoutResult> xml tags.
	 * Returned values will never be null.
	 */
	function extractResponse(xmlData) {
		if (xmlData === null) {
			return '';
		}
		if (xmlData.childNodes.length === 0) {
			return '';
		}
		var result = xmlData.firstChild.nodeValue;
		if (result === null) {
			return '';
		}
		result = result.trim();
		return result;
	}

	function doLogin(){
		if (isLoading){
			document.getElementById("loading-message").style.display="block";
			setTimeout(doLogin,100); // check until we're ready to run
			return;
		}
		// Close the login window...
		document.getElementById("logon-form").style.display="none";
		document.getElementById("loading-message").style.display="none";		
	//	$("#loading-message").hide();
/*		document.getElementById("application").style.left="0px";
		document.getElementById("application").style.top="0px";
		document.getElementById("application").style.right="0px";
		document.getElementById("application").style.bottom="0px";*/
		
		//GO!
		document.getElementById("application").style.position="static";
		document.getElementById("application").style.display="block"; // ensure it's visible
		// ... and open Navigator
		JMT.forms.Navigator.show();
	}
	function showLoginWindow(){
		document.getElementById("application").style.position="fixed";
//		document.getElementById("application").style.display="none";
		document.getElementById("logon-form").style.display="block";
		document.body.style.position="static"; // If we don't have this then the body changes to relative positioned for some reason and the login screen is not redrawn where we want it.
		document.getElementById("username").value = "";
		document.getElementById("password").value = "";
		document.getElementById("newpass1").value = "";
		document.getElementById("newpass2").value = "";
		document.getElementById("username").focus();
	}
	
	var preprocessor = function (xml, args){
		if (isLoading){
			document.getElementById("loading-message").style.display="block";
			setTimeout(doLogin,100); // check until we're ready to run
			return;
		}

		document.getElementById("loginBtn").disabled = false;
		document.getElementById("loginAsGuestBtn").disabled = false;
		JMT.global.preprocessor(xml,args);
	}; 
	
	// Creates the exception handler in case of failure 
	var exceptionHandler = function(errorCode, errorString, details) {
		document.getElementById("loginBtn").disabled = false;
		document.getElementById("loginAsGuestBtn").disabled = false;
		alert(_xlt("Failed to login") + ". " + errorString);
	};
	
	// Creates the callback function
	var loginCallback = function (xml) {
		
		document.getElementById("loginBtn").disabled = false;
		document.getElementById("loginAsGuestBtn").disabled = false;
		
		// Process the incoming message
		var result = extractResponse(xml);
		// success: result is empty
		// failure: result contains the error/warning message
		if (result !== "") {
			exceptionHandler(0, result);
			if(result.indexOf("password has expired") > -1) {
				document.getElementById("newpass1tr").style.display = "";
				document.getElementById("newpass2tr").style.display = "";
			}
			return;
		}
		
		document.getElementById("newpass1tr").style.display = "none";
		document.getElementById("newpass2tr").style.display = "none";
		
		JMT.JMTWebService.getCurrentTerminal(function (xml){
			var currentTerminalName = $(xml).find('terminal name').text();
			if (currentTerminalName) {
				document.getElementById("toolbar-text").innerHTML = currentTerminalName;
			}					
		});
		
		doLogin();
	};	
	
	return { // public attributes and functions
		init : function(){
			//----- CHECK FOR OUTDATED BROWSERS
			// if they are running internet explorer 6.0 then we might as well just give up now
			// as it doesn't support many things required by this app.
		    if (navigator.appName == 'Microsoft Internet Explorer') {
			  	var rv = -1;
			  	var ua = navigator.userAgent;
			  	var re = new RegExp("MSIE ([0-9]{1,}[\\.0-9]{0,})");
			  	if (re.exec(ua) !== null) {
			  		rv = parseFloat(RegExp.$1);
			  	}
				if (rv < 7) {
					// Hide the login form and the application. Display the IE6 is unsupported message.
					document.getElementById("logon-form").style.display="none";
					document.getElementById("application").style.display="none";
					document.getElementById("ie6-message").style.display="block";
					return;
				}
			  }
			document.getElementById("username").focus();
			//----- INITIATE BACKGROUND LOADING OF SCRIPTS
			function loadingComplete(){ // CALLBACK FOR WHEN SCRIPT LOADING COMPLETES
			
				//$("#application").show(); //document.getElementById("application").style.display="block";
				Ext.BLANK_IMAGE_URL = 'ext-2.2/resources/images/default/s.gif';
				Ext.WindowMgr.zseed = 50000; // makes sure the message boxes appear in front of other things
				Ext.QuickTips.init(); 
				// Setup the desktop:
				JMT.desktop = new Ext.Desktop();
				$('#logo-picture, #navigator-button').click(JMT.forms.Navigator.show);
				$('#logout-button').click(JMT.startup.promptBeforeLogout);
				$('#option-button').click(JMT.forms.OptionNavigator.show);
				$('#help-button').click(JMT.startup.openHelpPage);
				isLoading = false; // when everything's loaded, set a flag.
			}
			if ('undefined' !== typeof Ext) { // Check whether Ext.js and (by implication) all other relevant scripts have been loaded
				loadingComplete();
			} else { // If they haven't then we need to load them.
				BackgroundLoad.css([
				"ext-2.2/resources/css/_AllExtCssMin.css",
				"css/_AllCssMin.css"]);
				BackgroundLoad.scriptNo$('jqueryMin.js');
				BackgroundLoad.script([
				"ext-2.2/adapter/ext/ext-base.js",
				"ext-2.2/ext-all.js",
				"scripts/_AllScriptsMin.js"
				],loadingComplete);
			}
		},
		promptBeforeLogout: function(){
			Ext.MessageBox.confirm('Confirm', 'Are you sure you want to log out?', function(btn){
				if (btn === 'yes'){
					JMT.startup.doLogout();
				}
			});
		},
		validateLogin : function (form) {
			document.getElementById("loginBtn").disabled = true;
			document.getElementById("loginAsGuestBtn").disabled = true;
			
			if (document.getElementById("newpass1tr").style.display === "") {
				// Do the webservice call
				JMT.JMTWebService.logonAndChangePassword(
						form.username.value,
						form.password.value,
						form.newpass1.value,
						form.newpass2.value,
						loginCallback, preprocessor,
						exceptionHandler);
			}
			else {
				// Do the webservice call
				JMT.JMTWebService.logon(
						form.username.value,
						form.password.value, 
						loginCallback, preprocessor,
						exceptionHandler);
			}
			isGuest = false;
		},
		loginAsGuest : function () {
			document.getElementById("loginBtn").disabled = true;
			document.getElementById("loginAsGuestBtn").disabled = true;
			
			// Do the webservice call
			JMT.JMTWebService.logonAsAnonymousUser( 
					loginCallback, preprocessor,
					exceptionHandler);
			isGuest = true;
		},
		isGuest : function (){
			return isGuest;
		},
		visitHomePage : function () {
			window.open("http://www.jadeworld.com/logistics");
		},
		openHelpPage : function () {
			JMT.global.whenReady('getHelpFile',null,'WS_HelpFile',function(store, xml){
				var url = $(xml).find("helpFile url").text();
				if(url) {
					window.open(url);
				}
				else {
					JMT.startup.visitHomePage();
				}
			});
		},
		
		doSessionTimeOut : function(){
			JMT.desktop.clearAll();
			JMT.global.clearCache();
			showLoginWindow();
		},
		
		doLogout : function() {
			// Creates the callback function
			var mask = new Ext.LoadMask(
				Ext.getBody(), {msg: _xlt("Logging out") + '...', removeMask: true});
			mask.show();
			
			var clearAllCallback = function () {
				// Creates the exception handler in case of failure 
				var exceptionHandler = function(errorCode, errorString, details) {
					// Hide the "Logging out..." message
					mask.hide();
					
					Ext.MessageBox.show({
						title: _xlt("System Error"),
						msg: _xlt("Logout has been completed with problems") + '\n' + errorString,
						buttons: Ext.MessageBox.OK,
						icon: Ext.MessageBox.WARNING,
						width: 350,
						fn: function(btn) {
							// Show the LoginWindow
							showLoginWindow();
						}
					});
				};

				var callback = function (xml) {
					// Process the incoming message
		
					// the response will be always a boolean or an empty string
					var result = extractResponse(xml);
					if (result != 'true') {
						exceptionHandler(0, _xlt("Server returned an unexpected error"));
						return;
					}
					// Hide the "Logging out..." message
					mask.hide();
					
					// Show the LoginWindow
					showLoginWindow();
				};
				
				// Do the webservice call
				JMT.JMTWebService.logout(
						callback, 0,
						exceptionHandler);
			}
			JMT.desktop.clearAllDoneCallback = clearAllCallback;
			JMT.desktop.clearAll();
			JMT.global.clearCache();					
		}
	};
}();
JMT.startup.init();

