var ActivityTimer;
var RedirectTimer;
var ActivityTimeoutRedirect = null;
var TimeoutMins = 20;
var RedirectMins = 1;
var KeepAliveSpacingMS = 10000;
var KeepAliveURL;
var IsChildWindow = false;
var LastKeepAlive = null;
var ChildWindow = null;

function openWin(a)
{
	if (!ChildWindow) {
		var url = a.href;
		var args = 'width=1024,height=768,channelmode=0,directories=0,fullscreen=0,location=0,menubar=0,status=yes,titlebar=0,toolbar=no,resizable=1,scrollbars=0';
		ChildWindow = window.open(url, 'docview', args);
	}
	else {
		ChildWindow.document.location = a.href;
		ChildWindow = ChildWindow;
	}
}

function redirectToLogout() {
	window.location.href = ActivityTimeoutRedirect;
}

function showKeepAlive() {
	//show the keep alive box
	$('kaBox').setStyle('display', 'block');
	setTimeout(function () {
		$('kaBox').fade('in');
	}, 1000);

	if (ChildWindow)
		ChildWindow.showKeepAlive();
	
	//set a timer for redirect
	RedirectTimer = redirectToLogout.delay(1000 * 20 * RedirectMins);
}

function hideKeepAlive() {
	//clear redirect timer
	RedirectTimer = $clear(RedirectTimer);
	if (ChildWindow)
		ChildWindow.hideKeepAlive();
	//hide the keep alive box
	$('kaBox').fade('out');
	setTimeout(function () {
		$('kaBox').setStyle('display', 'none');
	}, 1000);

}

function confirmKeepAlive() {
	hideKeepAlive();
	resetActivityTimer();
}

function resetActivityTimer()
{
	if (IsChildWindow && window.opener) {
		window.opener.resetActivityTimer();
	}
	else { 
		//reset client side timer
		if (ActivityTimer != null) {
			ActivityTimer = $clear(ActivityTimer); //clear timer
			hideKeepAlive();
		}

		//send request to the server saying we're still interested
		if (!LastKeepAlive || LastKeepAlive < new Date().getTime() - KeepAliveSpacingMS) {
			new Request({
				url: KeepAliveURL,
				onComplete: function () {
					LastKeepAlive = new Date().getTime();
				}
			}).send();
		}

		ActivityTimer = showKeepAlive.delay(1000 * 60 * TimeoutMins);
	}
}

window.addEvent('domready', function () {
	if (ActivityTimeoutRedirect != null) {
		resetActivityTimer();
		document.addEvent('click', resetActivityTimer);
	}

	$$('a.tablink').each(function (item) {
		item.addEvent('click', function (event) {
			new Event(event).stopPropagation();
		});
	});
});
