var BandwidthTest = {
	measured_bandwidth: null,
	img: null,
	bytes: null,
	btime: null,
	etime: null,
	callbacks: [],
	run: function() {
		var self = BandwidthTest;
		self.measured_bandwidth = Cookie.get('measured_bandwidth');
		if((!self.measured_bandwidth) && self.img && self.bytes) {
			var img = self.img + '?' + Math.random();
			var el = Builder.node(
				'img',
				{src: self.img, style: 'display: none;'}
			);
			$(el).observe('load', self.loaded.bindAsEventListener($(el)));
			self.btime = (new Date()).getTime();
			var body = $$('body').first();
			if(body)
				body.appendChild(el);
			if(window.opera)
				$(el).style.display = 'block';
		} else {
			if(self.measured_bandwidth) {
				self.measured_bandwidth = new Number(self.measured_bandwidth);
				self.run_callbacks();
			}
		}
	},
	add_callback: function(f) {
		var self = BandwidthTest;
		self.callbacks.push(f);
	},
	run_callbacks: function() {
		var self = BandwidthTest;
		if(self.callbacks && self.callbacks.length) {
			for(var i=0,len=self.callbacks.length; i<len; ++i) {
				(self.callbacks[i])(self.measured_bandwidth);
			}
		}
	},
	loaded: function(e) {
		var self = BandwidthTest;
		self.etime = (new Date()).getTime();
		self.measured_bandwidth = Math.floor(((self.bytes * 8)/((self.etime - self.btime)/1000)) / 1024);
		var nextyear = new Date();
		nextyear.setFullYear(nextyear.getFullYear() + 1);
		Cookie.set('measured_bandwidth', self.measured_bandwidth, nextyear);
		if(window.opera)
			this.style.display = 'none';
		self.run_callbacks();
	}
};

Event.observe(
	window, 
	'load',	
	function(e) {
		BandwidthTest.run();
	},
	false 
);
