/*
	Lib to keep the connection to server alive
*/

var keepAliveIntervalTimer;
var timeout;
var errorCount;

var TIMEOUT_DEFAULT = 10;
var TIMEOUT_ERROR1 = 2;
var TIMEOUT_ERROR2 = 3;

function doKeepAlive() {
		new Ajax.Request(ogcore_ajax_getRequestUrl('keepalive.keepAlive', ''), {
			evalScripts:false,
			onFailure: function() {
				onImmformerCxnError();
			},
			onException: function() {
				onImmformerCxnError();
			},
			onSuccess: function(transport) {
				if(transport.responseText.startsWith("keepAlive"))
					onImmformerCxnOk();
				else onImmformerCxnError();
			}
		});
}

function setupKeepAlive() {
	errorCount = 0;
	setTimer(TIMEOUT_DEFAULT);
}

function onImmformerCxnOk() {
	setupKeepAlive();
}

function onImmformerCxnError() {
	if(errorCount<0) return;
	errorCount++;
	if(errorCount > 0) {
		timeout = TIMEOUT_ERROR1;
	}
	if(errorCount > 1) {
		TIMEOUT_ERROR2;
	}
	if(errorCount > 2) {
		errorCount = -1;
		requestStart();
		alert(i18n_message_brokenconnection);
	}
}

function setTimer(i) {
	timeout = 1000 * 60 * i;
	if(keepAliveIntervalTimer) {
		window.clearInterval(keepAliveIntervalTimer);
	}
	keepAliveIntervalTimer = window.setInterval("doKeepAlive();", timeout);
}
