/**
 * KeepAlive tries to keep the session alive by accessing a given URL
 * (path) at regular intervals (timeout).
 */

function KeepAlive(timeout, path) {
	this.timeout = timeout;
	this.path = path;
	this.schedule();
	this.request = false;
}

/** Request the URL and reschedule. On error, call retry. */
KeepAlive.prototype.now = function() {
	try {
		this.request = createXMLHttpRequest();
		if (!this.request) {
			if (showMessage) showMessage('error.xmlhttp.keepalive');
		} else {
			var _this = this; // Workaround for keeping scope.
			this.request.onreadystatechange = function() { _this.callback(); };
			this.request.open('GET', this.path, true);
			this.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			this.request.send(null);
			
			if (window.XMLHttpRequest) {
				this.callback();
			}
		}		
		this.schedule();
	} catch (err) {
		this.retry();
	}
}

/** Call the now function after the given timeout. */
KeepAlive.prototype.schedule = function() {
	delayedCall(this, ".now()", this.timeout);
}

/** Call the now function after one quarter of the given timeout. */
KeepAlive.prototype.retry = function() {
	delayedCall(this, ".now()", this.timeout / 4);
}

/** Handle the response from the request sent by now(). Check for timeout. */
KeepAlive.prototype.callback = function() {
	if (this.request.readyState == 4) {
		if (this.request.status == 200) {
			var xmldoc = this.request.responseXML;
			if (checkForTimeout(xmldoc)) {
				return;
			}
		}
	}
}
			
