// Locale for login
var dictionary={}; //Dictionary object that contains all the translations
var fs = {
	/**
	 * Locale based functions such as getting and setting values, example of use are:
	 * 
	 * 	//Set the locale from the global file	
	 *	fs.locale.setLocale("en-en");
	 *
	 *	//Global language items
	 * 	fs.locale.loadNamespace("global",{
	 *		"open": "open",
	 * 		"close": "close"	
	 *	});
	 *
	 *	fs.locale.loadNamespace("documents", {
	 *		"welcome": "Welcome to {1}"
	 *	});
	 */
	locale:{
		
		/**
		 * Returns the required word based on a supplied key.  If additional params are supplied then these
		 * become the token keys in phrase generation, additional params can either be a group of strings separated
		 * be a comma or an array of strings
		 * 
		 * Examples:
		 * 	write("global", "open");  --> gets the translation for "open" from the "global" namespace
		 * 	write("documents", "welcome", [workspace]) --> might return "Welcome to Normal-Workspace" where 
		 * 		"Normal-Workspace" was passed as a string workspace
		 * 
		 * @param _namespace	Mandatory string that dictates the required namespace from which to pull
		 * 					 	the key from.  
		 * @param _key  		Mandatory string indicating the key
		 * @param (optional) 	An array of strings that will match locations in the source string
		 * @return string 		The string matching the supplied namespace and key - or a tokenized version of it 
		 * 
		 */
		write: function(_namespace, _key){
		
			var str="";
		
			if(dictionary.hasOwnProperty(_namespace)){
				
				var str=dictionary[_namespace][_key];
			
				//Don't tokenize if no additional arguments are supplied and then only tokenize if the third
				//parameter is an array
				if(arguments.length == 3 && lang.isArray(arguments[2])){
					str=lang.tokenize(str, arguments[2])
				}
			}
			
			//If the key doesn't exist - pass back a blank
			return str==undefined?_key:str;
		},
		
		/**
		 * Returns the locale code for the currently loaded language, e.g. en-gb
		 * @return string containing language code
		 */
		getLocale: function(){
			return dictionary.languageCode||"xx-xx"; 
		},
		
		/**
		 * Allows the locale string to be set.  Usually called from the local-****-global.js file
		 * @param _lang string containing language code 
		 */
		setLocale: function(_lang){
			if(typeof _lang === "string")dictionary.languageCode=_lang;
		},
		
		/**
		 * 
		 */
		loadNamespace: function(_namespace, _values){
			dictionary[_namespace]=_values;
		},
		
		/**
		 * 
		 */
		removeNamespace: function(_namespace){
			dictionary.remove(_namespace);
		}
		
	}
}

/**
 * Shortcut fs.locale.write - saves time and file size...
 */
var $w=fs.locale.write;
function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if ((typeof element == "string"))
    element = document.getElementById(element);
  return element;
}

function activeXEnabled() {
	try {
		var dict = new ActiveXObject("Scripting.Dictionary");
		if (dict != null) {
			return true;
		}
	} catch (e) {
		return false;
	}
	return false;
}

function getXMLHttpRequest() {
	var xml;
	if (activeXEnabled()) {
		try {
			xml = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (e) {
			xml = new ActiveXObject("MSXML2.XMLHTTP.4.0");
		}
	} else {
		//All other browsers can just use a normal XMLHttpRequest
		if (navigator.appName == "Microsoft Internet Explorer") {
			//IE but no activeX:
			//Create a SAJAX backup XMLHttpRequest
			xml = new SAJAXHttpRequest();
		} else {
			//All other browsers can just use a normal XMLHttpRequest
			xml = new XMLHttpRequest();
		}
	}
	return xml;
}

function getAjaxResponseByPost(url,queryString, format,callbackFunction, populatingObj,isAsync){
	
	var xml = getXMLHttpRequest();
		
	if(isAsync==undefined)	{
   		isAsync="true";
   	}	
	xml.open("POST", url, isAsync);
	xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
  	xml.onreadystatechange = function() {
		if (xml.readyState == 4) {
			 if(format == "XML") {
	 			 callbackFunction(xml.responseXML, populatingObj);  				
	 		 }
	 		 else if(format == "TEXT"){
		 		callbackFunction(xml.responseText, populatingObj);  				
	         }
	 		 else if(format == "JASON"){
			 	try {
					evaluateed = eval('(' + xml.responseText + ')');
					callbackFunction(evaluateed, populatingObj);
				}catch(e){
					doLogin();
				}
	         }
		     else{
				alert("Doesn't support");				
			 }
		}
	}
	xml.send(queryString); 
}

function keyHandling(e) {
	var pKey = e.keyCode;
	if (pKey == 13){
		doLogin();
	}
}
		
// Replaces all occurences of a character with its encoded value within given string.
function escapeChar(unescapedString, escapeChar){
	// unescapedString - String from which character is to be encoded, escapeChar - character which is to be encoded
	splitStr = new Array()
	splitStr = unescapedString.split(escapeChar)
	return splitStr.join(encodeURIComponent(escapeChar));
}

function doLogin(){
	$('fs-login-error-div').style.display = "none";
	var username = $('fs-login-username');
	var password = $('fs-login-password');
	if(username.value.length < 1) {
        username.style.backgroundColor = "#ffd6d6";
        username.focus();
        return false;
    }else if(password.value.length < 1) {
        password.style.backgroundColor = "#ffd6d6";
        password.focus();
        return false;
    }else{
		$('fs-login-mask-div').style.display = "block";
		$('fs-login-loading-div').style.display = "block";
    	username.style.backgroundColor = "#ffffff";
    	password.style.backgroundColor = "#ffffff";
		var url='/pol/authenticateFSAction';
		// replace all occurences of '%' char with its encoded value
		var escapePercent = escapeChar(password.value, "%");
		
		// replace all occurences of '&' char with its encoded value
		var escapeAmp = escapeChar(escapePercent, "&");
		
    	// replace all occurences of '+' char with its encoded value
		var escapePlus = escapeChar(escapeAmp, "+");

		var queryString = 'system=pol&actiontype=UserLogin&username='+username.value+'&password='+escapePlus;
		getAjaxResponseByPost(url,	queryString, "JASON",	handleLogin, "",	true);
    }
}

function handleLogin(responseObj, element){
	$('fs-login-config-message').style.display = "none";
	if(responseObj.loginStatus == true || responseObj.loginStatus == "true"){
		$("loading-msg").innerHTML = $w("login","fs.login.successfully");
		$("fs-initialise-logonid").value = responseObj.loginId;
		initConfigCheck();
	}else{
		$('fs-login-error-div').style.display = "inline";
		$('fs-login-mask-div').style.display = "none";
		$('fs-login-loading-div').style.display = "none";
	}
}

function initialiseWorkspace(){
	$("fs-initialise-form").submit();
}

function showForgotPassword(){
	var displayStyle = $('fs-login-forgot-password-div').style.display;
	if(displayStyle && displayStyle == "inline"){
		$('fs-login-forgot-password-container').style.borderWidth = '0px';
		$('fs-login-forgot-password-container').style.borderStyle = 'solid';
		$('fs-login-forgot-password-container').style.borderColor = '#225588';
		$('fs-login-forgot-password-div').style.display = 'none';
		$('fs-forgot-error-div').style.display = "none";
	}else{
		$('fs-login-forgot-password-container').style.borderWidth = '1px';
		$('fs-login-forgot-password-container').style.borderStyle = 'solid';
		$('fs-login-forgot-password-container').style.borderColor = '#225588';
		$('fs-login-forgot-password-div').style.display = 'inline';
	}
}

function doForgotPassword(){
	$('fs-login-error-div').style.display = "none";
	$('fs-forgot-error-div').style.display = "none";
	var userEmail = $('fs-login-forgot-email');
	if(!isEmail(userEmail)) {
        userEmail.style.backgroundColor = "#ffd6d6";
        userEmail.focus();
        return false;
    }else{
    	userEmail.style.backgroundColor = "#ffffff";
    	var url="/pol/user/CreateUserPasswordFSAction";
		var queryString = 'languageCode=' + languageCode + '&emailAddress='+ userEmail.value;
		getAjaxResponseByPost(url,	queryString, "JASON",	handleForgotPass, userEmail,	true);
    }
}

function handleForgotPass(responseObj, element){
	var forgotErrorDiv = $('fs-forgot-error-div');
	if(responseObj.success == true){
		$("fs-initialise-logonid").value = responseObj.loginId;
		forgotErrorDiv.innerHTML = responseObj.errorMessage;
		forgotErrorDiv.style.color = "#000000";
		forgotErrorDiv.style.display = "inline";
	}else{
		forgotErrorDiv.innerHTML = responseObj.errorMessage;
		forgotErrorDiv.style.color = "#ff0000";
		forgotErrorDiv.style.display = "inline";
	}
}

function trimSpaces(string){
    var startPos=0;
    while(startPos<string.length && string.charAt(startPos)==' '){
        startPos++;
    }
    var endPos=string.length-1;
    while(endPos>=startPos && string.charAt(endPos)==' '){
        endPos--;
    }
    return string.substring(startPos,endPos+1);
}

function isEmail(email){
    if (email.value) {
	   email = email.value; 
       // validation is for " @ " and " . " only & not for "whitespace".
       matchEmail = /^[^@]+@[^@]+\.[^@]+$/; 
       // trimming of the string.
       email = trimSpaces(email);   
        // validation is for 'whitepace' not to be there
        if( email.indexOf(" ") != -1 ) {
        	return false;
        }
        // validation is for ' not to be there
        if( email.indexOf("'") != -1 ) {       
        	return false;
        }
        // validation is for "  not to be there   
        if( email.indexOf("\"") != -1 ) {       
        	return false;
        }
         // validation is for ,  not to there 
         if( email.indexOf(",") != -1 ) {       
         	return false;
         }
         // validation is for !  not to be there
         if( email.indexOf("!") != -1 ) {       
         	return false;
         }
         // validation is for ?  not to be there
         if( email.indexOf("?") != -1 ) {       
         	return false;
         }
         // validation is for ; last check
         if( email.indexOf(";") != -1 ) { 
         	return false;
         }      
         return matchEmail.test(email);
     }   
}


	function initConfigCheck(){
		$('fs-login-config-div').innerHTML = "";
		$('fs-login-config-div').innerHTML = '<iframe name="main" src="/resources/jsps/pol/login/config_check.jsp" frameborder=0 border=0 marginheight=0 marginwidth=0 scrolling=no height=1 width=1 />';
	}
