
//Requires jquery.cookie.js
//Requires sendOpCommand.php
//Requires webtoolkit.md5.js

//'front', 'operatus', or 'enterprise'
var source;

function handleLogin(sourcePage)
{	
	//console.log("Call to handleLogin...");
	
	
	source = sourcePage;
	
	$("#badAccount").hide();
	$("#badInfo").hide();
	
	//Retrieve record for person.
	var emailStr = $("#username").val()
	var passStr = $("#password").val();
	
	if( emailStr!="" && passStr!="")
	{
		var queryString = "userID="+emailStr+"&commandID=fetchpersonrecord";
	
		if(source=="front")
		{
			$.ajax( {type:"POST", url:"./php/sendOpCommand.php", data:queryString, dataType:"xml", success:function(msg){handleIDCallback(msg);}} );
		}
		else if(source=="operatus")
		{
			$.ajax( {type:"POST", url:"../php/sendOpCommand.php", data:queryString, dataType:"xml", success:function(msg){handleIDCallback(msg);}} );
		}
		else if(source=="enterprise")
		{
			$.ajax({type:"POST", url:"../php/sendOpCommand.php", data:queryString, dataType:"xml", success:function(msg){handleIDCallback(msg);}});
		}
	}

}

function handleIDCallback(data)
{	
	//console.log("Call to handleIDCallback...");
	var personText = $(data).find('person').text();
	
	if(personText!="NONE")
	{
		//If account is present, check if password matches
		var givenPass = $("#password").val();
		var passHash = MD5(givenPass);
		
		var passHashOnRecord = $(data).find('password').text();
		
		if(passHash == passHashOnRecord)
		{
			//If so, then set cookies, and direct them to home.
			var email = $("#username").val();
			$.cookie('user', email, {path:'/'});
			$.cookie('operatusAuthenticate', "yes", {path:'/'});
			
			if(source=="front")
				document.location = "./operatus/home/";
			else if(source=="operatus")
				document.location = "./home/";
			else if(source=="enterprise")
				document.location = "../operatus/home/";
		}
		else
		{
			//Throw up "incorrect password" error screen
			$("#badInfo").show();
		}
		
	}
	else
	{
		//Else throw up "no such user" error screen.
		$("#badAccount").show();
	}
	
}