function sendLoginParam(provider) {
	// window.location = window.location.protocol + "//" + window.location.host+
	// "/?provider=" + provider;
	var location = window.location + "";
	if (location.indexOf('login.html') != -1) {
		location = window.location.protocol + "//" + window.location.host;
	} else if (location.indexOf('/app/') != -1) {
		location = window.location + "";
	} else if (location.indexOf('/app') != -1) {
		location = window.location.protocol + "//" + window.location.host;
	}
	var defaultApplication = "";
	if (location.indexOf("crm") != -1) {
		defaultApplication = "crm";
	} else {
		defaultApplication = "sis";
	}
	if (location.indexOf("/app/") + 5 == location.length) {
		document.getElementById('errormessage').innerHTML = 'Kindly specify valid application name in URL.';
		document.getElementById('errormessage').style.display = 'block';
		return;
	}
	if (location.indexOf("/app/") == -1) {
		location = window.location.protocol + "//" + window.location.host
				+ "/app/" + defaultApplication;
	}
	var appName = location.substring(location.indexOf("/app/") + 5,
			location.length);
	var url = "/user/managenewuser";
	var args = "_validate_application_=" + appName;
	isApplicationExist(url, args, location, provider);
	// window.location = location + "/?provider=" + provider;
}

function submitLocation(str, location, provider) {
	if (str == null || str == "") {
		window.location = location + "/?provider=" + provider;
	} else {
		document.getElementById('errormessage').innerHTML = str;
		document.getElementById('errormessage').style.display = 'block';
	}

}

function isApplicationExist(url, args, location, provider) {
	var xmlHttp;
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert("Your browser does not support XMLHTTP!");
		return;
	}
	xmlHttp.open("POST", url, true);
	xmlHttp.setRequestHeader("Content-type",
			"application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", args.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			var statusText = xmlHttp.statusText;
			var str = xmlHttp.responseText;
			submitLocation(str, location, provider);
		}
	}
	xmlHttp.send(args);
}

function login() {
	var username = document.getElementById('emailid');
	var password = document.getElementById('password');
	var errorMsgField = document.getElementById('errormessage');
	var errorMessage = 'Field can not be left blank.';
	document.getElementById('sendmail').style.display = 'none';
	errorMsgField.style.display = 'none';
	clearBorder(username);
	clearBorder(password);
	var isUsernameValid = false;
	if (validateField(username, errorMsgField, errorMessage)) {
		isUsernameValid = validateEmailid(username, errorMsgField);
	}
	var isPasswordValid = false;
	if (isUsernameValid) {
		isPasswordValid = validateField(password, errorMsgField, errorMessage);
	}
	if (isPasswordValid) {
		signIn();
	}
}

function validateField(field, errorMsgField, msg) {
	if (field.value == null || field.value == '') {
		showErrorBorder(field);
		errorMsgField.style.display = 'block';
		errorMsgField.innerHTML = msg;
		return false;
	} else {
		errorMsgField.style.display = 'none';
		return true;
	}
}

function validateEmailid(emailidField, errorMsgField) {
	var pattern = /[\w]+((.|-)[\w]+)*@[\w-]+(.[\w-]+)+/;
	var valid = (pattern.test(emailidField.value));
	if (!valid) {
		showErrorBorder(emailidField);
		errorMsgField.style.display = 'block';
		errorMsgField.innerHTML = 'Emailid you entered is incorrect.';
		return false;
	} else {
		return true;
	}
}

function showErrorBorder(field) {
	field.style.border = '1px solid red';
}
function clearBorder(field) {
	field.style.border = '1px solid #7F9DB9';
}

function checkLoginError(str) {
	if (str == null) {
		return;
	}
	if (str == 'login=true') {
		// window.location = window.location.protocol + "//"+
		// window.location.host + "/app";
		document.loginform.action = window.location.protocol + "//"
				+ window.location.host + "/app";
		document.forms["loginform"].submit();
	} else if (str.indexOf("<title>404") != -1) {// handling if user already
		// loged in and try to login
		// again using login.html
		document.loginform.action = window.location.protocol + "//"
				+ window.location.host + "/app";
		document.getElementById('errormessage').innerHTML = 'This user already login in this browser';
		document.forms["loginform"].submit();
	} else if (str.indexOf('applanebrowserui.nocache.js') != -1) {// temporary
		// window.location = window.location.protocol + "//"+
		// window.location.host;
		document.loginform.action = window.location.protocol + "//"
				+ window.location.host;
		document.forms["loginform"].submit();
	} else if (str == 'login=false') {
		document.getElementById('errormessage').style.display = 'block';
		document.getElementById('errormessage').innerHTML = 'Incorrect username or password';
		document.getElementById('signin').disabled = false;
		document.getElementById('password').value = '';
	} else if (str == 'activate=false') {
		document.getElementById('sendmail').style.display = 'block';
		document.getElementById('errormessage').style.display = 'block';
		document.getElementById('errormessage').innerHTML = 'Account need to be verified';
		document.getElementById('signin').disabled = false;
	} else if (str == 'mailsent=true') {
		// window.location = window.location.protocol + "//"+
		// window.location.host + '/status.html';
		document.loginform.action = window.location.protocol + "//"
				+ window.location.host + '/status.html';
		document.forms["loginform"].submit();
	} else if (str == 'mailsent=false') {
		document.getElementById('errormessage').style.display = 'block';
		document.getElementById('errormessage').innerHTML = 'Invalid request';
		document.getElementById('signin').disabled = false;
		document.getElementById('password').value = '';
	} else if (str == 'regrets') {
		document.getElementById('errormessage').style.display = 'block';
		document.getElementById('errormessage').innerHTML = 'Something unexpected took place at server, we are looking into the issue';
		document.getElementById('signin').disabled = false;
	}
	document.getElementById('signin').disabled = false;
}

function showProviderIcons() {
	var domainbox = document.getElementById('domainbox');
	domainbox.style.display = 'none';
	var backtologinlink = document.getElementById('backtologinlink');
	backtologinlink.style.display = 'none';
	var iconpanel = document.getElementById('iconpanel');
	iconpanel.style.display = 'block';
}

function showDomainBox() {
	var domainbox = document.getElementById('domainbox');
	domainbox.style.display = 'block';
	var backtologinlink = document.getElementById('backtologinlink');
	backtologinlink.style.display = 'block';
	var iconpanel = document.getElementById('iconpanel');
	iconpanel.style.display = 'none';
	document.getElementById('domainname').focus();
}

function validateDomainValue() {
	var domainname = document.getElementById('domainname');
	var errorMsgfield = document.getElementById('domainnameerror');
	var errorMessage = 'Domain name can not left blank';
	errorMsgfield.style.display = 'none';
	clearBorder(domainname);
	var ifValid = validateField(domainname, errorMsgfield, errorMessage);
	var domainstring = domainname.value;
	if (ifValid) {
		var wwwstr = domainstring.match("www");
		var domainsep = domainstring.match("\\.");
		if (wwwstr != null || domainsep == null) {
			// alert('Domain name is invalid...please enter domain name like
			// yourdomain.com');
			domainname.value = '';
			domainname.focus();
			errorMsgfield.style.display = 'block';
			errorMsgfield.innerHTML = 'Domain name is invalid...please enter <br/>domain name like yourdomain.com.'
		} else {
			window.location = window.location.protocol + "//"
					+ window.location.host + "/?domainName=" + domainname.value;
		}
	}
}

function sendMail() {
	var url = "/user/activatemail";
	var args;
	args = 'emailid=' + document.getElementById('emailid').value;// emailid
	args += '&password=' + document.getElementById('password').value;
	args += '&sendmail=true';
	callServlet(url, args);
}

function checkKey(e, id) {
	var keynum;
	if (window.event) // IE
	{
		keynum = e.keyCode;
	} else if (e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which;
	}
	if (keynum == 13) {
		// var field = document.getElementById(id);
		// field.focus();
		// field.click();
		login();
	}
}

function callServlet(url, args) {
	var xmlHttp;
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert("Your browser does not support XMLHTTP!");
		return;
	}
	xmlHttp.open("POST", url, true);
	xmlHttp.setRequestHeader("Content-type",
			"application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", args.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			var statusText = xmlHttp.statusText;
			var str = xmlHttp.responseText;
			if (xmlHttp.statusText == 'Internal Server Error') {
				var errorMessage = 'Exception from server';
				if (str != null && str.trim().length > 0) {
					var startIndex = str.indexOf("@exst@");
					var endIndex = str.indexOf("@exen@");
					var length = endIndex - startIndex - 6;
					var msg = str.substr(startIndex + 6, length);
					errorMessage += msg.trim().length > 0 ? '[' + msg + ']'
							: '[' + str + ']';
				}
				alert(errorMessage);
			}
			responseReceived(str);
		}
	}
	xmlHttp.send(args);
}

function responseReceived(responseText) {
	checkLoginError(responseText);
}

function signIn() {
	var url = "/authenticate";
	var args;
	args = 'emailid=' + document.getElementById('emailid').value// emailid
	args += '&password=' + document.getElementById('password').value; // orgname
	document.getElementById('signin').disabled = true;
	callServlet(url, args);
}

function GetXmlHttpObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else {
		try {
			return new ActiveXObject('MSXML2.XMLHTTP.3.0');
		} catch (e) {
			return new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
}

function createNewUser() {
	var location = window.location + "";
	if (location.indexOf('login.html') != -1) {
		location = window.location.protocol + "//" + window.location.host;
	} else if (location.indexOf('/app/') != -1) {
		location = window.location + "";
	} else if (location.indexOf('/app') != -1) {
		location = window.location.protocol + "//" + window.location.host;
	}
	var defaultApplication = "";
	if (location.indexOf("crm") != -1) {
		defaultApplication = "crm";
	} else {
		defaultApplication = "sis";
	}
	if (location.indexOf("/app/") + 5 == location.length) {
		document.getElementById('errormessage').innerHTML = 'Kindly specify valid application name in URL.';
		document.getElementById('errormessage').style.display = 'block';
		return;
	}
	if (location.indexOf("/app/") == -1) {
		location = window.location.protocol + "//" + window.location.host
				+ "/app/" + defaultApplication;
	}
	var appName = location.substring(location.indexOf("/app/") + 5,
			location.length);
	var url = window.location.protocol + "//" + window.location.host
			+ "/user/generalusersignup?"
			+ 'applane_native_signup=true&__application_name__=' + appName;
	window.location = url;
	// document.getElementById('crnhrf').href=url;
}
