/**
	Login Stuff
	Author: PJ Pretorius
*/

//==============================================================================
/*
	Helpful Cookie functions from W3Schools :)
*/
function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
		{
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}
//==============================================================================

/*
	This is the callback after login on the home page (main login), also sets up the username cookie
*/
function _PostLoginMainPage(Response)
{
	if(Response.main.Success!=undefined)
	{//Success!
		//Store the curren user name; expires in two days
		setCookie('username',Response.Return.username,2);
		//Check for re-directs
		if(Response.Return.trackback!=undefined)
		{
			location.href =  Response.Return.trackback;
			return false;
		}
		//Redirect to splash page
		location.href = "/dwexec/Login/SplashPage.php";
	}
	else
	{
		//report errors
		if(Response.main.errors)
		{
			var Errors = "";
			for(var ind in Response.main.errors)
			{
				Errors +=(Response.main.errors[ind].error)+"\n";
			}
			alert(Errors);
		}
	}	
}

/*
	callback after login for the re-login generated form
*/
function _PostLogin(Response)
{
	if(Response.main.Success!=undefined)
	{
		$('.Re_LoginBox').remove();
		//any child of the body which should not be shown upon successful re-login, should have the class 'LoginNoUnhide'
		$('body').children(':not(.LoginNoUnhide)').show();
		ResetGlobalTimeOut();
	}
	else
	{
		//report errors
		if(Response.main.errors)
		{
			var Errors = "";
			for(var ind in Response.main.errors)
			{
				Errors +=(Response.main.errors[ind].error)+"\n";
			}
			alert(Errors);
		}
	}
}

/*
	The event handler for login forms
*/
function Login(src,MainPage)
{
	if(MainPage==undefined) var MainPage = true;
	
	if(src.tagName=="FORM")
		var srcFormName = src.name;
	else
		var srcFormName = src.form.name;
		
	//get form data and encrypt the password
	var FormData = serializeForm("theLogin");
	FormData['password'] = hex_md5("User=" + FormData['username'] + "&Pass=" + FormData['password']);
		
	if(MainPage)
		$.JQRPC('/dwexec/Login/AJAXReLogIn.php','theLoginHandler',{	formData: FormData	},_PostLoginMainPage);
	else
		$.JQRPC('/dwexec/Login/AJAXReLogIn.php','theLoginHandler',{	formData: FormData	},_PostLogin);
	
}

/*
	This functinon loads LoginHTML.php and sets up its event handlers
	Note: The SUForm
*/
function InitLoginForm()
{
	//store the URL's get variables
	var getVars = location.search;
	getVars = getVars.substr(1);//take out the '?'
	if($('#LoginBox').length>0)
	{
		$('#LoginBox').load('/dwexec/Login/LoginHTML.php',getVars,function()
		{
			//define the event handlers for the login section
			$("#theLogin").submit(function()
				{
					Login(this);
					return false;//escape submit behaviour
				});
			//SU submit doesn't always exist... so test first
			if($("#SUForm").length>0)
			{
				//define the SU submit event handler
				$("#SUForm").submit( function()
					{
						SuPost();
						return false;//escape submit behaviour
					});
			}
		});
	}
}

/*
	this function generates the html for a re-login for for when the user's session expires
*/
function MakeLoginForm()
{// this is the HARD-CODED version. Should only be called when a session expires... 
	var username = getCookie("username");
	if(username)
	{
		var HTMLText = '<div class="Re_LoginBox"><b>PEPFAR DATAWAREHOUSE: Your session has expired. You need to re-login to display this page again.</b>';
		HTMLText += '<form name="theLogin" id="theLogin">';
		HTMLText += '	Username:<br/><input type="text" name="username" style="width:82%;float:centre;overflow:hidden;" disabled="true"  value="'+username+'"><br/>';
		HTMLText += '	Password:<br/><input type="password" name="password" style="width:82%;float:centre;"><br/>';
		HTMLText += '<input type="submit" value="LogIn">';
		HTMLText += '</form></div>';
	
		return HTMLText;
	}
	else
	{
		alert('Error!:\n You cannot re-login to this page without losing all your changes... Your browser has deleted the cookie required to retain the session (Which should have been active for at least a day).\n This page will now refresh to log you in again, but any changes you made will be gone...Sorry.');
		location.href = location.href;
	}
}

//==============================================================================
//TimeOut Functions
//==============================================================================

var minRemaining = 0;

/*
	Helper to reset the global timeout.
	//== added logon check to hide timeout if logged-out
*/
function ResetGlobalTimeOut()
{
	minRemaining = GLOBALTIMEOUT;
	announceTimer();
}

/*
	This function calls the function IsLoggedIn in AJAXReLogIn.php
	If the AJAX call returns response.Return.LoginRequired, display a login form
		else if we are already logged in (response.Return.LoggedIn), just display a message saying everything is pashash.
*/
function CallLoginCheck()
{
	$.JQRPC('/dwexec/Login/AJAXReLogIn.php','IsLoggedIn',null,
		function(response)
		{
			if(response.Return.LoginRequired)
			{// Force re-login.
				if($('#theLogin').length==0)
				{
					$('body').children().hide();
					$('body').append(MakeLoginForm());
					//event handler
					$("#theLogin").submit(function()
						{
							Login(this,false);
							return false;//escape submit behaviour
						});
				}
				//$('LoginBox').innerHTML = MakeLoginForm();
			}
			else 
			{
				if(response.Return.LoggedIn)
				{
					ResetGlobalTimeOut();
					alert('You are still logged in and your session has been re-freshed. :)');
				}
				else
				{
					alert('There seems to be an issue with the server-side script (AJAXReLogIn.php)');
				}
			}
		});
}

/*
	helper to display timeout info
*/
function announceTimer()
{
	if ( typeof mm_logonUID == 'undefined')		//== While both menu systems are operational - drop clause once newMenu rolled out
	{
		$("#TimeMan").html("Timeout in " + minRemaining + " min");
		return;
	}
	if ( mm_logonUID != '')
	{
		$("#TimeMan").html("Timeout in " + minRemaining + " min");
	}
}

/*
	Function which decrements the timer and performs login checks if the timer has 1 minute to go.
*/
function decrementTimer()
{
	if ( typeof mm_logonUID == 'undefined') { return; }	//== No need if not logged in
	if ( mm_logonUID == '') { return; }		//== No need if no longer logged in.
	
	minRemaining --;
	if (minRemaining == 2)		//== Upped to 2 to allow some time to respond.
	{
		if(typeof(checkSaveRequired)=='function')//special code needed to jam with Form.php :(
			checkSaveRequired();
		var temp = window.confirm('You Are About To Timeout! Refresh This Session?');
		if (temp)
		{  // Send Refresh Here
			CallLoginCheck();
		}
		else return;		//== No sense in trying for re-login if response is No.
	}
	if (minRemaining <= 0)
	{  
		CallLoginCheck();
	}
	announceTimer();
}

/*
	Submit handler for the SU form, created by LoginHTML.php
*/
function SuPost()
{
	$.post("/dwexec/Login/Su.php" ,$("#SUForm").serialize(), function(data, textStatus)
	{
		if(data.success)
		{
			alert(data.success);
			location.href = "/";
		}
		else
			if(data.error)
				alert(data.error);
			else
				alert("Unknown error:'LoginStuff2.js'");
	}
	, "json" );
}

