﻿// The following two values configure the speed of the counter

// This is the minimum delay (in milliseconds) between counts
var MIN_COUNTER_INTERVAL_MS = 500;

// This is the maximum delay (in milliseconds) between counts
var MAX_COUNTER_INTERVAL_MS = 5000;

// This value determines the rate (in milliseconds) at which the value of the counter is saved on the server
var SAVE_INTERVAL_MS = 10000;

if(!window.XMLHttpRequest) {
	XMLHttpRequest = function() {
		var ids = ["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
		for(var i = 0; i < ids.length; ++i) {
			try {
				return new ActiveXObject(ids[i]);
			}
			catch(e) {}
		}

		throw new Exception("Error creating XMLHttpRequest object");
	}
}

var counterValue = 0;
var counterNode = null;

function initializeCounter(id) {
	var xmlHttp = new XMLHttpRequest();
	xmlHttp.open("GET", "counter.asp", true);
	
	xmlHttp.onreadystatechange = function() {
		if(xmlHttp.readyState == 4) {
			var text;
			if(xmlHttp.status != 200 && xmlHttp.status != '') {
				text = "Error";
			} else {
				counterValue = parseInt(xmlHttp.responseText);
				text = counterValue;
			}
			var node = document.getElementById(id);
			counterNode = document.createTextNode(text);
			node.appendChild(counterNode);
			
			incrementCounter();
			
			setInterval(saveCounter, SAVE_INTERVAL_MS);
		}
	};
	
	xmlHttp.send(null);
}

function incrementCounter() {
	++counterValue;
	counterNode.nodeValue = counterValue;

	var nextDelay = Math.random() * (MAX_COUNTER_INTERVAL_MS - MIN_COUNTER_INTERVAL_MS) + MIN_COUNTER_INTERVAL_MS;
	setTimeout(incrementCounter, nextDelay);
}

function saveCounter() {
	var xmlHttp = new XMLHttpRequest();
	xmlHttp.open("GET", "counter.asp?counter=" + counterValue, true);
	xmlHttp.send(null);
}