// js handling the login procedures

// constants
var NORMAL_STATE = 4;
var LOGIN_PREFIX = 'login.php';

// variables
var http = getHTTPObject(); // We create the HTTP Object
var loggedIn = false;
var messages = 'Please wait. Loading...';



// validateLogin method: validates a login request
function validateLogin()
{
 
	// ignore request if we are already logged in
	if (loggedIn)
		return;

	// get form form elements 'username' and 'password'
	username = document.getElementById('username').value;
	password = document.getElementById('password').value;

	// ignore if either is empty
	if (username != '' && password  != '') {
		// compute the hash of the hash of the password and the seed
		hash = hex_md5(password);
		
		// open the http connection
		http.open('post', LOGIN_PREFIX, true);
		http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		// where to go
		http.onreadystatechange = handleHttpValidateLogin;
		http.send('task=checklogin&username='+username+'&hash='+hash);
	}
}

// handleHttpValidateLogin method: called when the validation results are returned from the server
function handleHttpValidateLogin()
{

	// did the connection work?
	if (http.readyState == NORMAL_STATE) {
		if (http.status == 200) {
			// split by the pipe
			results = http.responseText.split('|');
			
			if (results[0] == 'true')
			{
				loggedIn = true;
				messages = results[1];
				
				document.form2.username.blur();
				document.form2.password.blur();
				
				document.form2.submit();
			}
			else
			{
				if(results[1])	{
					messages = results[1];
				}
				else {
					messages = 'Please wait. Loading...';
				}
			}
			showLogin();
		}
		else	{
			messages = 'ERROR: Cannot complete request!';
		}
	}
}
