﻿// JScript File
var isPopup = false; //set this to true in popups

var iElapsedTime = 0;
var iBrowsingTime = 0;
var iTimeOutNotice = 0;

/**************************************************
* replace showModalDialog with wrapper - START
**************************************************/
var tmpShowModalDialog = window.showModalDialog;

//parses the return value and determines whether the window timed out.
function parseReturnVal(returnVal) {
	if (typeof (returnVal) == "string") {
		if (returnVal == "timeoutClose") {
			if (isPopup) {
				window.returnValue = returnVal;
				window.close();
			}
			else {
				window.location = "/LoginError.aspx?err=TimeoutExpired";
			}
			return undefined;
		} else {
			fn_ResetSessions(); //reset session if window is closed for reasons other than timeout
			return returnVal;
		}
	}
	else {
		fn_ResetSessions(); //reset session if window is closed for reasons other than timeout
		return returnVal;
	}
}

function wrapperShowModalDialog(sUrl) {
	var spTimeout = document.all ? document.all["spTimeout"] : document.getElementById("spTimeout");
	spTimeout.innerText = "Countdown Temporarily Disabled";
	var returnVal = tmpShowModalDialog(sUrl);
	return parseReturnVal(returnVal);
}

function wrapperShowModalDialog(sUrl, vArguments) {
	var spTimeout = document.all ? document.all["spTimeout"] : document.getElementById("spTimeout");
	spTimeout.innerText = "Countdown Temporarily Disabled";
	var returnVal = tmpShowModalDialog(sUrl, vArguments);
	return parseReturnVal(returnVal);
}

function wrapperShowModalDialog(sUrl, vArguments, sFeatures) {
	var spTimeout = document.all ? document.all["spTimeout"] : document.getElementById("spTimeout");
	spTimeout.innerText = "Countdown Temporarily Disabled";
	var returnVal = tmpShowModalDialog(sUrl, vArguments, sFeatures);
	return parseReturnVal(returnVal);
}

window.showModalDialog = wrapperShowModalDialog;
/**************************************************
* replace showModalDialog with wrapper - END
**************************************************/

function setTimeOut(iTimeOut) {
	//****************************************************************************************
	// Timer functionality start                                                              
	//****************************************************************************************

	//Return value from setInterval call
	var iIntID;

	//Keeps track of how long we have been sitting on this page	
	iElapsedTime = 0;

	//Get our session timeout from the parameter passed
	iBrowsingTime = iTimeOut;

	//Set timeout notice threshold at 10 minutes before whatever our timeout is...
	//or half our timeout if timeout is < 20 minutes
	if (iBrowsingTime > 1200) {
		iTimeOutNotice = iBrowsingTime - 600;
	}
	else {
		iTimeOutNotice = Math.floor(iBrowsingTime / 2);
	}

	try {
		iIntID = window.setInterval("browsingTime();", 1000);
		browsingTime(); //run to update on page load
	} catch (e) {
		//Do Nothing
	}
}

//**************************************
//  Put all timeout functionality here  
//**************************************

function browsingTime() {
	var spTimeout = document.all ? document.all["spTimeout"] : document.getElementById("spTimeout");

	//increment elapsed time
	iElapsedTime++;

	//if elapsed time is equal to the timeout notice value, show our inactive message
	if (iElapsedTime == iTimeOutNotice) {
		showInActiveMsg();
	}

	//Check if elasped time is less than our timeout
	if (iElapsedTime < iBrowsingTime) {

		//How much time do we have left in seconds?
		var iTimeLeft = iBrowsingTime - iElapsedTime;

		//How many hours are in iTimeLeft
		var iHour = Math.floor(iTimeLeft / 3600);

		//How many minutes are in iTimeLeft?
		//var iMin = Math.floor(iTimeLeft / 60);
		var iMin = Math.floor((iTimeLeft - (Math.floor(iTimeLeft / 3600) * 3600)) / 60);

		//convert minutes to 2 places if needed
		var sMin = iMin.toString();
		if (sMin.length == 1) sMin = "0" + sMin;

		//How many seconds are in iTimeLeft?
		var iSec = iTimeLeft - (Math.floor(iTimeLeft / 60) * 60);

		//Convert seconds to string so we can pad if need be
		var sSec = iSec.toString();
		if (sSec.length == 1) sSec = "0" + sSec;

		//Check to see if browser supports textContent method
		var hasTextContent = (document.getElementsByTagName("body")[0].textContent != undefined) ? true : false;

		//Set the browser window status
		if (iHour > 0) {
			if (hasTextContent) {
				spTimeout.textContent = "Session Time Remaining: " + iHour + ":" + sMin + ":" + sSec;
			} else {
				spTimeout.innerText = "Session Time Remaining: " + iHour + ":" + sMin + ":" + sSec;
			}
		} else {
			if (hasTextContent) {
				spTimeout.textContent = "Session Time Remaining: " + iMin + ":" + sSec;
			} else {
				spTimeout.innerText = "Session Time Remaining: " + iMin + ":" + sSec;
			}
		}

	} else {
		//we have timed out, clear the status bar
		spTimeout.innerText = "";
		// run any registered timeout callbacks
		runSessionTimeoutCallbacks();
		if (isPopup) {
			//set our return value to timed out
			window.returnValue = "timeoutClose";

			//close the window
			window.close();
		}
		else { //redirect
			top.location = "/LoginError.aspx?err=TimeoutExpired";
		}
	}

}

function showInActiveMsg() {
	var spTimeout = document.all ? document.all["spTimeout"] : document.getElementById("spTimeout");

	//Set status bar to let user know they could be timing out
	spTimeout.innerText = "Possibly Timing Out";

	//Set up info to pass to our pop up warninig
	var WinArgs = new Array();
	WinArgs[0] = iBrowsingTime - iElapsedTime;
	WinArgs[1] = 1;
	WinArgs[2] = window;

	//Display our modal popup warning
	var myWin = tmpShowModalDialog(RelativeWebDirectoryPath + "/Security/PopUps/AlertTimeout.html", WinArgs, "status:no;center:yes;scroll:no;resizable:no;dialogWidth:356px;dialogHeight:220px;help:no;");

	//What happenned when the window closed?
	if (myWin == 1) {
		//It closed itself because we have timed out, notify the user
		if (isPopup) {
			window.returnValue = "timeoutClose";
			window.close();
		}
		else {
			top.location = "/LoginError.aspx?err=TimeoutExpired";
		}
	}
	else {
		//The user closed it, rest the timeout and go on our way
		fn_ResetSessions();
	}
}

var sessionTimeoutCallbacks = new Array();

function addSessionTimeoutCallback(callback) {
	sessionTimeoutCallbacks.push(callback);
}
function runSessionTimeoutCallbacks() {
	var len = sessionTimeoutCallbacks.length;
	for (var i = 0; i < len; i++) {
		callback = sessionTimeoutCallbacks.pop(); // pop the item from the array so we don't run it 2x.
		if ((callback == null) || !(callback instanceof Function))
			continue;
		callback();
	}
}

function fn_ResetSessions() {
	//Make sure that sessions on the server are still active (and refresh if they are)
	var h1 = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

	h1.open("GET", RelativeWebDirectoryPath + "/Security/Timeout/CheckSessionTimeout.aspx", false);
	h1.send();

	if (h1.responseText != "NOSESSION") {
		/* //do we need to refresh timeout specifically - should be done by checksessiontimeout
		var h2 = new ActiveXObject("Microsoft.XMLHTTP");
		h2.open("GET", RelativeWebDirectoryPath + "/Security/Timeout/RefreshSessionTimeout.aspx", false);
		h2.send();
		*/
		fn_ResetTimeOut();
	}
	else {
		//Something odd happened.  Therefore, to be safe, we close the session.
		var h3 = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

		h3.open("GET", RelativeWebDirectoryPath + "/Security/Timeout/AbandonSession.aspx", false);
		h3.send();

		if (isPopup) {
			window.returnValue = "timeoutClose";
			window.close();
		}
		else {
			top.location = "/LoginError.aspx?err=TimeoutExpired";
		}
	}
}

function fn_ResetTimeOut() {
	iElapsedTime = 0;
}
