/*
	Connection speed (throughtput) detection routine
	
	Requirements: Load this script, empty script container, set data script URL, set callback function
	                         At your test location (dsDataURL), DetectSpeedData.png and DetectSpeedLatency.png must be present.
			    DetectSpeedData.png is the image file used to test the speed.
			    DetectSpeecLatency.png is a very very small image file used to test latency to make the speed more accurate.
	
	Sample code:
		<script src="DetectSpeed.js" language="javascript"></script>
		<script language="JavaScript">
			var newurl;
			function doload() {
				dsDataURL='<%=mylocation%>_lib/DetectSpeedData.js';
				dsStartTest('DetectSpeedData',dsDataURL,speedTestDone);
			}
			function speedTestDone() {
				var e=document.getElementById('playstate')
				e.innerHTML=e.innerHTML+'<br>'+dsTextOutput+'<br>';
				newurl=initialLocation+'&MediaThroughput='+throughputstr+'&MediaPlayers='+playerString;
				e.innerHTML=e.innerHTML+'<input type=button name=gobtn value=Play onclick="document.location=newurl;">';
				document.location.replace(newurl);
			}	
		</script>
		<div id="DetectSpeedData" style="visibility:hidden;height:1px;width:1px;"></div>
	
*/

// Global variables (so other routines can access our information)
var dsData=' ';
var dsDataURL;
var dsDataSize=31468; // in Bytes
var dsTestStartTime=0;
var dsTestEndTime=0;
var dsDiffTimeMsec=0;
var dsDiffTimeSec=0;
var dsThroughput=0;
var dsLatency=0;
var dsDateObj=0; 
var dsTextOutput="";
var dsThroughputstr="";
var dsEndCallback;
var dsContainer;
var dsContainerHTML;

// Throughput Calculation (called at end of test
function dsCalcSpeed(mylatency) {
	// How long it took = end time - start time (in milliseconds, so we divide by 1000), then make sure the result isn't 0
	dsDiffTimeMsec = dsTestEndTime - dsTestStartTime - mylatency;
	dsDiffTimeSec = dsDiffTimeMsec/1000;
	if (dsDiffTimeSec <= 0) {
		dsDiffTimeSec = 0.01; // don't want our result to be "infinity"
	}

	// The end result we want is K bits per second (Kbps), so first, we calculate Kb, then divide by seconds
	var bits = (dsDataSize*8);   // convert Bytes to bits, 
	var kbits = bits/1024;     // convert bits to kbits
	var kbps  = kbits/(dsDiffTimeSec);
	return(kbps);
}
function dsCalcThroughput() {
	// How long it took = end time - start time (in milliseconds, so we divide by 1000), then make sure the result isn't 0
	dsThroughput = dsCalcSpeed(100);
	dsThroughput = dsThroughput * 1.20;  // account for IP packet header overhead - averages about 7%
	dsThroughputstr = dsThroughput.toString();
	dsTextOutput = "Time to load: (sec): <B>" + dsDiffTimeSec + "</B><BR>Kbits:<B> " + dsDataSize*8/1024 + "</B><BR>Throughput (Kbps): <B>" + dsThroughput +"</B>";
}

// To start the test, we record the start time, set a callback so we know when our data load is complete, the tell the browser to load the data
function dsStartTest(mycontainer,myurl,cbfunc) {
	// Save incoming information for later
	dsContainer=document.getElementById(mycontainer);
	dsContainerHTML=dsContainer.innerHTML;
	dsDataURL=myurl+'DetectSpeedData.png';
	dsEndCallback=cbfunc;
	dsLatency=0;

	// Test 1: File size
	var req=null;
	if (window.XMLHttpRequest) { // Non-IE browsers	
		req = new XMLHttpRequest();
	} else {
		req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	req.open('HEAD','DetectSpeedData.png',false);
	req.send(null);
	if (req.status!=200) {
		alert('Missing data file, status='+req.status);
		dsDataSize=65000;
	} else {
		dsDataSize=parseFloat(req.getResponseHeader("Content-Length"));
	}
	
	// Test 2: Latency
	dsDateObj = new Date();
	dsTestStartTime=dsDateObj.getTime();
	dsContainer.innerHTML='<img style="width:1px;height:1px;visibility:hidden;" src="'+myurl+'DetectSpeedLatency.png?time='+dsTestStartTime.toString()+'" onload="dsGetLatency();" onreadystatechange="dsRSC(this,\'dsGetLatency()\');">';
	
	// at this point we give up control and wait for the onload  event to fire, which continues to the next function
}
function dsGetLatency() {
	if (!dsLatency) { //For IE, make sure this doesn't execute twice
	dsDateObj = new Date();
	dsTestEndTime=dsDateObj.getTime();
	dsLatency=dsTestEndTime-dsTestStartTime;
	dsThroughput=0;

	// Test 3: Speed
	dsDateObj = new Date();
	dsTestStartTime=dsDateObj.getTime();
	dsContainer.innerHTML='<img style="width:1px;height:1px;visibility:hidden;" src="'+dsDataURL+'?time='+dsTestStartTime.toString()+'" onload="dsGetSpeed();" onreadystatechange="dsRSC(this,\'dsGetSpeed()\');">';
	}
	// at this point we give up control and wait for the onload  event to fire, which continues to the next function
}
function dsGetSpeed() {
	if (!dsThroughput) { //For IE, make sure this doesn't execute twice
	dsDateObj = new Date();
	dsTestEndTime=dsDateObj.getTime();
	dsThroughput=dsCalcSpeed(dsLatency);
	//dsThroughput=dsCalcSpeed(0);
	dsThroughputstr = dsThroughput.toString();
	dsTextOutput = "Time to load: (sec): <B>" + dsDiffTimeSec + "</B><BR>Kbits:<B> " + dsDataSize*8/1024 + "</B><BR>Throughput (Kbps): <B>" + dsThroughput  + "</B><BR>Latency (secs): <B>" + dsLatency/1000 +"</B>";
	setTimeout('dsEndCallback()',100);
	dsContainer.innerHTML=dsContainerHTML;
	}
/* === original functino===
function dsStartTest(cbfunc) {
	dsEndCallback=cbfunc;
	var e=document.getElementById('DetectSpeedData');
	e.onload=dsEndTest;
	e.onreadystatechange=dsEndTestRS;
	dsDateObj = new Date();
	dsTestStartTime=dsDateObj.getTime();
	e.src=dsDataURL+'?time='+dsTestStartTime.toString();
*/
}

// IE uses a different method "ready state" to tell when loading is complete, so support that too
function dsRSC(e,f) {
	if ((e.readyState=='complete')||(e.readyState=='loaded')) {
		setTimeout(f,10);
	}
}

// To end the test, we record the end time, call the calculation function, then the page's callback function
function dsEndTest() {
	dsDateObj = new Date();
	dsTestEndTime=dsDateObj.getTime();
	try {
		dsSetTestData();
		dsDataSize=dsData.length+40+400; // adjust for script size overhead and http headers
	} catch (e) {
		dsDataSize=31844+20+400;
	}
	dsCalcThroughput();
	setTimeout('dsEndCallback()',100);
}

// IE uses a different method "ready state" to tell when loading is complete, so support that too
function dsEndTestRS() {
	var e=document.getElementById('DetectSpeedData');
	if ((e.readyState=='complete')||(e.readyState=='loaded')) {
		dsEndTest();
	}
}

function dsStartFlash(mycontainer,cbfunc) {
	dsEndCallback=cbfunc;
	dsContainer=document.getElementById(mycontainer).parentNode;
	dsContainerHTML=dsContainer.innerHTML;
	

	// Set width and height for this test
	playerdiv.style.width=320;
	playerdiv.style.height=320/4*3+20;
	var vpos=(parseInt(playercontainer.style.height) / 2)-(parseInt(playerdiv.style.height) / 2);
	playerfloat.style.top=vpos;
	playerdiv.style.top=0;
	var hpos=(parseInt(playercontainer.style.width) / 2)-(parseInt(playerdiv.style.width) / 2);
	playerfloat.style.left=hpos;
	playerdiv.style.left=0;

	var xpiurl='swfobject-2.1/expressinstall.swf';
	var params={
		allowscriptaccess:'always'
	}
	var flashvars={
		testfile: dsDataURL,
		callback: 'dsEndFlash'
	}
	var attributes = {
		id: "dsFlash",
		name: "dsFlash"
	};
	
	swfobject.embedSWF('DetectSpeed2.swf?NoCache=200811251100',mycontainer,parseInt(playerdiv.style.width),parseInt(playerdiv.style.height),'9.0.0',xpiurl,flashvars,params,attributes);
}

function dsEndFlash(kbps,imgsize,kbps1,kbps2) {
	//alert('Image size: '+imgsize+', Speed: '+kbps+' Kbps');
	dsContainer.innerHTML=dsContainerHTML;
	dsThroughput = kbps;
	dsThroughput = dsThroughput * 1.20;  // account for IP packet header overhead - averages about 7%
	dsThroughputstr = dsThroughput.toString();
	dsTextOutput = 'Image size: '+imgsize+',Throughput (Kbps): <B>' + dsThroughput +'</B>, first='+kbps1+', second='+kbps2;
	//alert(dsTextOutput);
	setTimeout('dsEndCallback()',100);
}

