
function testBandwidth() {	
	var test = new bandwidthTest(['random400.bin', 'random400.bin', 'random500.bin']);
}

function bandwidthTest(testFiles) {
	this.testNum = 1;
	this.maxTests = testFiles.length;
	this.downloadFiles = testFiles;
	this.downloadSpeeds = new Array;
	this.uploadSpeeds = new Array;
	
	this.testDownload();
}

bandwidthTest.prototype.testDownload = function() {
	testObj = this;
	start = new Date().getTime();
	$.ajax({
		type: "GET",
		url: "/assets/bandwidth/" + testObj.downloadFiles[this.testNum-1] + "?id=" + start,		
		dataType: 'application/octet-stream',
		success: function(msg) {
			end = new Date().getTime();
			seconds = (end - start) / 1000;
			bytes = msg.length;
			testObj.downloadSpeeds.push(testObj.kbpsFormat(bytes, seconds));
			testObj.uploadData = msg;
		},
		complete: function(xhr, textStatus) {
			testObj.testUpload();
		},
		error: function(XMLHttpRequest,status,error){}
	});
}

bandwidthTest.prototype.testUpload = function() {
	testObj = this;
	start = new Date().getTime();
	$.ajax({
		type: "POST",
		url: "/assets/bandwidth/upload.php?id=" + start,
		data: testObj.uploadData,
		dataType: 'text/html',
		success: function(msg) {
			end = new Date().getTime();
			seconds = (end - start) / 1000;
			bytes = testObj.uploadData.length;
			testObj.uploadSpeeds.push(testObj.kbpsFormat(bytes, seconds));
		},
		complete: function(xhr, textStatus) {
			
			testObj.writeBandwidth(testObj.downloadSpeeds, testObj.uploadSpeeds);
						
			if (testObj.testNum < testObj.maxTests) {
				testObj.testNum++;
				testObj.testDownload();
			}
		},
		error: function(XMLHttpRequest,status,error){}		
	});
}
bandwidthTest.prototype.writeBandwidth = function(downloadSpeeds, uploadSpeeds) {
		
	// average download results, write to page
	var downAvg = this.arrayAvg(downloadSpeeds);
	var downString = downAvg+' kbps';
		
	$('#downSpeed').html(downString);			 
	$('#downloadSpeed').val(downAvg);
		
	// average upload results, write to page		
	var upAvg = this.arrayAvg(uploadSpeeds);
	var upString = upAvg+' kbps';
		
	$('#upSpeed').html(upString);			 
	$('#uploadSpeed').val(upAvg);
}

bandwidthTest.prototype.arraySum = function(arr) {
	for(var sum = 0, i = arr.length; i; sum += arr[--i]);
	return sum;
};

bandwidthTest.prototype.arrayAvg = function(arr) {
	for(var sum = 0, i = arr.length; i; sum += arr[--i]);
	return Math.round(sum / arr.length);
};

bandwidthTest.prototype.kbpsFormat = function(bytes, seconds) {
	var sizeInBits = bytes * 8;// convert Bytes to bits
	var sizeInKBits = sizeInBits / 1024;// convert bits to kbits
	return Math.round((sizeInKBits/seconds) * 1.07); // IP packet header overhead around 7%
}

