var login = {
	start: function() {
		var xmlhttp = null;
		if(window.XMLHttpRequest) {
			xmlhttp = new XMLHttpRequest();
		} else if(window.ActiveXObject) {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} else {
			return false;
		}
		xmlhttp.open("GET", "/static/admin/auth.jsp?action=getHash", true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				if (xmlhttp.readyState) {
					var hash = xmlhttp.responseText;
					login.logging(hash);
				}
			}
		}
		xmlhttp.send(null);
	},
	logging: function(hash) {
		if(window.XMLHttpRequest) {
			xmlhttp = new XMLHttpRequest();
		} else if(window.ActiveXObject) {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} else {
			return false;
		}
		var loginPassword = document.getElementById('loginPassword').value;
		var loginName = document.getElementById('loginName').value;
		var tmp = document.getElementById('loginForm').elements['remember'];
		var remember = null;
		for(i = 0; i < tmp.length; i++) {
			if(tmp[i].checked) {
				remember = tmp[i].value;
			} 
		}
		
		url = "/static/admin/auth.jsp";
		params = "action=auth&hash=" + hex_md5(hash + hex_md5(loginPassword)) + loginName + "&remember=" + remember;
		xmlhttp.open("POST", url, true);
		
		//Send the proper header information along with the request
		xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlhttp.setRequestHeader("Content-length", params.length);
		xmlhttp.setRequestHeader("Connection", "close");
		
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				if (xmlhttp.readyState) {
					var rsp = xmlhttp.responseText;
					if(rsp) {
						alert(rsp.replace(/\\n/gi,"\n"));
					}
					if(location.pathname.match('/logout')) {
						location.pathname = "/";
					} else {
						location.reload();
					}
					
				}
			}
		}
		xmlhttp.send(params);  
	}
}

function submitenter(myfield, e) {
	var keycode;
	if (window.event)
		keycode = window.event.keyCode;
	else if (e)
		keycode = e.which;
	else
		return true;
	if (keycode == 13) {
		login.start();
		return false;
	} else
		return true;
}

