var updater = null;

var Updater = function(interval, lastModified, lastModifiedUrl) {
	this.timer = null;
	this.period = interval;
	this.lastModified = lastModified;
	this.lastModifiedUrl = lastModifiedUrl;
	this.requestLastModified = null;
	this.requestLastModifiedCount = 0;
	this.block = false;
}

Updater.prototype.init = function() {
	this.timer = setInterval(_updaterLoadLastModified, this.period);
}

Updater.prototype.loadLastModified = function() {
	if (this.requestLastModifiedCount != 0) {
		this.requestLastModifiedCount++;
		if (this.requestLastModifiedCount > 4) {
			this.requestLastModifiedCount = 0;
			this.requestLastModified.abort();
			this.requestLastModified = null;
		} else {
			return;
		}
	}
	if (this.block)
		return;
	this.requestLastModified = ((typeof XMLHttpRequest == "undefined") ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest());
	this.requestLastModifiedCount = 1;
	var url = this.lastModifiedUrl + "?xml=true&requestId=" + (new Date().getTime());
	this.requestLastModified.open("GET", url, true);
	var req = this.requestLastModified;
	this.requestLastModified.onreadystatechange = function() {
		if (req.readyState == 4) {
			updater.checkLastModified(req.responseText);
			updater.requestLastModifiedCount = 0;
			updater.requestLastModified = null;
		}
	}
	this.requestLastModified.send(null);
}

Updater.prototype.checkLastModified = function(lastModifiedString) {
	if (this.block)
		return;
	var newLastModified = new Number(lastModifiedString);
	if (newLastModified > this.lastModified) {
		this.destroy();
		document.location.reload();
	}
}

Updater.prototype.destroy = function() {
	clearInterval(this.timer);
}

Updater.prototype.setBlock = function(block) {
	this.block = block;
}

function _updaterLoadLastModified() {
	if (updater != null)
		updater.loadLastModified();
}