/*
'Author					: Stefan Kruger
'Date Created			: 09-Dec-2005
'Last Changed by		: Stefan Kruger
'Date Last Changed		: 15-Dec-2006
'Version				: 1.0.15122006
'Comments/Changes:
'Date:			Person:					Desc:
'------------------------------------------------------------------------------------------------------
'09-Dec-2005	Stefan Kruger			Created file
'23-Dec-2005	Stefan Kruger			Added custom homepage loading
'15-Dec-2006	Stefan Kruger			Fixed content hiding.

'ToDo List:
'Date:			Person:					Desc:
'------------------------------------------------------------------------------------------------------
*/

//////////////////////////////////////////////////////////////////////////////////////////////
//PREDEFINED USER FUNCTIONS USED IN THE POST-LOADING OF LOGIN
//////////////////////////////////////////////////////////////////////////////////////////////
/*
This function is called on successful finish of an actual login to check for login success or failure
*/
var loginChecker = function (oXML,outputDiv) 
{

    // DEBUG
    //   prompt('iets',oXML.responseText);
    //   return;
    // DEBUG
    
	var retar = new Array();
	retar = (oXML.responseText).split("^||^");;
	
	//prompt('text',retar);
	//return;
	if (retar.length) {
	
	//document.write (oXML.responseText)
	//alert (oXML.responseText);
	//return;
		
		if (retar.length == 6) {
			//Valid login
			if (parseInt(retar[0]) == 1){
				logInUser(retar[4]);
			}
			//Invalid login
			else {
				//showLogin();
				//getMessageBox(retar[1],retar[2],'topcontent');
				alert (retar[2]);
			}
		}
		else {
			alert("Invalid length of login verification data returned.");
		}
	}
	else {
		alert ("Empty login verification data returned.");
	}
	hideLoading();
	oXML = null;
};

/*
This function is used when displaying a loaded login page
*/
var completedLoginLoad = function (oXML,outputDiv) {
	var display = pageLoadChecker(oXML,outputDiv);
	display = oXML.responseText;
	if (display) {
		outputDiv.innerHTML = display;
	}
	hideLoading();
	display = null;
	oXML = null;
	//Focus fixer.
	/*if (document.getElementById("frmLogin").username.value == "") {
		//document.getElementById("frmLogin").username.focus();
	}
	else {
		//document.getElementById("frmLogin").password.focus();
	}*/
};

//////////////////////////////////////////////////////////////////////////////////////////////
//ACTUAL LOGIN FUNCTIONS
//////////////////////////////////////////////////////////////////////////////////////////////
/*
The function displaying a login page
*/

/* -- KDT - Comented out 06-sep-2007 - new function - ShowHomepageLoggedOut
function showLogin() {   
	setupHomeScreen();
	//Set up option pane
	if (document.getElementById("optionpane")) {
		document.getElementById("optionpane").style.display = "none";	
	}
}
*/

function ShowHomepageLoggedOut()
{
    setupHomeScreen();
}



/*
Batch function to process login display setup when user has been authorised
*/
function logInUser(){
	//Update login identity
    //updateLoginIdentity();
	//alert('login')
	setupHomeScreen();
}

function setupHomeScreen(){
	//Load tab menu
	//getTabMenu(true);
	//Set up default output division
	//alert('homescreen')
	getDefaultOutputDiv();
	//Load home page
	getHomePage();
}

/*
Function to retrieve and load the home page guid from cookies
*/
function updateLoginIdentity(logoutFlag) {
	if (!(logoutFlag)) {
		var loadLoginIdentity = function(oXML) {	    
			if (oXML.status == 200) {
				var identityResponse = oXML.responseText;
				if (identityResponse.length > 0) {
					try {
						//alert(identityResponse);
						document.getElementById("loginIdentity").innerHTML = "Logged in as : " + identityResponse;
					}
					catch (ex) {alert(ex.message)}
				}
				else {
					//alert("Warning : No login identity was found.");
				}
			}
			else {
				alert("Error occured while fetching login identity page.\nError code returned was : " + oXML.status);
			}
		}
		hiddenSubmit("include/actionfunctionmanager.asp","action=getloginidentity",loadLoginIdentity,0,null,null,true);
	}
	else {
		try {
			document.getElementById("loginIdentity").innerHTML = "Not logged in";
		}
		catch (ex) {}
	}
}

/*
Function to retrieve and load the home page guid from cookies
*/
function getHomePage()
{
	//alert('hi')
	var loadHome = function(oXML) 
	{	    
		if (oXML.status == 200) {
			var homeguid = oXML.responseText;
			//alert(homeguid)
			if (homeguid.length > 0) {
				//alert(homeguid);
				getPage(homeguid,"");
			}
			else {
				alert("Warning : No home page id was found. Page content may not display correctly.");
			}
		}
		else {
			alert("Error occured while fetching home page.\nError code returned was : " + oXML.status);
		}
	}
	//Hide submenu items
	contentHider();
	hiddenSubmit("include/actionfunctionmanager.asp","action=gethomeguid",loadHome,0,null,null,true);
}

/*
Batch function to process a complete logoff
If sessionExpiry is true a sessionexpired message is displayed instead of the default logoff
*/

function logOffUser(sessionExpiry){
	//Clear cookies
	//clearMemberCookie();
	//clearSupplierCookie();

	hiddenSubmit("include/logoff.asp","",null,4,null,null,false);
	//hiddenSubmit("default.asp","",null,4,null,null,false);

	//Clear content (full)
	contentHider(true);
	//Clear tab sub menu
	menuHider();
	
	//Reload homepage
    //   getHomePage();
	
	//Remove login identity
	//updateLoginIdentity(true) 
	
	//ReLoad tab menu - Not used by Kumon
	//getTabMenu(true);

	//Load home page
	getHomePage(); // problem kdt
	//setupHomeScreen();
	
	//Display message
	if (sessionExpiry) {
		//getMessageBox("Session Expired","Because of more strict security measures in place, you are unable to view any more pages.|^^|This should only happen every 24 hours or if your IP address changes.|^^|Please log in again.",defaultoutputdiv);
	}
	else {
		//getMessageBox("Logged off","You have logged off successfully.",defaultoutputdiv);
	}

	//Show login
	//showLogin(); taken out kdt - 06-sep-2007
}

/*
A function that logs off the current user and displays the session expiry message
*/
function expireSession(){
	logOffUser(true);
}

/*
This function is an entry point to either authorising a user login or mailing of password from login screen
loginOrForget = true --> login
loginOrForget = false --> mail password (for Logoff)
*/
function doLogin(loginOrForget,site){
	if (document.getElementById("frmLogin").txtEmail.value != ""){
		if (loginOrForget){
			if (document.getElementById("frmLogin").txtPassword.value != ""){
				var data = fetchInputFormData("frmLogin") + "&loginrequest=true";
				//alert(data);
				hiddenSubmit(document.getElementById("frmLogin").action,data,loginChecker,0,null,null,true);
			}
			else {
				alert("Please enter your password.");
			}
		}
		else {
			//Reset forgot pasword
			goToResetPassword(document.getElementById("frmLogin").txtEmail.value,site);
		}
	}
	else {
		alert("Please enter your email address before proceding.");
	}
	return false;
}

/*
This function calls for the mailing of a users password.
*/
function goToResetPassword(mailad) {
	var page = "include/resetpassword.asp";
	var data = "action=forgotpassword&email=" + mailad;
	genericSubmit(page,data,null,"topcontent",completedSingleLoad,regularloadingstring);
}

function checkReminderQuestion(thePage, theForm){

	var reminderReturn = function(oXML)
	{
		var returnVal = oXML.responseText;
			//alert("Auth# : " + authXML);
			regularCursor();
		if (returnVal.substr(0,5) == "ERROR" || returnVal.substr(0,5) == "Error" || returnVal.substr(0,5) == "error") 
		{
			alert(returnVal);
			//document.getElementById("topcontent").innerText = returnVal;
			return;
		}
		else 
		{
			document.getElementById("topcontent").innerHTML = returnVal;
			//alert(returnVal);
			return;
		}
		oXML = null;
	}

	if (document.getElementById("frmForgotPassword").txtAnswer.value != ""){
		var page = thePage;
		var data = "action=checkanswer" + "&" + fetchInputFormData(theForm);
		//alert (thePage);
		//return;
		//thePage
		hiddenSubmit(page,data, reminderReturn, 0, 'topcontent', null, false);
		//hiddenSubmit(page,data,whenDoneRunThis,modeDelimiter,div,postload,syncmode)
		
		//genericSubmit(page,data,null,"topcontent",completedSingleLoad,regularloadingstring);
	}
	else {
		alert("Please enter an answer before proceding.");
	}
}

function changePassword(thePage, theForm){
	var form = theForm;
		
	if (document.frmForgotPassword) {
		if (document.frmForgotPassword.txtNewPass.value.length >= 6){
			if (document.frmForgotPassword.txtNewPass.value == document.frmForgotPassword.txtConfirmPass.value){
				var updatePass = function (oXML) {
					var result = oXML.responseText.split("|^^|");
					if (parseInt(result[0]) == 1) {
						alert (result[1]);
						checkAction(58,106,1,null,false,null,false)
						//loadWelcomeScreen();
					}
					else {
						alert (result[1]);
						document.frmForgotPassword.txtNewPass.value = "";
						document.frmForgotPassword.txtConfirmPass.value = "";
						return;
					}
				}
				var page = thePage;
				var data = "action=updatepassword&userid=" + document.frmForgotPassword.userid.value + "&password=" + document.frmForgotPassword.txtNewPass.value 
				hiddenSubmit(page,data,updatePass,0,null,null,true);
				//hiddenSubmit(page,data, reminderReturn, 0, 'topcontent', null, false);
			}
			else {
				alert("The new password and confirm password values differ. Please verify that you've typed both correctly and try again.");
			}
		}
		else {
			alert("The new password needs to be at least six (6) characters in length. Please select a different password.");
		}
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////
//EVENT LISTENERS
//////////////////////////////////////////////////////////////////////////////////////////////
/*
Login password box enter press listener
*/
function checkLoginForEnter(fld,evt){
	if (isEnterKey(evt)){
		doLogin(true,"");
	}
}


function GotoLoginPage()
{

    contentHider();
    document.getElementById("topcontent").style.display = "block";

    var WriteContent = function(oXML)
    {
	    var returnVal = oXML.responseText;
		regularCursor();

	    if (returnVal.substr(0,5).toLowerCase() == "error")
	    {
		    alert(returnVal);
		    //document.getElementById("topcontent").innerText = returnVal;
		    return;
	    }
	    else 
	    {
		    document.getElementById("topcontent").innerHTML = returnVal;
		    //alert(returnVal);
		    //return;
	    }
	    oXML = null;
    }
    
    //hiddenSubmit(page,data,whenDoneRunThis,modeDelimiter,div,postload,syncmode)
	hiddenSubmit('login.asp',null, WriteContent, 0, 'topcontent', null, false);
	document.getElementById("topcontent").display = "block";

}