var pass, login, page, base;
function hbcrl_init(dest, baseURL)	{
	login=document.getElementById("login").value;
	var passobj=document.getElementById("password");
	page=dest;
	base=baseURL;

	if(!login)	{
		alert("Please enter login");
		return false;
	}
	if(!(passobj && passobj.value))	{
		alert("Please enter password");
		return false;
	}

	pass=sha1Hash(passobj.value, false);

	//	send login = request challenge
	setData(baseURL+"/user/login/?login="+login, "POST", "", "", hbcrl_get_challenge);
	setSubmitState(false);
	return false;
}

function setData(url, method, content, headers, handler, param)	{
	if(url)	{
        if(window.ActiveXObject)
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        else
			xmlhttp = new XMLHttpRequest();

        xmlhttp.open(method, url);
        if(handler!=null)
			xmlhttp.onreadystatechange= function () {handler(xmlhttp, param); };
	    if (headers) {
	        for (var key in headers) {
	            xmlhttp.setRequestHeader(key, headers[key]);
	        }
	    }

        xmlhttp.send(content);
	}
}

//	process challenge
function hbcrl_get_challenge(xmlhttp)	{
	if(xmlhttp.readyState==4)	{
		if(xmlhttp.status==200)	{
			//	final hash = hash ( hash( plain password ) + challenge )
			var h_pass=sha1Hash(pass+xmlhttp.responseText, true);

			//	send hash
			setData(base+"/user/login/?login="+login+"&hash="+h_pass, "POST", "", "", hbcrl_get_auth);
		}
		else	{
			window.status="Error "+xmlhttp.status+" during challenge request: "+xmlhttp.statusText;
			// Although we should have generic text for both wrong username and password, it is still possible to detect
			// which one isn't correct by debugging JavaScript.
			alert("Error during authentication: This username doesn't exists.");
			setSubmitState(true);
		}
	}
}
function hbcrl_get_auth(xmlhttp)	{
	if(xmlhttp.readyState == 4)	{
		if(xmlhttp.status == 200)	{
			window.location=page;
		}
		else	{
			window.status="Error "+xmlhttp.status+" during authentication: "+xmlhttp.statusText;
			alert("Error during authentication: You entered wrong password.");
			setSubmitState(true);
		}
	}
}

function setSubmitState(active)	{
var button=document.getElementById("loginsubmit");
	if(!button)
		return;
	button.value = active ? "Login" : "Submitting data...";
	button.disabled = !active;
}