/* Counter object */

var counter = null;

function initcounter () {
	counter = new Counter("/GetLeafCount.aspx?time=" + Math.random(), 60000, updatecounter);
	counter.getTotals(); // init
}
function updatecounter() {
	document.getElementById("dayLeaves").innerHTML = counter.GetDayLeaves();
	document.getElementById("totalLeaves").innerHTML = counter.GetTotalLeaves();
}
function refreshcounter () {
	counter.getTotals();
}

Counter = function(requesturl, interval, updatefunction) {
	// set requesturl as property
	this.requesturl = requesturl;
	this.interval = interval;
	this.updatefunction = updatefunction;
	
	var request;	
	// branch for native XMLHttpRequest object
	if(window.XMLHttpRequest) {
    	try {
			request = new XMLHttpRequest();
		} catch(e) {
			request = false;
		}
	// branch for IE/Windows ActiveX version
	} else if(window.ActiveXObject) {
       	try {
        	request = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		request = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		request = false;
        	}
		}
	}
	if(request) {
		// set request property
		this.xmlhttp = request;
		// set interval
		setInterval(this.method(this.getTotals), this.interval);
	}
}

Counter.prototype.processRequestChange = function() {
	// only if req shows "loaded"
	if (this.xmlhttp.readyState == 4) {
		// only if "OK"
		if (this.xmlhttp.status == 200) {
			// ...processing statements go here...
			this.setTotals();
		} else {
			//alert("There was a problem retrieving the XML data:\n" + req.statusText);
		}
	}
}

Counter.prototype.getTotals = function() {
	this.xmlhttp.open("GET", this.requesturl, true);
	this.xmlhttp.onreadystatechange = this.method(this.processRequestChange);
	this.xmlhttp.send("");
}

Counter.prototype.setTotals = function() {
	var items = this.xmlhttp.responseXML.getElementsByTagName("count");
	var day = items[0].getAttribute("day");
	var school = items[0].getAttribute("schools");
	var total = items[0].getAttribute("total");
	// set properties
	this.dayLeaves = day;
	this.schoolLeaves = school;
	this.totalLeaves = total;
	// call given updatefunction
	this.updatefunction();
}

Counter.prototype.method = function (method) { 
     var context = this; 
     return function () { 
          method.apply(context, arguments); 
     } 
}
/* properties */
Counter.prototype.GetDayLeaves = function() {
	return this.dayLeaves;
}
Counter.prototype.GetSchoolLeaves = function() {
	return this.schoolLeaves;
}
Counter.prototype.GetTotalLeaves = function() {
	return this.totalLeaves;
}
