var httpRequest = false;
var prefix = "";
var oll_user = 0;

function ajax_login(username_id, password_id, set_prefix) {

	standard = false;
	if (username_id === undefined) {
		username_id = "login_user";
		standard = true;
	}
	if (password_id === undefined) {
		password_id = "login_pass";
	}
	if (set_prefix === undefined) {
		prefix = "";
	}
	else {
		prefix = set_prefix;
	}
  
	var verify = true;
	
	var cur_time = "" + (new Date()).getTime();
	cur_time = cur_time.substr(0,cur_time.length-3);
	
	var params = "user=" + encodeURI( document.getElementById(username_id).value ) +
				"&pass=" + encodeURI( sha1Hash(sha1Hash(document.getElementById(password_id).value) + "" + cur_time) ) +
				"&time=" + cur_time;
	var url = "ajax/a_user_login.php";
	var mime = "application/json";
	
	hidediv("no_login_user");
	hidediv("no_login_pass");
	hidediv("login_try_again");
	
	if (document.getElementById(username_id).value === "") {
		showdiv_inline(prefix + "no_login_user");
		document.getElementById(username_id).focus();
		verify = false;
	}
	else if (document.getElementById(password_id).value === "") {
		showdiv_inline(prefix + "no_login_pass");
		document.getElementById(password_id).focus();
		verify = false;
	}
	
	if (!verify) {
		return false;
	}
	
	if (window.XMLHttpRequest) {
		httpRequest = new XMLHttpRequest();
		if (httpRequest.overrideMimeType) {
			// set mime type accordingly
			httpRequest.overrideMimeType(mime);
		}
	}
	else if (window.ActiveXObject) { // IE
		try {
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {}
		}
	}
	if (!httpRequest) {
		alert('Create XMLHTTPRequest failed.');
		return false;
	}
	
	httpRequest.open('POST', url, true);
	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	//httpRequest.setRequestHeader("Content-length", params.length);
	//httpRequest.setRequestHeader("Connection", "close");
	
	httpRequest.onreadystatechange = function() {
		if (httpRequest.readyState == 4) {
			if (httpRequest.status == 200) {
				if(httpRequest.responseText != "NULL") {
					something = "(" + httpRequest.responseText + ")";
					//alert(something);
					oll_user = eval(something);
					if(typeof(oll_user) != "number")
					{
						if(standard)
						{
							document.getElementById("nav_user_name").innerHTML = oll_user.login;
							document.getElementById("nav_user_points").innerHTML = oll_user.rewards;
							document.getElementById("login_user").value = "";
							document.getElementById("login_pass").value = "";
							hidediv("login_overlay_box");
							hidediv("nav_logged_out");
							showdiv_inline("nav_logged_in");
							hidediv("login_try_again");
							hidediv("login_form");
							showdiv("login_thanks");
							login_cleanup();
						}
						else
						{
							login_cleanup();
						}
						window.location.reload();
					}
					else
					{
						showdiv_inline(prefix + "login_try_again");
						document.getElementById(prefix + "login_user").value = "";
						document.getElementById(prefix + "login_pass").value = "";
						document.getElementById(prefix + "login_user").focus();
					}
				}
				else {
					showdiv_inline(prefix + "login_try_again");
					document.getElementById(prefix + "login_user").value = "";
					document.getElementById(prefix + "login_pass").value = "";
					document.getElementById(prefix + "login_user").focus();
				}
			}
			else {
				alert(httpRequest.responseText);
				alert('Request failed.' + httpRequest.status);
			}
		}
	};
	
	httpRequest.send(params);
	return true;
}


function ajax_logout() {
	
	var params = "user=logout";
	var url = "ajax/a_user_logout.php";
	var mime = "application/json";
	
	if (window.XMLHttpRequest) {
		httpRequest = new XMLHttpRequest();
		if (httpRequest.overrideMimeType) {
			// set mime type accordingly
			httpRequest.overrideMimeType(mime);
		}
	}
	else if (window.ActiveXObject) { // IE
		try {
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {}
		}
	}
	if (!httpRequest) {
		alert('Create XMLHTTPRequest failed.');
		return false;
	}
	
	httpRequest.open('POST', url, true);
	httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	//httpRequest.setRequestHeader("Content-length", params.length);
	//httpRequest.setRequestHeader("Connection", "close");
	
	httpRequest.onreadystatechange = function() {
		if (httpRequest.readyState == 4) {
			if (httpRequest.status == 200) {
				//oll_user = false;
				hidediv("nav_logged_in");
				showdiv_inline("nav_logged_out");
				hidediv("login_thanks");
				//hidediv("signup_thanks");
				showdiv_inline("login_form");
				logout_cleanup();
				window.location.reload();
			}
			else {
				alert('Request failed.' + httpRequest.status);
			}
		}
	};
	
	httpRequest.send(params);
	return true;
}

function showdiv_inline(id) {
	//safe function to show an element with a specified id
		  
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'inline';
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = 'inline';
		}
		else { // IE 4
			document.all.id.style.display = 'inline';
		}
	}
}


// SHA1 hashing functions
// used with explicit permission
// from: http://www.movable-type.co.uk/scripts/sha1.html
// author/copyright: copyright 2002-2005 Chris Veness
// authors note: You are welcome to re-use these scripts [without any warranty express or implied] provided you retain my copyright notice and when possible a link to my website (under a LGPL license). ¤ection numbers relate the code back to sections in the [NIST 'FIPS 180-2'] standard. If you have any queries or find any problems, please contact me.
// SHA1 information: http://en.wikipedia.org/wiki/SHA-1
function sha1Hash(msg)
{
    // constants [¤4.2.1]
    var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];


    // PREPROCESSING 
 
    msg += String.fromCharCode(0x80); // add trailing '1' bit to string [¤5.1.1]

    // convert string msg into 512-bit/16-integer blocks arrays of ints [¤5.2.1]
    var l = Math.ceil(msg.length/4) + 2;  // long enough to contain msg plus 2-word length
    var N = Math.ceil(l/16);              // in N 16-int blocks
    var M = new Array(N);
    for (var i=0; i<N; i++) {
        M[i] = new Array(16);
        for (var j=0; j<16; j++) {  // encode 4 chars per integer, big-endian encoding
            M[i][j] = (msg.charCodeAt(i*64+j*4)<<24) | (msg.charCodeAt(i*64+j*4+1)<<16) | 
                      (msg.charCodeAt(i*64+j*4+2)<<8) | (msg.charCodeAt(i*64+j*4+3));
        }
    }
    // add length (in bits) into final pair of 32-bit integers (big-endian) [5.1.1]
    // note: most significant word would be ((len-1)*8 >>> 32, but since JS converts
    // bitwise-op args to 32 bits, we need to simulate this by arithmetic operators
    M[N-1][14] = ((msg.length-1)*8) / Math.pow(2, 32); M[N-1][14] = Math.floor(M[N-1][14])
    M[N-1][15] = ((msg.length-1)*8) & 0xffffffff;

    // set initial hash value [¤5.3.1]
    var H0 = 0x67452301;
    var H1 = 0xefcdab89;
    var H2 = 0x98badcfe;
    var H3 = 0x10325476;
    var H4 = 0xc3d2e1f0;

    // HASH COMPUTATION [¤6.1.2]

    var W = new Array(80); var a, b, c, d, e;
    for (var i=0; i<N; i++) {

        // 1 - prepare message schedule 'W'
        for (var t=0;  t<16; t++) W[t] = M[i][t];
        for (var t=16; t<80; t++) W[t] = ROTL(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1);

        // 2 - initialise five working variables a, b, c, d, e with previous hash value
        a = H0; b = H1; c = H2; d = H3; e = H4;

        // 3 - main loop
        for (var t=0; t<80; t++) {
            var s = Math.floor(t/20); // seq for blocks of 'f' functions and 'K' constants
            var T = (ROTL(a,5) + f(s,b,c,d) + e + K[s] + W[t]) & 0xffffffff;
            e = d;
            d = c;
            c = ROTL(b, 30);
            b = a;
            a = T;
        }

        // 4 - compute the new intermediate hash value
        H0 = (H0+a) & 0xffffffff;  // note 'addition modulo 2^32'
        H1 = (H1+b) & 0xffffffff; 
        H2 = (H2+c) & 0xffffffff; 
        H3 = (H3+d) & 0xffffffff; 
        H4 = (H4+e) & 0xffffffff;
    }

    return H0.toHexStr() + H1.toHexStr() + H2.toHexStr() + H3.toHexStr() + H4.toHexStr();
}

//
// function 'f' [¤4.1.1]
//
function f(s, x, y, z) 
{
    switch (s) {
    case 0: return (x & y) ^ (~x & z);           // Ch()
    case 1: return x ^ y ^ z;                    // Parity()
    case 2: return (x & y) ^ (x & z) ^ (y & z);  // Maj()
    case 3: return x ^ y ^ z;                    // Parity()
    }
}

//
// rotate left (circular left shift) value x by n positions [¤3.2.5]
//
function ROTL(x, n)
{
    return (x<<n) | (x>>>(32-n));
}

//
// extend Number class with a tailored hex-string method 
//   (note toString(16) is implementation-dependant, and 
//   in IE returns signed numbers when used on full words)
//
Number.prototype.toHexStr = function()
{
    var s="", v;
    for (var i=7; i>=0; i--) { v = (this>>>(i*4)) & 0xf; s += v.toString(16); }
    return s;
}