/* 
Web-Innova AJAX Login script
Copyright 2006 - Web-Innova, LLC
login.js
6/2006
rev 8/2006
*/
//  Initialize variables
var xmlHttp;
xmlHttp = null;
var id = null;

//  BEGIN LOGIN FUNCTIONS
//  Function to execute when login button is clicked
function login_site() {
	var check;
	var button;
	var lform;
	var msg;
	
	//  Change button text and disable
	button = document.getElementById("login_button");
	button.value = "Wait...";
	button.disabled = true;
	
	//  Check if fields contain values
	check = check_values();
	if (check == false) {
		//  If field is blank, re-enable form
		button.value = "login";
		button.disabled = false;
		return;
	} else {
		//  If okay, generate salt and proceed with login
		genSalt();
	}
	}
	
//  Function to check if login form has all the values necessary to login
function check_values() {
	var user;
	var pass;
	var msg;
	var msg_txt;
	
	//  Get values from the form
	user = document.getElementById("username");
	pass = document.getElementById("password");
	msg_txt = '';
	
	//  Check if any are empty
	if( user.value == '' )
	{
		msg_txt += "Username is missing <br />";
	}
	
	if( pass.value == '' )
	{
		msg_txt += "Password is missing";
	}

	//  If necessary display error message
	if( msg_txt != '') 
	{
		msg = document.getElementById("login_msg");
		msg.innerHTML = msg_txt;
		return false;
	}
		
	}
	
//  Function to handle when return messages for a successful or unsuccessful login
function handleSignonChange() {
	if(xmlHttp.readyState == 4) {
		if(xmlHttp.status == 200) {
			document.getElementById("login_form").innerHTML = xmlHttp.responseText;
			//window.location.reload();
		}
	}
}

//  Function to handle when return messages for a successful or unsuccessful login
function handleXMLSignonChange() {
	var response = xmlHttp.responseXML;
	var result = null;
	var type;
	var message;
	var button;
	
	if(xmlHttp.readyState == 4) {
		if(xmlHttp.status == 200) {
			//document.getElementById("login_form").innerHTML = xmlHttp.responseText;
			//alert("XML Loading...");
			//alert(response.xml);
			var login = response.getElementsByTagName("login");
			result = login[0];
			type = result.getAttribute("type");
			//alert(type);
			if(type == "error") 
			{
				//alert("Type - Error");
				//message = result.childNodes(0).firstChild.text;
				message = result.getElementsByTagName("message")[0].firstChild.nodeValue;
				//alert(message);
				document.getElementById("login_msg").innerHTML = message;
				button = document.getElementById("login_button");
				button.value = "login";
				button.disabled = false;

			} 
			if(type == "success") {
				var ln = document.getElementById("leftnav");
				var la = document.getElementById("login_area");
				var account = document.createElement('div');
				account.setAttribute('id', 'account_area');
				var welcome = document.createElement('h6');
				
				//alert("Success");
				welcome_txt = result.getElementsByTagName("welcome")[0].firstChild.nodeValue;
				var welcome_msg = document.createTextNode(welcome_txt);
				//var welcome_msg = document.createTextNode("Hello");
				welcome.appendChild(welcome_msg);
				//alert(welcome.nodeType);
				//alert(welcome_txt);
				
				var list = document.createElement('ul');
				var links = response.getElementsByTagName("link");
				//alert(links.length);
				for(var i = 0; i < links.length; i++) {
					line = links[i];

					var option = document.createElement('li');
					var href = document.createElement('a');
					url = line.getAttribute("url");
					href.setAttribute('href', url);

					if(line.getAttribute("onclick")) {
						//alert("Found onclick");
						jsclick = line.getAttribute("onclick");
						//alert(jsclick);
						//href.setAttribute('onclick', jsclick);
						//href.onclick = function() { 
							//logout();
							//return false;
							//jsclick
							//}
							href.onclick = function() { jsclick(); };
					}

					line_txt = line.firstChild.nodeValue;
					line_item = document.createTextNode(line_txt);
					href.appendChild(line_item);
					//alert(line_txt);
					
					option.appendChild(href);
					list.appendChild(option);
				}
								
				account.appendChild(welcome);
				account.appendChild(list);
				//ln.replaceChild(account, login_area);
				ln.replaceChild(account, la);
				window.location.reload();

				
			}
			
		}
	}
}

//  Function to generate salt to encrypt password when logging in
function genSalt() {
	var salt_url;
	
	//  Need to generate a unique URL to fix IE problem of caching
	salt_url = 'util/salt.php?key=' + Math.random() * Date.parse(new Date());
	
	//  Create ajax object
	createXMLHttpRequest()
	
	//  Process ajax request
	xmlHttp.open('GET', salt_url, true);
	xmlHttp.onreadystatechange = handleSalt;
	xmlHttp.send(null);
	
}

//  Function to parse the salt returned from the server to include in login URL
function handleSalt() {
	if(xmlHttp.readyState == 4) {
		if(xmlHttp.status == 200) {
			full_salt = xmlHttp.responseText.split('|');
			id = full_salt[0];
			salt = full_salt[1];
			
			// Execute the login process
			signon();
		}
	}
}

//  Function to execute the login
function signon() {
	var user;
	var pass;
	var url;
	var hash;
	
	//  Get the username/password from the login form
	user = document.getElementById("username");
	pass = document.getElementById("password");
	
	//  Generate the hash to include into the URL using the salt and user password
	hash = hex_sha1(hex_md5(pass.value) + salt);

	//  Full URL for AJAX to send to the server
	url = "util/signon.php?username=" + user.value + "&hash=" + hash + "&id=" + id;

	//  Create AJAX object
	createXMLHttpRequest();
	
	//  Process the AJAX request
	//xmlHttp.onreadystatechange = handleSignonChange;
	xmlHttp.onreadystatechange = handleXMLSignonChange;
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
	
	//document.refresh();
	
	return true;
	
}

//  END LOGIN FUNCTIONS

//  BEGIN LOGOUT FUNCTIONS
//  Function to log out and close sessions
function logout() {
	var url;
	
	//  Need to generate a unique URL to fix IE problem of caching
	url = "util/logout.php?key=" + Math.random() * Date.parse(new Date());

	//  Create AJAX object
	createXMLHttpRequest();

//  Process the AJAX request
	xmlHttp.onreadystatechange = handleLogout;
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
	
	//document.refresh();
	//window.location.reload();
	//window.location="http://vesper.web-innova.com:8001/";
	
	return true;

}

//  Function to handle the returned AJAX message after logging off
function handleLogout() {
	if(xmlHttp.readyState == 4) {
		if(xmlHttp.status == 200) {
			document.getElementById("leftnav").innerHTML = xmlHttp.responseText;
			//document.getElementById("login_form").innerHTML = xmlHttp.responseText;
			//window.location.reload();
			window.location="http://" + window.location.host;

		}
	}

}
//  END LOGOUT FUNCTIONS

//  BEGIN FORGOT PASSWORD FUNCTIONS
//  Function to make forgot password form
function forgotPass() {
	//  Initialize variables and assign parent areas
	var login_area = document.getElementById("login_area");
	var login_form = document.getElementById("login_form");
	var forgot_password = document.createElement('fieldset');
	var fsl = document.createElement('legend');
	
	//  Assign legend text
	var legend_txt = document.createTextNode('Forgot Password');
	//  Append legend text
	fsl.appendChild(legend_txt);
	
	//  Create form
	var f = document.createElement('form');
	f.setAttribute('action', 'forgot_pass.php');
	f.setAttribute('method', 'post');
	f.setAttribute('enctype', 'multipart/form-data');
	f.setAttribute('name', 'forgot_pass');
	
	//  Create field inside label tag
	var l = document.createElement('label');
	var label_txt = document.createTextNode('eMail:');
	l.htmlFor = 'email';
	l.appendChild(label_txt);
	var e = document.createElement('input');
	e.setAttribute('type', 'text');
	e.setAttribute('name', 'email');
	e.setAttribute('id', 'email');
	
	//  Create Send new password button to execute forgot password
	var b = document.createElement('input');
	b.setAttribute('type', 'submit');
	b.setAttribute('name', 'forgot_button');
	b.setAttribute('id', 'forgot_button');
	b.onclick = function() {
		resetPassword();
		return false;
		}
	b.setAttribute('value', 'Send New Password');
	
	//  Create area for return messages
	var msg = document.createElement('div');
	msg.setAttribute('id', 'login_msg');
	
	//  Generate form
	l.appendChild(e);
	f.appendChild(l);
	f.appendChild(b);
	forgot_password.appendChild(fsl);
	forgot_password.appendChild(f);
	forgot_password.appendChild(msg);

	//  Replace login form with the forgot password form
	login_area.replaceChild(forgot_password, login_form); 
	
}

//  Function to execute forgot password process
function resetPassword() {
	var user;
	var msg;
	
	//  Get email address entered into forgot password form
	user = document.getElementById("email");

	//  Generate unique URL to solve IE caching issue
	url = "util/forgot_pass.php?email=" + user.value + "&key=" + Math.random() * Date.parse(new Date());

	//  Create AJAX object
	createXMLHttpRequest();
	
	//  Process AJAX request
	xmlHttp.onreadystatechange = handlePasswordReset;
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
	
	return true;
	
}

//  Function to handle AJAX return messages after executing forgot password process
function handlePasswordReset() {
	if(xmlHttp.readyState == 4) {
		if(xmlHttp.status == 200) {
			//  Insert message on page
			document.getElementById("login_msg").innerHTML = xmlHttp.responseText;
			
			//  Set focus on email field and hightlight value
			document.forgot_pass.email.focus();
			document.forgot_pass.email,select();
		}
	}
}
		
//  END FORGOT PASSWORD FUNCTIONS

