var httpRequest = false;

function ajax_signup(username, password, p_verify, email) {
	
	if (username === undefined) {
		username = "signup_user";
	}
	if (password === undefined) {
		password = "signup_pass";
	}
	if (p_verify === undefined) {
		p_verify = "signup_p_verify";
	}
	if (email === undefined) {
		email = "signup_email";
	}
	
	hidediv("new_user_fail");
	hidediv("no_user");
	hidediv("no_pass");
	hidediv("no_p_verify");
	hidediv("no_pass_match");
	hidediv("no_email");
	hidediv("incorrect_email");
	hidediv("user_already_exists");
	hidediv("email_already_exists");
	var verify = true;
	
	var email_filter  = /[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
	if (document.getElementById(password).value === "") {
		showdiv_inline("no_pass");
		document.getElementById(password).focus();
		verify = false;
	}
	else if (document.getElementById(p_verify).value === "") {
		showdiv_inline("no_p_verify");
		document.getElementById(p_verify).focus();
		verify = false;
	}
	else if (document.getElementById(password).value != document.getElementById(p_verify).value) {
		showdiv_inline("no_pass_match");
		document.getElementById(password).value = "";
		document.getElementById(p_verify).value = "";
		document.getElementById(password).focus();
		verify = false;
	}
	if (document.getElementById(email).value === "") {
		showdiv_inline("no_email");
		document.getElementById(email).focus();
		verify = false;
	}
	else if (!email_filter.test(document.getElementById(email).value)) {
		showdiv_inline("incorrect_email");
		document.getElementById(email).focus();
		verify = false;
	}
	if (document.getElementById(username).value === "") {
		showdiv_inline("no_user");
		document.getElementById(username).focus();
		verify = false;
	}

	if(!verify) {
		return false;
	}
	
	var params = "user=" + encodeURI( document.getElementById(username).value ) +
				"&email=" + encodeURI( document.getElementById(email).value ) +
				"&pass=" + encodeURI( sha1Hash(document.getElementById(password).value) ) +
				"&p_verify=" + encodeURI( sha1Hash(document.getElementById(p_verify).value) );
	var url = "ajax/a_new_user.php";
	var mime = "application/json";
	
	var httpRequest = 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) {
				//alert(httpRequest.responseText);
				if(httpRequest.responseText != "NULL") {
					if(httpRequest.responseText == "User Exists") {
						showdiv("user_already_exists");
						document.getElementById(username).focus();
					}
					else if (httpRequest.responseText == "Email Exists") {
						showdiv("email_already_exists");
						document.getElementById(email).focus();
					}
					else {
						oll_user = eval("(" + httpRequest.responseText + ")");
						document.getElementById("nav_user_name").innerHTML = oll_user.login;
						document.getElementById("nav_user_points").innerHTML = oll_user.rewards;
						document.getElementById(username).value = "";
						document.getElementById(email).value = "";
						document.getElementById(p_verify).value = "";
						document.getElementById(password).value = "";
						hidediv("nav_logged_out");
						showdiv_inline("nav_logged_in");
						hidediv("signup_form");
						showdiv("signup_thanks");
						login_cleanup();
						
						// show their profile to the new user?
						new_location = "page.php?page=profile&id=" + oll_user.id;
						//alert(new_location);
						window.location.replace( new_location );
					}
				}
				else {
					showdiv_inline("new_user_fail");
				}
			}
			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;
}