var Login = {
	sessionTimeCount: 0,
	init: function() {
		// Delay focus in case a dialog is not yet visible
		setTimeout(function() {
			Login.timeoutDisable();
			Login.setFocus();
		}, 200);
	},

	setFocus: function() {
		var loginForm = $j('#loginForm');
		if (!loginForm[0])
			return;

		var elem;
		if (loginForm[0].vCompany.value.length == 0 && loginForm[0].vCompany.type != 'hidden' && loginForm[0].vCompany.disabled != true) {
			elem = loginForm[0].vCompany;
		} else if (loginForm[0].vLoginname.value.length == 0 && loginForm[0].vLoginname.type != 'hidden' && loginForm[0].vLoginname.disabled != true) {
			elem = loginForm[0].vLoginname;
		} else if (loginForm[0].vPassword.type != 'hidden' && loginForm[0].vPassword.disabled != true) {
			elem = loginForm[0].vPassword;
		}
		if (elem) {
			elem.focus();
			if (elem.type == 'text' || elem.type == 'password') {
				elem.select();
			}
			return;
		}
	},

	checkBrowser: function() {
		var userAgent = navigator.userAgent.toLowerCase();
		var browser = 'Unknown';
		var version = $j.browser.version;
		var validBrowser = false;
		if ($j.browser.mozilla) {
			if (userAgent.match(/firefox/)) {
				browser = 'Firefox';
				// Use the firefox version, not the "rv" tag that is in $j.browser.version
				version = userAgent.match(/firefox[\/: ]([\d.]+)/)[1];
				if (parseFloat(version) >= 2)
					validBrowser = true;
			} else {
				browser = 'Mozilla';
				if (parseFloat(version) >= 1)
					validBrowser = true;
			}
		} else if ($j.browser.msie) {
			browser = 'Internet Explorer';
			if (parseFloat(version) >= 5.5)
				validBrowser = true;
		} else if ($j.browser.opera) {
			browser = 'Opera';
			if (parseFloat(version) >= 5)
				validBrowser = true;
		} else if ($j.browser.webkit) {
			var versionArr = userAgent.match(/version[\/: ]([\d.]+)/);
			if(versionArr != null && versionArr.length >= 2) {
				version = versionArr[1];
				if (parseFloat(version) >= 1) {
					browser = 'Safari';
					validBrowser = true;
				}
			} else {
				//chrome is also consider as safari but verison match is different
				if (userAgent.match(/chrome/)) {
					//any version of chrome is valid
					//var versionArr = userAgent.match(/chrome[\/: ]([\d.]+)/);
					browser = 'Chrome';
					validBrowser = true;
				}
			}
		} else if (userAgent.match(/blackberry/)) {
			browser = 'BlackBerry';
			//sample: BlackBerry9700/5.0.0.442 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/
			//we don't know exact blackberry's agent version. so not to do version check now
			version = 'BlackBerry';
			validBrowser = true;
		}

		// Convert to a friendly name
		$j('#browser_version').html(browser + ' version ' + version);

		if ($j.browser.msie && version == 6)
			$j("#ie6BrowserWarning").show();

		if (!validBrowser) {
			// Avoid jQuery for this just in case it's not supported in the unsupported browser
			document.getElementById("browserError").style.display = "block";
		}
	},

	checkForm: function(_form, checkpwd) {
		var onError = function(form_object, input_object, object_value, error_message) {
			alert(error_message);
			if (input_object.type != 'hidden' && input_object.disabled != true)
				input_object.focus();
			return false;
		};

		if (!hasValue(_form.vCompany, "TEXT")) {
			onError(_form, _form.vCompany, _form.vCompany.value, "Company is required.");
			return false;
		}
		if (!hasValue(_form.vLoginname, "TEXT")) {
			onError(_form, _form.vLoginname, _form.vLoginname.value, "Username is required.");
			return false;
		}
		if (checkpwd && !hasValue(_form.vPassword, "PASSWORD")) {
			onError(_form, _form.vPassword, _form.vPassword.value, "Password is required.");
			return false;
		}
		return true;
	},

	requestPassword: function() {
		// Validate the form without password
		if (!Login.checkForm($j('#loginForm')[0], false))
			return;
		var message = "Your password will be sent to your email address.\n\nAre you sure?";
		//if (!confirm(message))
		//	return;
		modalQuery("Request Password", message, { cssClass: 'message_box info', close: true }, [
			{ cssClass: 'send', text: 'Email password', onClick: function() {
				$j.modal.close();
				// Submit
				var loginForm = $j('#loginForm');
				loginForm[0].operation.value = "requestPassword";
				loginForm[0].submit();
			}			
			}/*,
			{ cssClass: 'cancel', text: 'Cancel', onClick: function() { $j.modal.close(); } }*/
		]);
	},

	onSuccess: function(options) {
		// By default, we assume the user is loading a page and had to login.
		// On success, they're logged in and reloading the page will take them to the URL they asked for.
		// If they were on the Login page, we change the URL to the Default.
		var url = "" + window.location; // Force new string to be allocated

		if (options && options.redirect) {
			url = options.redirect;
		} else {
			// Reload the current page, now that we're logged in
			// Replace the old tokenid with the new valid one
			url = url.replace(/tokenid=[^&]+/, "tokenid=" + options.tokenid);
		}
		window.location = url;
	},

	onError: function(message) {
		Login.timeoutDisable();
		displayFlash(message, { cssClass: ' error', header: 'Login Error' });
		Login.setFocus();
	},

	/*	onSubmit - called when requesting login form or submitting login credentials.
	Note: this routine is shared for both functions, as submitting the login might
	come back with an error message (invalid password) to re-display the login form.
	*/

	onSubmit: function() {
		// Test to see if we can create ajax object, report error otherwise.
		// We only do this here on login once to warn the user.
		var xhr;
		try {
			xhr = Ajax.getAjaxObject();

			if (xhr == null) {
				eventTrack("Client Info", "Ajax", "no", null);
				return true; // Allow non-ajax form submit to proceed
			}
		} catch (err) {
			eventTrack("Client Info", "Ajax", "no", null);
			return true; // In case of Ajax error, allow non-ajax form submit to proceed
		}
		eventTrack("Client Info", "Ajax", "yes", null);

		/*
		try {
		if (window.ActiveXObject) {
		try {
		xhr = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (err) {
		xhr =  new XMLHttpRequest();
		}
		} else {
		xhr =  new XMLHttpRequest();
		}
		} catch (err) {
		return true; // Allow non-ajax form submit to proceed
		}
		*/
		var loginForm = $j('#loginForm');
		//for safari fix with jquery 1.4.2
		if(loginForm.length == 0) {
			//make sure login form is loaded on correct place
			//otherwise stop reload the page with relogin
//			return false;
		}

		if (loginForm[0]) {
			if (!Login.checkForm(loginForm[0], true))
				return false;
		} else {
			// Override onSuccess so we don't reload the page
			window.Login.onSuccess = function() {
				$j.modal.close();
			};
		}

		var loginOnComplete = function(xhr, textStatus) {
			if (textStatus == 'success') {
				var contentType = xhr.getResponseHeader("Content-type");
				if (contentType == "text/javascript") {
					eval(xhr.responseText);
					// If we reach this point, the eval did not do a redirect.
					// In case this means an error, so let's set the focus on the login form.
					// DRP 20090801 obsolete?
					//Login.init();
				} else if (contentType == "text/html") {
					// Display the popup login dialog
					// Disable sessionTimeout which is reset by default by Ajax.send's onComplete.
					// Timeout shouldn't run while login is showing!
					Login.timeoutDisable();
					$j.modal.open(xhr.responseText, {
						close: false,
						afterVisible: Login.init
					});
				}
			}
		};

		var data = loginForm[0] ? loginForm.serialize(true) : {
			vCompany: DocumentData.loginCompany,
			vLoginname: DocumentData.loginName,
			vPassword: '',
			operation: 'timeout',
			tokenid: DocumentData.tokenid,
			redirect: DocumentData.redirect
		};

		Ajax.send({
			relativeUrl: '?Login',
			type: 'post',
			data: data,
			onComplete: loginOnComplete
		});
		return false;
	},

	cancel: function() {
		var message =
			"Your session has expired. If you choose to close, your browser will return to the current page " +
			"but you will be unable to perform any operations until you log in again.";
		modalQuery("Expired Session", message, { cssClass: 'message_box attention' }, [
			{ cssClass: '', text: 'Renew Session', onClick: function() { Login.onSubmit(); } },
			{ cssClass: 'cancel', text: 'Close', onClick: function() { $j.modal.close(); } }
		]);
	},

	timeoutEnable: false,

	timeoutDisable: function() {
		Login.timeoutEnable = false;
		// Clear existing timeout, if it's already running
		if (Login.sessionTimeout)
			clearTimeout(Login.sessionTimeout);
	},

	setSessionTimeout: function() {
		Login.timeoutEnable = true;
		Login.sessionTimeoutDelay = window.DocumentData ? DocumentData.timeout * 1000 : null; // milliseconds

		// Clear existing timeout, if it's already running
		if (Login.sessionTimeout) {
			clearTimeout(Login.sessionTimeout);
		}

		var myDateCurrent = new Date();
		var currentTime = myDateCurrent.getTime();
		Login.sessionTimeCount = currentTime;

		if (Login.sessionTimeoutDelay) {
			Login.sessionTimeout = setTimeout( function() {

					var myDateAtTimeout = new Date();
					var currentTimeAtTimeout = myDateAtTimeout.getTime();
					//safari problem with 1.4.2. when click next and prev, setTimeout will be triggered.
					//so we try to compare the real time difference, and reset timeout if needed.
					if(currentTimeAtTimeout >= Login.sessionTimeCount + Login.sessionTimeoutDelay) {
						if (Login.timeoutEnable)
							Login.onSubmit();
					} else {
						//safari case
						Login.setSessionTimeout();
					}
				}, Login.sessionTimeoutDelay);
		}
	}
};