//.........................................................................................
// timer objects

/** Timer is global common timer type. Should hold all timer properties */
function Timer(DOMobjName, redirectUrl) {
	this.DOMobjName = DOMobjName;
	this.redirectUrl = redirectUrl;
}

/** Instance of Timer. Properties should be defined on jsp page */
var timerObj = new Timer();

/** function to execute before timeout. Should be defined on jsp page */
function beforeTimeOut(obj) { }

/** window/frame object where timer object is */
var timerFrame = self;
/** global Expiration message */
var timeOutText = "Session Expired";
/** @return boolean whether session is expired */
function isTimeOut(objName) { 
	try {
		if (gbNN6) { // NN6-Mozilla
			return(timerFrame.document.getElementById(objName).textContent == timeOutText);
		} else {
			return(timerFrame.document.getElementById(objName).innerText == timeOutText);
		}
	} catch(err) { return false; }
}

/** function to set Expiration message. Pay attention that this function differs from framework version */
function onTimeOut(tObj) { // when time is expired
	try {
		if (gbNN6) { // NN6-Mozilla
			timerFrame.document.getElementById(tObj.DOMobjName).textContent = timeOutText;
		} else {
			timerFrame.document.getElementById(tObj.DOMobjName).innerText = timeOutText;
		}
		var urlSiteStr = tObj.redirectUrl;
		if (urlSiteStr != null && urlSiteStr != "") {
			//alert("Your session" +
			//	((tObj.redirectUrlName != null) ? " at url '" + tObj.redirectUrlName + "'" : "") +
			//	" has expired. Any not saved data have been removed.");
            var choice = confirm("Your session" +
                ((tObj.redirectUrlName != null) ? " at '" + tObj.redirectUrlName + "'" : "") +
                " has expired. Any not saved data have been removed.");
            if (choice == true){
			     window.location = urlSiteStr; // redirect to session invalidate page
            }
		}
	} catch(err) { return false; }
}

/** 
* If we need to keep window timeout when user does not close browser window. May be redefined in the jsp of particular application 
* Set it to true if you need to keep session active in opened window.
*/
var windowKeepAlive = false; // boolean

/** Session Timeout value. Set up in deployment descriptor (web.xml). Must be defined in the jsp. Reasonable range: 15-60 min. */
var sessionTimeout = 0; // in sec. Sample value: 1799 (equals 30 min)

/** 
* Window timeout. May be defined in the jsp of particular application (make sense if windowKeepAlive == true). 
* Maximum timeout value in case user does not close browser window. Set it if you need to keep session active in opened window.
* Reasonable range: 2-8 hours. (for reference use CQ project)
*/
var windowTimeout = 0; // in sec. Sample value: 7199 (equals 2 hours)

/** 
* Time interval to call session refresh action ('beforeTimeOut' function). 
* This is calculated based on sessionTimeout, windowTimeout and windowKeepAlive values.
* Should be redefined in the jsp of particular application if windowKeepAlive == true.
*/
var keepAliveInterval = 0; // in sec

/** Initial and actual script timeout. This is calculated based on sessionTimeout, windowTimeout and windowKeepAlive values */
var scriptTimeout = 0; // in sec

/** Document's object id to show time. Must be defined in the jsp of particular application */
var timerObjectId; // DOM Id

/** Copy of scriptTimeout variable within showTimer() function local scope */
var localScriptTimeout;
function getLocalScriptTimeout() {
	return localScriptTimeout;
}
function setLocalScriptTimeout(newVal) {
	localScriptTimeout = newVal;
}
/**
* startTimer function. This function is invoked only from the jsp of particular application. It calls showTimer.
* 
* @input objId - id of element on the page (must exist on the page)
* @input timeout - session timeout (MaxInactiveInterval) in sec. Legacy value was equal to sessionTimeout, now
* 	we should use scriptTimeout which is calculated on jsp page (from sessionTimeout, windowTimeout, windowKeepAlive vaues)
* @input whenShowSec - time in sec when we begin to show seconds, example: 179 means when 3 minutes or less remain, seconds are visible
* @input prefix - prefix string, example: "Remaining "
* @input suffix - suffix string
* @input hPrefix - prefix for hours value
* @input mPrefix - prefix for minuntes value
* @input sPrefix - prefix for seconds value
* @input hSuffix - suffix for hours value, example: " hrs "
* @input mSuffix - suffix for minuntes value, example: " min "
* @input sSuffix - suffix for seconds value, example: " sec"
*/
//var rnum = 0; // debug counter
function startTimer(objId, scriptTimeout, whenShowSec, prefix, hPrefix, hSuffix, mPrefix, mSuffix, sPrefix, sSuffix, suffix) {
	startTime = (new Date()).getTime(); // client's time when script start the countdown (in milliseconds)
	setLocalScriptTimeout(scriptTimeout); // set local scriptTimeout
	showTimer(objId, scriptTimeout, whenShowSec, prefix, hPrefix, hSuffix, mPrefix, mSuffix, sPrefix, sSuffix, suffix);
}

function showTimer(objId, nothing, whenShowSec, prefix, hPrefix, hSuffix, mPrefix, mSuffix, sPrefix, sSuffix, suffix) {
	obj = timerFrame.document.getElementById(objId);
	if ( obj && !isNaN(parseInt(getLocalScriptTimeout())) ) {
		if (isNaN(parseInt(whenShowSec))) { whenShowSec = getLocalScriptTimeout(); } // if whenShowSec is not specified
		finishTime = (new Date()).getTime(); // current script execution time
		runTime = parseInt((finishTime - startTime) / 1000, 10); // quantity of seconds which script is running (in seconds)
	
		timeLeft = getLocalScriptTimeout() - runTime; // time left in seconds
		
		var hous = (timeLeft >= (60 * 60)) ? parseInt(timeLeft / (60 * 60), 10) : 0;
		var mins = (timeLeft >= 60) ? parseInt((timeLeft % (60 * 60)) / 60, 10) : 0;
		var secs = (timeLeft < 60) ? timeLeft : parseInt(timeLeft % 60, 10);
		var timerValue = '';
	
		if (timeLeft < 1) {
			onTimeOut(timerObj); // timeout, end of execution
		} else {
			// do we neet to call session refresh action?
			if (windowKeepAlive // redundant check (leave for now)
				&& runTime > keepAliveInterval // script is running long enough to refresh
				&& timeLeft > sessionTimeout // remaining time is still more than server timeout
			) { 
				beforeTimeOut(null); // session refresh action
				setLocalScriptTimeout(getLocalScriptTimeout() - runTime); // reduce whole script timeout
				startTime += parseInt(runTime*1000, 10); //(new Date()).getTime(); // change script start point
				//++rnum;
			} else if (timeLeft == sessionTimeout) { // remaining time is exact server timeout
				beforeTimeOut(null); // session refresh action
				//++rnum;
			}
			var newHous = ''; // new value of hours
			var newMins = ''; // new value of minutes
			var newSecs = ''; // new value of seconds
			
			timerValue += prefix;
			if (hous > 0) {
				newHous = hous;
				timerValue += (hPrefix + newHous + hSuffix);
				newMins = (mins < 10) ? '0' + mins : mins;
				timerValue += (mPrefix + newMins + mSuffix);
			} else {
				newMins = mins;
				timerValue += (mPrefix + newMins + mSuffix);
			}
			if (!isNaN(timeLeft)) { // to get NaN out in Netscape 4 browser (?)
				if (timeLeft <= whenShowSec) { // show seconds
					newSecs = (secs < 10) ? '0' + secs : secs;
					timerValue += (sPrefix + newSecs + sSuffix);
				}
			}
			timerValue += suffix;
			if (obj.hours != newHous || obj.minutes != newMins || obj.seconds != newSecs) { // if actual display time information is changed
				obj.hours = newHous;
				obj.minutes = newMins;
				obj.seconds = newSecs;
				if (gbNN6) {
					obj.textContent = timerValue;
						//+ " rfrsh: " + rnum + " timeLeft: " + timeLeft + " sessionTimeout: " + sessionTimeout
						//+ " localScriptTimeout: " + getLocalScriptTimeout() + " scriptTimeout: " + scriptTimeout 
						//+ " runTime: " + runTime + " keepAliveInterval: " + keepAliveInterval; // refresh screen
				} else {
					obj.innerText = timerValue;
						//+ " rfrsh: " + rnum + " timeLeft: " + timeLeft + " sessionTimeout: " + sessionTimeout
						//+ " localScriptTimeout: " + getLocalScriptTimeout() + " scriptTimeout: " + scriptTimeout 
						//+ " runTime: "+ runTime + " keepAliveInterval: " + keepAliveInterval; // refresh screen
				}
			}
			setTimeout("showTimer('" + timerObjectId + "', -1, " + whenShowSec + ", '" + prefix + "', '" + hPrefix + "', '" + hSuffix + "', '" + mPrefix + "', '" + mSuffix + "', '" + sPrefix + "', '" + sSuffix + "', '" + suffix + "')", 500); // set delay (in msec) for next call
		}
	}
}
