/* Controls top counter */

stadiumCounter={
	init:function() {
		if($('counter') != null) {
			new PeriodicalExecuter(function(pe) {
				stadiumCounter.getCount();
			}, 90);
			stadiumCounter.getCount();
		}
	},

	getCount:function() {
		var url = "/xhr/stadiumCount.xhr.php";
		var qs  = "?noCache="+this.noCacheString();
		new Ajax.Request(url, { method:'get', parameters:qs, onComplete: function(r) {
			var response = r.responseText;
			if(response != "ERROR") {
				stadiumCounter.updateCount(response);
			}
		}});
	},

	updateCount:function(n) {
		$$('#counter span')[0].title = n;
		var nc = n.split(""); // seperate each character in string
		this.clearCount();

		var img, imgSrc, rn;

		for(var i=0; i < nc.length; i++) {
			img = document.createElement("img");
			img.alt = nc[i];

			/* Work out which number to use */
			switch(nc[i]) {
			case 2:
			case 4:
			case 5:
			case 7:
				imgSrc = "/images/countNumbers/"+nc[i];
				rn = Math.floor(Math.random()*11);
				if(rn > 5) imgSrc += "B";
				imgSrc += ".gif";
				break;
			default:
				imgSrc = "/images/countNumbers/"+nc[i]+".gif";
			}

			img.src = imgSrc;
			$$('#counter span')[0].appendChild(img);
		}
	},

	clearCount:function() {
		$$('#counter img').each(function(i) {
			$(i).remove();
		});
	},

	noCacheString:function() {
		var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
		var rn;
		var str = "";
		var ln = Math.floor(Math.random()*4)+6;

		for(var i=0; i <= ln; i++) {
			rn = Math.floor(Math.random()*chars.length);
			str += chars.substring(rn,rn+1);
		}

		return str;
	}
}

Event.onDOMReady(function() {
	stadiumCounter.init();
});