var startTime;
var endTime;
var lastReadyState = -1
var httpRequester = getHTTPRequestObject();
var testFileUrl;
//var testFileUrl = 'http://home.eircom.net/Images/Test/1500.jpg';

function getHTTPRequestObject(){
	var xmlHttpRequest;
	if (window.XMLHttpRequest) {
		xmlHttpRequest = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try {
			xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	return xmlHttpRequest;
}

function processResult(){
	if (httpRequester.readyState != lastReadyState){
		lastReadyState = httpRequester.readyState
		if (httpRequester.readyState == 3){
			startTime = new Date();
		} else if (httpRequester.readyState == 4){
			endTime = new Date();
			if (httpRequester.status == 200){
				responseSize = eval(parseInt(httpRequester.getResponseHeader("Content-Length")) + httpRequester.getAllResponseHeaders().length);
				timeTaken = eval((endTime - startTime) / 1000); //in seconds

				bytesPerSecond = eval(responseSize / timeTaken);
				bitsPerSecond = eval(bytesPerSecond * 8)
				kilobitsPerSecond = eval(bitsPerSecond / 1024);
				
				//alert("Download of " + responseSize + " bytes took " + timeTaken + " seconds\n\n" + "This equates to " + bytesPerSecond + " bytes per second \n(" + Math.round(kilobitsPerSecond) / 1 + " kilobits per second)");
				document.forms["result"].elements["kbps"].value = Math.round(kilobitsPerSecond) / 1;
				document.forms["result"].submit();
			} else	{
				catchError("The test file was not found " + httpRequester.status + url);
			}
		}
	}
}

function runSpeedTest(){
				//testFileUrl = 'http://broadbandsupport.eircom.net/download/netopia/firmware/2247NWG-firmware.bin';
				testFileUrl = 'resources/testFile-1500.jpg';
				try{
								document.getElementById('speedtest-button').innerHTML = "Please wait...";
				} catch(e){}
				testFileUrl += '?random=' + Math.floor(Math.random() * 1000001);
				if (httpRequester){
								httpRequester.open("GET", testFileUrl, true);
								httpRequester.onreadystatechange = processResult;
								httpRequester.send(null);
				} else{
								catchError("Your browser could not handle the speed test");
				}
				//return false;
}

function catchError(description){
	try{
		document.getElementById('speedtest-error').innerHTML = "An error occured while attempting the speed test <br />" + description;
		document.getElementById('speedtest-button').innerHTML = "Test your speed"
	} catch(e){
				alert("An error occured while attempting the speed test\n" + description);
 }
}