var clientTimeout = 0;
var serverTimeout = 0;
var warnWnd = null;
var dbgProgress = '';
var watchDebug = false;

function addWatchHook(doc) {
	doc.onmouseover = resetWatch;
	doc.onmousedown = resetWatch;
	doc.onkeydown = resetWatch;
}

function resetWatch() {
	if(!warnWnd)
		clientTimeout = 0;
	else if(!warnWnd.closed)
		warnWnd.focus();
	if(watchDebug)
		watchDbgOut(1);
}

function startWatch() {
	setInterval('watchDog()', 1000);
}

function watchDog() {
	var el;
	clientTimeout++;
	serverTimeout++;
	if(clientTimeout > expiredLimit) {
		closeWarning();
		location = '/Blank?session_expired=yes&ss=' + sessionID + '&project=' + PROJECT + '&cachebust=' + (Math.floor(999999 * Math.random()));
	} else if(clientTimeout > warningLimit) {
		if(!warnWnd)
			warnWnd = open('/warning.html', '_blank', 'width=340,height=275,menubar=no,toolbar=no,scrollbars=no,resizable=no,statusbar=no,left=300,top=200');
		if(warnWnd && !warnWnd.closed && (el = warnWnd.document.getElementById('expire')))
			el.value = expiredLimit - clientTimeout;
	}
	if(serverTimeout > sessionLimit) {
		serverTimeout = 0;
		if((el = document.getElementById('refresh')))
			el.src = '/Blank?cachebust=' + (Math.floor(999999 * Math.random()));
	}
	if(watchDebug)
		watchDbgOut(0);
}

function closeWarning() {
	if(warnWnd && !warnWnd.closed)
		warnWnd.close();
	warnWnd = null;
	resetWatch();
}

function watchDbgOut(a) {
	if(a)
		dbgProgress = dbgProgress.length > 70 ? '' : dbgProgress + '.';
	status = 's:' + serverTimeout + '/' + sessionLimit + ' c:' + clientTimeout + '/' + expiredLimit + ' ' + dbgProgress;
}

