var originalTitle = document.title;
var displayDialogTO = true;
var blinkTitleBar = null;
var to_counter = null;

var s_session_timer = {
	time: 0,
	now: function() { return (new Date()).getTime(); },
	start: function() { this.time = this.now(); },
	since: function() { return (this.now() - this.time); }
}

function startStudentSessionTimer() {
	displayDialogTO = true;
	s_session_timer.start();
	checkStudentSessionTimer();
}

function checkStudentSessionTimer() {
	if (s_session_timer.since() > sessionTimeout && displayDialogTO) {
		displayDialogTO = false;
		showDialogTimeout();
		alertTitleBar();
	}
	if (s_session_timer.since() > sessionExpiration) {
		hideDialogTimeout();
		logoffUser();
	}
	else
		setTimeout("checkStudentSessionTimer()", 1000);
}

var p_session_timer = {
	time: 0,
	now: function() { return (new Date()).getTime(); },
	start: function() { this.time = this.now(); },
	since: function() { return (this.now() - this.time); }
}

function startProfSessionTimer() {
	displayDialogTO = true;
	p_session_timer.start();
	checkProfSessionTimer();
}

function checkProfSessionTimer() {
	if (p_session_timer.since() > sessionTimeout && displayDialogTO) {
		displayDialogTO = false;
		showDialogTimeout();
		alertTitleBar();
	}
	if (p_session_timer.since() > sessionExpiration) {
		hideDialogTimeout();
		logoffUser();
	}
	else
		setTimeout("checkProfSessionTimer()", 1000);
}

var d_session_timer = {
	time: 0,
	now: function() { return (new Date()).getTime(); },
	start: function() { this.time = this.now(); },
	since: function() { return (this.now() - this.time); }
}

function startDemoSessionTimer() {
	d_session_timer.start();
	checkDemoSessionTimer();
}

function checkDemoSessionTimer() {
	if (d_session_timer.since() > sessionExpiration) {
        logoffUser();
	}
	else setTimeout("checkDemoSessionTimer()", 1000);
}

function resetTimeoutCountdown() {
	hideDialogTimeout();
	if (s_session_timer.time > 0)
		startStudentSessionTimer();
    if (p_session_timer.time > 0)
        startProfSessionTimer();
    if (d_session_timer.time > 0)
        startDemoSessionTimer();
}

function alertTitleBar() {
	if (new Date().getSeconds() % 2 == 0)
		document.title = originalTitle;
	else
		document.title = "Aplia session timeout!";
	blinkTitleBar = setTimeout("alertTitleBar()", 1000);
}

function setTimeRemaining() {
	var timeRemaining = 0;
	
	if (s_session_timer.time > 0)
		timeRemaining = (sessionExpiration - s_session_timer.since()) / 60000;
    if (p_session_timer.time > 0)
        timeRemaining = (sessionExpiration - p_session_timer.since()) / 60000;
    if (d_session_timer.time > 0)
        timeRemaining = (sessionExpiration - d_session_timer.since()) / 60000;

	if (timeRemaining < 1)
		document.getElementById("time-remaining").innerHTML = " 1 minute.";
	else
		document.getElementById("time-remaining").innerHTML = Math.ceil(timeRemaining) + " minutes.";
	
	to_counter = setTimeout("setTimeRemaining()", 1000);
}

function showDialogTimeout() {
	// show the timeout dialog
	window.scrollTo(0, 0);
	YAHOO.util.Dom.setStyle("dialogTimeout", "display", "block");
	
	// show/remove the answer submission message
	if (s_session_timer.time > 0)
		YAHOO.util.Dom.setStyle("relogin-student", "display", "block");
	if (p_session_timer.time > 0)
		YAHOO.util.Dom.setStyle("relogin-student", "display", "none");
	
	// set the time remaining
	setTimeRemaining();
}

function hideDialogTimeout() {
	YAHOO.util.Dom.setStyle("dialogTimeout", "display", "none");
	if (blinkTitleBar != null)
		clearTimeout(blinkTitleBar);
	if (to_counter != null)
		clearTimeout(to_counter);
	document.title = originalTitle;
}

function showDialogLogin() {
	// show the login dialog
	window.scrollTo(0, 0);
	YAHOO.util.Dom.setStyle("dialogLogin", "display", "block");
	
	// clear the e-mail address and password fields
	document.getElementById("reloginEmail").value = "";
	document.getElementById("reloginEmail").className = "lblemail";
	document.getElementById("reloginEmail").blur();
	document.getElementById("reloginPassword").value = "";
	document.getElementById("reloginPassword").className = "lblpassword";
	document.getElementById("reloginPassword").blur();
}

function hideDialogLogin() {
	YAHOO.util.Dom.setStyle("dialogLogin", "display", "none");
	startStudentSessionTimer();
}

function showDialogExpired() {
	// show the expired dialog
	window.scrollTo(0, 0);
	YAHOO.util.Dom.setStyle("dialogExpired", "display", "block");
}

var LoginDialogRequest = {
	handleSuccess: function(o) {
		// Hide the spinner image
		YAHOO.util.Dom.setStyle("spinner", "display", "none");
		
		// parse the JSON string
		try {
			var result = YAHOO.lang.JSON.parse(o.responseText);
			switch (result.status) {
				// successful login by a different user
				case 1:	window.location.href = result.redirectURL;
						break;
				// successful login by the same user
				case 2:	hideDialogLogin();
						break;
				// invalid login credentials
				case 3:	document.getElementById("reloginPassword").value = "";
						document.getElementById("reloginPassword").className = "lblpassword";
						document.getElementById("reloginPassword").blur();
						addErrorInline("error-inline-login", result.errorMessage);
						showErrors();
						return false;
				// inactive or disabled user
				case 4:	window.location.href = result.redirectURL;
						break;
				// server error
				case 5: 
				default: showServerError();
			}
		}
		catch (e) {
			showServerError();
			return;
		}
	},
	
	handleFailure: function(o) {
		showServerError();
	},
	
	send: function() {
		var formData = YAHOO.util.Dom.get("dialogLoginForm");
		var sUrl = "/af/servlet/loginajax";
		sUrl = uniqueUrl(sUrl);
		
		YAHOO.util.Connect.resetFormState();
		YAHOO.util.Connect.setForm(formData);
		var transaction = YAHOO.util.Connect.asyncRequest("POST", sUrl, showLoginDialogCallback);
	}
}

var showLoginDialogCallback = {
	success: LoginDialogRequest.handleSuccess,
	failure: LoginDialogRequest.handleFailure,
	scope:	 LoginDialogRequest,
	timeout: 120000
};

function submitLoginDialog() {
	// clear any error messages that are displayed
	clearOldErrors();
	// display the spinner image
	YAHOO.util.Dom.setStyle("spinner", "display", "block");
	// send the ajax login request to the server
	LoginDialogRequest.send();
}

function showServerError() {
	YAHOO.util.Dom.setStyle("spinner", "display", "none"); // hide the spinner image
	addErrorInline("error-inline-login", "The Aplia server cannot process your request. Please try again in 15 minutes.");
	showErrors();
	return false;
}

var LogoffRequest = {
	handleLogoff: function(o) {
		if (s_session_timer.time > 0)
			showDialogLogin();
		if (p_session_timer.time > 0)
			showDialogExpired();
	},
	send: function() {	
		var sUrl = "/af/servlet/logoffajax";
		sUrl = uniqueUrl(sUrl);
		
		YAHOO.util.Connect.resetFormState();
		var transaction = YAHOO.util.Connect.asyncRequest("POST", sUrl, LogoffCallback); 		
	}
}

var LogoffCallback = {
	success: LogoffRequest.handleLogoff,
	failure: LogoffRequest.handleLogoff,
	scope:	 LogoffRequest,
	timeout: 120000
};

function logoffUser() {
	LogoffRequest.send();
}

var PingRequest = {
	handleSuccess: function(o) {
		// parse the JSON string
		try {
			var result = YAHOO.lang.JSON.parse(o.responseText);
			if (result.status == 1)
				resetTimeoutCountdown();
		}
		catch (e) {
			//showServerError();
			return;
		}
	},
	handleFailure: function(o) {
		// do nothing, let the timer count down
	},
	send: function() {	
		var sUrl = "/af/servlet/pingajax";
		sUrl = uniqueUrl(sUrl);
		
		YAHOO.util.Connect.resetFormState();
		var transaction = YAHOO.util.Connect.asyncRequest("POST", sUrl, PingCallback); 		
	}
}

var PingCallback = {
	success: PingRequest.handleSuccess,
	failure: PingRequest.handleFailure,
	scope:	 PingRequest,
	timeout: 120000
};

function continueSession() {
	PingRequest.send();
}

function checkKeyPress(e) {
	var keycode;
	if (navigator.appName.indexOf("Microsoft") != -1)
		keycode = window.event.keyCode;
	else
		keycode = e.which;
	
	if (keycode == 13) {
		submitLoginDialog();
		return false;
   }
	else
	   return true;
}

function showEmailLabel(visible) {
	var txtEmail = document.getElementById("reloginEmail");
	if (visible && txtEmail.value == "") {
			txtEmail.className = "lblemail";
	}
	else {
		txtEmail.className = "email";
	}
	
	if (!visible) {
		showPasswordLabel(true);
		setTimeout("checkPasswordField()", 1);
	}
}

function showPasswordLabel(visible) {
	var txtPassword = document.getElementById("reloginPassword");
	if (visible && txtPassword.value == "") {
		txtPassword.className = "lblpassword";
	}
	else {
		txtPassword.className = "password";
	}
}

function checkEmailField() {
	var txtEmail = document.getElementById("reloginEmail");
	if (txtEmail.value.length > 0) {
		txtEmail.className = "email";
	}
	setTimeout("checkEmailField()", 100);
}

function checkPasswordField() {
	var txtPassword = document.getElementById("reloginPassword");
	if (txtPassword.value.length > 0) {
		txtPassword.className = "password";
	}
	else
		setTimeout("checkPasswordField()", 100);
}
