// js handling the login procedures

// constants
var NORMAL_STATE = 4;
var LOGIN_PREFIX = '/doLogin.php?';

// variables
var http = getHTTPObject(); // We create the HTTP Object
var hasSeed = false;
var loggedIn = false;
var seed_id = 0;
var seed = 0;
var fullname = '';
var messages = '';

// getSeed method:  gets a seed from the server for this transaction
function getSeed() {		

	// only get a seed if we're not logged in and we don't already have one
	if (!loggedIn && !hasSeed) {
		// open up the path
		http.open('GET', LOGIN_PREFIX + 'task=getseed', true);
		http.onreadystatechange = handleHttpGetSeed;
		http.send(null);
	}
}

// handleHttpGetSeed method: called when the seed is returned from the server
function handleHttpGetSeed() {
	// if there hasn't been any errors
	if (http.readyState == NORMAL_STATE) {
		// split by the divider |
		results = http.responseText.split('|');
		
		// id is the first element
		seed_id = results[0];
		
		// seed is the second element
		seed = trimAll(results[1]);
		
		// now we have the seed
		hasSeed = true;
	}
}

// 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('wholesaleUser').value;
	password = document.getElementById('wholesalePassword').value;

	if(seed == 0 || seed_id == 0) {
		alert("Can't log in, no seed");
		return;
	}

	// ignore if either is empty
	if (username != '' && password  != '') {
	
		document.getElementById('wholesaleUser').disabled = 'disabled';
		document.getElementById('wholesalePassword').disabled = 'disabled';
		
		document.getElementById('loginButton').disabled = 'disabled';
		document.getElementById('loginButton').value = 'Logging in ...';
		
		var pass_seed = hex_md5(password.toString()) + seed.toString();
		
		// compute the hash of the hash of the password and the seed
		hash = hex_md5(pass_seed);
		
		pass_seed = null;
		
		// open the http connection
		http.open('GET', LOGIN_PREFIX + 'task=checklogin&username='+username+'&id='+seed_id+'&hash='+hash, true);
		
		// where to go
		http.onreadystatechange = handleHttpValidateLogin;
		http.send(null);
	} else if(username == '') {
		alert("You must enter your username");
	} else if(password == '') {
		alert("You must enter a password");
	}
}

// handleHttpValidateLogin method: called when the validation results are returned from the server
function handleHttpValidateLogin() {
	// did the connection work?
	if (http.readyState == NORMAL_STATE) {
		// split by the pipe
		results = http.responseText.split('|');
		
		if (results[0] == 'true') {
			hasSeed = false;
			loggedIn = true;
			fullname = results[1];
			messages = '';
			
			window.location.reload(true);
			
		} else {
			messages = results[1];
		}
		
		document.getElementById('wholesaleUser').disabled = null;
		document.getElementById('wholesalePassword').disabled = null;
		document.getElementById('loginButton').disabled = null;
		document.getElementById('loginButton').value = 'Log In';
	}
}

// resetLogin method: if logged in, 'logs out' and allows a different user/pass to be entered
function resetLogin() {
	loggedIn = false;
	hasSeed = false;
}

// method that sets up a cross-browser XMLHttpRequest object
function getHTTPObject() {

	var xmlHttp;
    
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
        try {
            xmlHttp = new XMLHttpRequest();
        } catch(e) {
            xmlHttp = false;
        }
        // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                xmlHttp = false;
            }
        }
    }

	return xmlHttp;
}

function fieldFocus() {

	try {		
		getSeed();
	}
	catch (e)
	{ } // do nothing... hides an apparent firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=236791

}

function trimAll(sString) {
	while (sString.substring(0,1) == ' ') {
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ') {
		sString = sString.substring(0,sString.length-1);
	}
	
	return sString;
}

function checkEnter(e){ //e is event object passed from function invocation

	characterCode = e.keyCode; 
	
	if(characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)
		validateLogin(); //submit the form
		return true;
	} else {
		return false;
	}
}

function showLoginForm() {
				
	getSeed();
	
	var pageOverlay = document.getElementById("overlay");
	var formOverlay = document.getElementById("loginFormOverlay");
	var formDisplay = document.getElementById("formOverlayDisplay");
	var formFields = document.getElementById("formFields");
	var submitButton = document.getElementById("submitButton");

	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	
	var formHeight = 275;
	var formWidth = 375;
	
	pageOverlay.style.display = 'block';
	formOverlay.style.display = 'block';
	pageOverlay.style.height = (arrayPageSize[1] + 'px');
	
	// center form and make sure that the top and left values are not negative
	var formTop = arrayPageScroll[1] + ((arrayPageSize[3] - formHeight) / 2);
	var formLeft = (arrayPageSize[0] - formWidth) / 2;
	
	formOverlay.style.top = (formTop < 0) ? "0px" : formTop + "px";
	formOverlay.style.left = (formLeft < 0) ? "0px" : formLeft + "px";

	formOverlay.style.width = formWidth + 'px';
	formOverlay.style.height = formHeight + 'px';
	
	formDisplay.style.width = (formWidth - 20) + 'px';
	formDisplay.style.height = (formHeight - 4) + 'px';
	formFields.style.height = (formHeight - 60) + 'px';
	
	formFields.style.overflow = "auto";
	document.getElementById("wholesaleUser").value = "";
	document.getElementById("wholesalePassword").value = "";
	document.getElementById("wholesaleUser").focus();
}

function closeLoginForm() {
	var pageOverlay = document.getElementById("overlay");
	var formOverlay = document.getElementById("loginFormOverlay");
	
	document.getElementById("wholesaleUser").value = "";
	document.getElementById("wholesalePassword").value = "";
		
	pageOverlay.style.display = 'none';
	formOverlay.style.display = 'none';
	formOverlay.style.width = '0px';
	formOverlay.style.height = '0px';
}