
var duration = 1000 * 60 * 60;					// Expires in one hour
var defaultCookieName = 'hbftStatus';

	// Store some general variables for reference between functions

var timerObj = '';
var cValue = '';

	// If cookie is renewed too often, things slow down. Track last renewal and compare to desired frequency:

var lastRenewal = new Date().getTime();
var renewFreq = 12700;					// Allow renewal every 12.7 seconds

	// Listen for event handlers (if not on the login page):

var thisDoc = location.href;

if (!thisDoc.indexOf('checkLogin.html')) {		// Is the current page checkLogin.html?
	document.onkeyup = renewCookie;			// 	No: listen for events
	document.onmouseup = renewCookie;
}


function startTimer() {
	timerObj = window.setTimeout("isCookieExpired()", duration + 3000);	// Delay slightly so cookie has time 
											//     to expire
}

function makeCookie(sValue) {

	if (sValue) {

// alert('Making a new cookie... sValue=' +sValue);

		now = new Date();
		var expires = new Date( now.getTime() + duration );

		document.cookie = defaultCookieName + "=" + escape(sValue) + "; expires=" + expires + ";";
//		return sValue;
	}
}


function readCookie() {

	var start = document.cookie.indexOf( defaultCookieName + "=" );
	var len = start + defaultCookieName.length + 1;
	if ( ( !start ) && 	( defaultCookieName != document.cookie.substring( 0, defaultCookieName.length ) ) ) {		// Doesn't exist
		return null;
	}
	if ( start == -1 ) {
		return null;																	// Contains no data
	}
	
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) {
		end = document.cookie.length;
	}
	return unescape( document.cookie.substring( len, end ) );
}


function renewCookie() {		// Extends timeout; used whenever user clicks comething

	var now = new Date().getTime();

	if (now >= (lastRenewal + renewFreq) ) {		// Not renewed recently: OK to renew again

		cValue = readCookie();
		if (cValue) {		// Cookie exists: update expiration if not renewed recently

			makeCookie(cValue);
			window.clearTimeout(timerObj);
			startTimer();
			lastRenewal = now;

		} else {		// Cookie no longer exists: page immediately expires

			location.href = 'loggedOut.html';
		}

	}				// Renewed recently; don't update the cookie so soon
}


function isCookieExpired() {	// If cookie is expired, redirects to error page

	if (!readCookie()) {
		parent.hideBtn('all'); location.href = "loggedOut.html";		// hide top buttons

		parent.setHeading('Home-Based Family Therapy', 'Logged Out', 'icon-HBFTpartnership.gif');
	} else {
//		alert('isCookieExpired: resetting the timer...');
		window.clearTimeout(timerObj);
		startTimer();				// reset the timer to check again
	}
}


function delCookie() {
	document.cookie = defaultCookieName + "=; expires=Fri, 21 Dec 1976 04:31:24 GMT;";
}


