﻿function activateLoginForm()
{
	Event.observe(window, 'load', InitForm);
}

function InitForm() {
	if (typeof window.event != 'undefined')
	{
		// IE
		document.onkeydown = function() {
			var t = event.srcElement.type;
			var kc = event.keyCode;
			if (kc == 13) {
				EncodePassword();
				__doPostBack('LoginAction1$lnkbtnLogin', '');
				document.body.style.cursor = 'wait';
				return false;
			}
		}
	}
	else {
		// FireFox/Others
		document.onkeypress = function(e) {
			var t = e.target.type;
			var kc = e.keyCode;
			if (kc == 13) {
				EncodePassword();
				__doPostBack('LoginAction1$lnkbtnLogin', '');
				document.body.style.cursor = 'wait';
				return false;
			}
		}
	}
	
	if ($("LoginAction1_tbLoginName").value != '') {
		$("LoginAction1_tbPassword").focus();
	}
	else {
		$("LoginAction1_tbLoginName").focus();
	}
}

function EncodePassword() {
	var sp = $("LoginAction1_tbPassword").value;
	
	var spMd5 = hex_md5(sp);

	var challenge = $("LoginAction1_hChallenge").value;
	var a, b, c;
	var hash;
	if (challenge == "") {
		alert("Unable to generate secure password check. Please contact the system administrator.");
		return;
	}
	for (var i = 0; challenge.length < 32; i++) {
		challenge = challenge + "q" + challenge;
	}
	challenge = challenge.slice(0, 32);
	hash = "";
	for (var i = 0; i < 32; i++) {
		a = parseInt(challenge.charCodeAt(i));
		b = parseInt(spMd5.charCodeAt(i));
		c = String(a ^ b);
		hash = hash + c;
	}
	spSecure = hex_md5(hash);
	$("LoginAction1_hPasswordMd5").value = spSecure;
	$("LoginAction1_tbPassword").value = ("xxxxxxxxxxxx").slice(0, sp.length);
}

// it's a copy of the function above, but I can't get it to work with the asp.net controls, 
// the login doesn't work anymore if I refactor the EncodePassword()
function EncodePassword2(sp, challenge) {
	var spMd5 = hex_md5(sp);
	var a, b, c;
	var hash;
	if (challenge == "") {
		alert("Unable to generate secure password check. Please contact the system administrator.");
		return;
	}
	for (var i = 0; challenge.length < 32; i++) {
		challenge = challenge + "q" + challenge;
	}
	challenge = challenge.slice(0, 32);
	hash = "";
	for (var i = 0; i < 32; i++) {
		a = parseInt(challenge.charCodeAt(i));
		b = parseInt(spMd5.charCodeAt(i));
		c = String(a ^ b);
		hash = hash + c;
	}
	var spSecure = hex_md5(hash);

	return (spSecure);
}

