// JS functions for measuring client bandwidth

var t;  // setTimeout object
var refreshRate = 10;  // refresh rate in seconds
var highbwthresh = 5000;
var medbwthresh = 750;
var startTime=0; 
var endTime=0; 
var date=0; 
var round=0;
var roundlimit=5;

function calcThroughput(text) { 
	var diffTimeMilliseconds = (endTime - startTime); 
	var diffTimeSeconds = diffTimeMilliseconds/1000;
	var datasize = text.length;
	var bits = (datasize*8); // convert Bytes to bits, 
	var kbits = bits/1024; // convert bits to kbits 
	var throughput = kbits/(diffTimeSeconds); 
	var constat = "slow";
	throughput = throughput * .93; // account for IP packet header overhead - averages about 7% 
	if (throughput > highbwthresh) {
		constat = "fast";
	} else if (throughput < highbwthresh && throughput > medbwthresh) {
		constat = "medium";
	}
	var textMessage = "Speed of Your Internet Connection: " + Math.round(throughput) + "kbps (" + constat + ")&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	document.getElementById("bandwidth").innerHTML=textMessage;
} 

// Gets test data - calls itself via setTimeout
function checkbw() {
	round = round + 1;
	// Clears previous setTimeout functions -- so multiple loops wont be running at once
	if (t) {
		clearTimeout(t);
	}
	
	date = new Date(); 
	startTime=date.getTime(); 
	fetchInfo('/cgi/bwtest.cgi', 'GET', 'text', calcbw,'');
	if (round < roundlimit) {
        t=setTimeout("checkbw()", refreshRate * 1000);
	}
}

function calcbw(text) {
	date = new Date(); 
	endTime=date.getTime(); 
	calcThroughput(text); 
}

function initializebw() {
// 	preloadImages('/img/checkout2-green.gif','/img/checkout2-yellow.gif','/img/checkout2-red.gif');
// 	t=setTimeout("checkbw()",500);
	checkbw();
}

function preloadImages() {
	if(document.images){
		if(!document.preloadImgs) document.preloadImgs=new Array();
		pli = document.preloadImgs;
		var i;
		var plil = pli.length;
		var pla=preloadImages.arguments;
		for(i=0; i<pla.length; i++) {
			if (pla[i].indexOf("#")!=0){ 
				pli[plil]=new Image;
				pli[plil++].src=pla[i];
			}
		}
	}
}
