var theRequest = false;

function utf8_encode ( string ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
    
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";
    var start, end;
 
    start = end = 0;
    for (var n = 0; n < string.length; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;
 
        if (c1 < 128) {
            end++;
        } else if((c1 > 127) && (c1 < 2048)) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc != null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }
    
    if (end > start) {
        utftext += string.substring(start, string.length);
    }
 
    return utftext;
}

function sha1Hash(msg)
{
    // constants [4.2.1]
    var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];


    // PREPROCESSING 
    msg = utf8_encode(msg);
    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]
    M[N-1][14] = ((msg.length-1) >>> 30) * 8;
    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);
    case 1: return x ^ y ^ z;
    case 2: return (x & y) ^ (x & z) ^ (y & z);
    case 3: return x ^ y ^ z;
    }
}


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

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;
}


function check_openid()
{
	
	openid  = document.getElementById('openid_url').value;
	page	= root_admin + "/?preaction=auth_openid&openid_url="+openid;
	
	theRequest = false;

	if(window.XMLHttpRequest)
	{
		theRequest = new XMLHttpRequest();
		if(theRequest.overrideMimeType)
		{
			theRequest.overrideMimeType('text/xml');
		}
	}
	else if(window.ActiveXObject)
	{
		try
		{
			theRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try
			{
				theRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if(!theRequest)
	{
		alert('Error: could not create XMLHTTP object.');
		return false;
	}
	
	
	theRequest.onreadystatechange = result_openid;
	theRequest.open('GET', page, true);
	theRequest.send(null);

	return false;
}

function result_openid()
	{
	if(theRequest.readyState == 4)
		{
		if(theRequest.status == 200)
			{
			//alert(theRequest.responseText);
			var res = theRequest.responseText;
			if(res == "valid")
				{
				document.openidform.submit();	
				}
			else
				{
				if(res == "no_account")
					
					document.getElementById("wrong_openid").innerHTML = "URL OpenID introuvable";
				else
					document.getElementById("wrong_openid").innerHTML = "URL OpenID erronée";
					
				document.getElementById("wrong_openid").style.display = "";
				document.getElementById("openid_url").select();
				}
			}
		}
	}
	
function check_passwd()
{
	if(!navigator.cookieEnabled) 
		{
		if (document.getElementById("cookie_disabled")) document.getElementById("cookie_disabled").style.display = "";
		//document.getElementById("login").select();
		return false;
		}

	login	= document.getElementById('login').value;
	passwd	= document.getElementById('passwd').value;

	page	= root_admin + "/";
	
	paramPost = "";
	paramPost+= "preaction=auth&hash="+sha1Hash(login+"@"+passwd);

	if (document.getElementById('url'))	paramPost+= "&url=" + document.getElementById('url').value;
	
	theRequest = false;

	if(window.XMLHttpRequest)
	{
		theRequest = new XMLHttpRequest();
		if(theRequest.overrideMimeType)
		{
			theRequest.overrideMimeType('text/xml');
		}
	}
	else if(window.ActiveXObject)
	{
		try
		{
			theRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try
			{
				theRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if(!theRequest)
	{
		alert('Error: could not create XMLHTTP object.');
		return false;
	}

	theRequest.onreadystatechange = result_passwd;
	theRequest.open('POST', page, true);
	theRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	theRequest.send(paramPost);

	return false;
}

function result_passwd()
	{
	if(theRequest.readyState == 4)
		{
		if(theRequest.status == 200)
			{
			//alert(theRequest.responseText);
			if(theRequest.responseText == "ok")
				{
				var ident = document.createElement('input');
				ident.type = 'hidden';
				ident.name = 'ident';
				ident.value = sha1Hash(document.getElementById('login').value+"@"+document.getElementById('passwd').value);
				document.loginform.appendChild(ident);

				document.getElementById('login').disabled = true;
				document.getElementById('passwd').disabled = true;
				
				document.loginform.submit();	
				}
			else if(theRequest.responseText == "okerror")
				{
				if (document.getElementById("wrong_error"))	document.getElementById("wrong_error").style.display = "";
				if (document.getElementById("wrong_login"))	document.getElementById("wrong_login").style.display = "none";
				}
			else
				{
				if (document.getElementById("wrong_error"))	document.getElementById("wrong_error").style.display = "none";
				if (document.getElementById("wrong_login"))	document.getElementById("wrong_login").style.display = "";
				
				document.getElementById("login").className+= " error";
				document.getElementById("passwd").className+= " error";
				if (document.getElementById("url"))	document.getElementById("url").className+= " error";
				if (document.getElementById("label_url"))	document.getElementById("label_url").className+= " error";
				if (document.getElementById("label_login"))	document.getElementById("label_login").className+= " error";
				if (document.getElementById("label_passwd"))	document.getElementById("label_passwd").className+= " error";
				//document.getElementById("login").select();
				}
			}
		}
	}
	
function check_send_pass()
{
	mail_login	= document.getElementById('mail_login').value;
	mail_mail	= document.getElementById('mail_mail').value;
	page	= root_admin + "/?preaction=send_pass&mail_login="+mail_login+"&mail_mail="+mail_mail;
	
	theRequest = false;

	if(window.XMLHttpRequest)
	{
		theRequest = new XMLHttpRequest();
		if(theRequest.overrideMimeType)
		{
			theRequest.overrideMimeType('text/xml');
		}
	}
	else if(window.ActiveXObject)
	{
		try
		{
			theRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try
			{
				theRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if(!theRequest)
	{
		alert('Error: could not create XMLHTTP object.');
		return false;
	}

	theRequest.onreadystatechange = result_send_pass;
	theRequest.open('GET', page, true);
	theRequest.send(null);

	return false;
}

function result_send_pass()
	{
	if(theRequest.readyState == 4)
		{
		if(theRequest.status == 200)
			{
			//alert(theRequest.responseText);
			if(theRequest.responseText == "ok")
				{
				document.getElementById("good_mail").style.display = "";
				}
			else
				{
				document.getElementById("wrong_mail").style.display = "";
				//document.getElementById("mail_login").select();
				}
				
			document.getElementById("mail_login").value = "";
			document.getElementById("mail_mail").value = "";
			}
		}
	}
	
function reset_login()
	{
	document.getElementById('wrong_login').style.display='none';	
	document.getElementById('login').className = 'input';	
	document.getElementById('passwd').className = 'input';
	}
	
function reset_mail()
	{
	document.getElementById('wrong_mail').style.display='none';
	document.getElementById('good_mail').style.display='none'
	document.getElementById('mail_mail').className = 'input';	
	document.getElementById('mail_login').className = 'input';
	}