/* Copyright (c) 2011, Absolute Futurity.  All rights reserved. http://www.absolutefuturity.com */
/* Authorized use for Vopnet mobile */


var n_genStr = 0;
var mindtime = 8000;	//8000;
var minutime = 6000;	//6000;

var fsize=new Array("100000","500000","1000000","2000000","5000000","10000000","20000000");
var realfsize=new Array(102963,511107,1022545,2046461,5117682,10242367,20480212);

var nisp=new Array("1G","2G","2.5G","2.75G","Edge","3G","4G","LTE");
var visp=new Array(1000,14400,57600,236800,1900000,2000000,16000000,25000000);
var uisp=new Array(1000,14400,28800,236800,947000,1000000,8000000,12000000);


var ulsize=new Array(100000,500000,1000000,2000000,5000000);

var testrunning=false;
var start;
var end;
var lattime;
var slat;
var sdnlbps;
var sulbps;
var pvdr;
var dltimes;
var ultimes;

var indfsize=1;
var indulsize=0;


function starttest(){

	testrunning=true;
	dltimes=0;
	ultimes=0;
	validatetest();
	window.document.getElementById('PlainOutput').innerHTML='';
	window.document.getElementById('ulgraphdiv').style.visibility = 'hidden';
	window.document.getElementById('dlgraphdiv').style.visibility = 'hidden';
	window.document.getElementById('allgraph').style.visibility = 'hidden';

	// ********* Ping for Latency ***********
	displaystatus("<br>Testing Latency...");
	start = new Date();
	pull("backend.php?len=1", "", function () {
		end = new Date();
		lattime = end.getTime() - start.getTime();

		// ********* 2nd Ping for Latency ***********
		start = new Date();
		pull("backend.php?len=1", "", function () {
			end = new Date();
			lattime1 = end.getTime() - start.getTime();
			if (lattime1<lattime) lattime=lattime1;
			displaystatus("<br>Your Lattency is " + lattime + " ms");
			slat=lattime;


			displaystatus("<br><br>Starting Download Test ............");

			downloadtest();

//			filldownloadgraph(9000000);
//			filluploadgraph(1000000);



		});

	});



//	displaystatus("<br>Main Process complete (asyncronous proccess running still)...");
}




function downloadtest(){
	// ********* Download Test ***********
	++dltimes;
	window.document.getElementById('busyOutput').style.visibility = 'visible';
	start = new Date();
	pull("dfiles/" + fsize[indfsize] + ".jpg", "", function () {
		end = new Date();
		var dnltime = end.getTime() - start.getTime();
		var dnlbps = ((realfsize[indfsize] + ((realfsize[indfsize]/576)*52)) * 8) / ((dnltime-lattime) / 1000)
		var oldtestsize=(realfsize[indfsize]/1000000).toFixed(2);
		window.document.getElementById('busyOutput').style.visibility = 'hidden';
		var skipupload=false;
		if (dnltime<8000 || dnlbps<0) {
			comprat=dnltime/realfsize[indfsize];
			do {
				indfsize++;
				if (indfsize>=6) break;
			}
			while (comprat*realfsize[indfsize]<mindtime);
			if (indfsize<7){
//				displaystatus("<br>Recalculated test parameters to compensate. Restarting download test now....");
				skipupload=true;
				if (dltimes<7) {
					downloadtest();
				} else {
					displaystatus("<br><br><br>Your speeds are too fast for this test or the server has gone down for maintenance during this test. Please contact Vopnet if the this problem persists....");
				}
			}
		}
		if (!skipupload){
			displaystatus("<br>Your maximum download speed is " + (dnlbps/1000).toFixed(2) + " Kbps");
			window.document.getElementById('dnlresultstext').innerHTML="<br>Your maximum download speed is " + (dnlbps/1000).toFixed(2) + " Kbps";
			filldownloadgraph(dnlbps);
			sdnlbps=dnlbps;
			displaystatus("<br><br><br>Starting Upload Test ............");
			uploadtest();
		}
	});
}



function uploadtest(){
	// ********* Upload Test ***********
	++ultimes;
	window.document.getElementById('busyOutput').style.visibility = 'visible';
	data = "data="+genStr(ulsize[indulsize]);
	start = new Date();
	pull("backend.php", data, function () {
		end = new Date();
		var ultime = end.getTime() - start.getTime();
		var ulbps = ((ulsize[indulsize]) * 8) / ((ultime-lattime) / 1000)
		var oldtestsize=(ulsize[indulsize]/1000000).toFixed(2);
		window.document.getElementById('busyOutput').style.visibility = 'hidden';
		var skipnext=false;
		if (ultime<6000 || ulbps<0) {
			comprat=ultime/ulsize[indulsize];
			do {
				indulsize++;
				if (indulsize>=4) break;
			}
			while (comprat*ulsize[indulsize]<minutime);
			if (indulsize<5){
//				displaystatus("<br>Recalculated test parameters to compensate. Restarting upload test now....");
				skipnext=true;
				if (ultimes<7) {
					uploadtest();
				} else {
					displaystatus("<br><br><br>Your speeds are too fast for this test or the server has gone down for maintenance during this test. Please contact Vopnet if the this problem persists....");
				}
			}
		}
		if (!skipnext){
			displaystatus("<br>Your maximum upload speed is: " + (ulbps/1000).toFixed(2) + " Kbps");
			window.document.getElementById('ulresultstext').innerHTML="<br>Your maximum upload speed is: " + (ulbps/1000).toFixed(2) + " Kbps";
			filluploadgraph(ulbps);
			sulbps=ulbps;
			pull("update.php?lat="+slat+"&dl="+sdnlbps+"&ul="+sulbps+"&pvdr="+pvdr, "", function () {});
			displaystatus("<br><br><br>Testing Complete!");
			buttonpress('test','retest');
//			window.document.getElementById('test').value = 'Restart Test';
			testrunning=false;
			validatetest();

		}
	});
}









function displaystatus(strstatus){
	window.document.getElementById('PlainOutput').innerHTML+=strstatus;
}




function pull(src, post, callback, opt_method, opt_sync) {
	if (src) {
    
		var X = new XMLHttpRequest();
  
		if (typeof opt_sync == 'undefined' ) opt_sync = true;

		if (X) {
			X.open("POST", src,opt_sync);
			X.onreadystatechange=function() {
				if (X.readyState==4) {
					if (opt_method != null) {
						if (!callback[opt_method]) {
							alert(opt_method + " was not found within class");
						}
						callback[opt_method]();
					} else if (callback) {
						callback();
					} 
				} 
			};
			X.send(post);
		} else {
			alert("Your browser does not support the XMLHttpRequest object.");
		}
	} else {
		alert("Invalid source");
	}
}

function genStr(len) {
    n_genStr = (n_genStr+1)%10;
    var ret = n_genStr+"";

    while (1) {
      if (ret.length > len) {
        return ret.substr(0, len);
      }
      if (ret.length*2 >= len) {
        return ret+ret.substr(0, len-ret.length);
      }
      ret += ret;
    }
}


function updateProgress(evt) {
  displaystatus("<br>Updating..");
  if (evt.lengthComputable) {
    var percentComplete = evt.loaded / evt.total;
    displaystatus("<br>" + percentComplete);
  } else {
    displaystatus("<br>" + 'Unable to compute progress information since the total size is unknown');
  }
}

function transferComplete(evt) {
  displaystatus("<br><br>The transfer is complete.<br><br>");
}

function transferFailed(evt) {
  alert("<br><br>An error occurred while transferring the file.<br><br>");
}

function transferCanceled(evt) {
  alert("<br><br>The transfer has been canceled by the user.<br><br>");
}

function cleargraph(){
	a=document.getElementById('tmod');
	a.innerHTML="";
}

function filldownloadgraph(currentspeed){
	var b='<table class="graphtb"><tr><td colspan="9" align="center">Download Speed<br><br></td></tr><tr>';
	var e=0;
	var c=visp[visp.length-1];
	var lognormalize=c/100000;
	var lognum=(100/Math.log(c/lognormalize));
	var d='<td class="barsec"><img src="images/green.gif" width="21" height="' + (Math.log(currentspeed/lognormalize)*lognum).toFixed(0) + '" alt="' + (currentspeed/1000).toFixed(2) + ' Kbps"></td>';
	for (i=0;i<nisp.length;i++) {
		if (currentspeed<visp[i] && d!=''){
			b+=d;
			d="";
			e=i;
		}
		b+='<td class="barsec"><img src="images/red.gif" width="21" height="' + (Math.log(visp[i]/lognormalize)*lognum).toFixed(0) + '" alt="' + (visp[i]/1000).toFixed(2) + ' Kbps"></td>';
	}
	b+="</tr><tr>";
	for (i=0;i<nisp.length;i++) {
		if (e==i) b+='<td class="legsec"><div class="divrot"><strong>Your Results</strong></div></td>';
		b+='<td class="legsec"><div class="divrot">' + nisp[i] + '</div></td>';
	}
	b+="</tr></table>";
	var f=0;
	for (i=0;i<5;i++) {
		f=c/1000;
		if (f>.009999) ff=3;
		if (f>.099999) ff=2;
		if (f>.999999) ff=1;
		if (f>9.999999) ff=0;
		b+='<div class="taxis">' + f.toFixed(ff) + ' -</div>';
		c=c/10;
	}
	b+='<div class="taxis">0 -</div>';
	var a=window.document.getElementById('dltmod');
	a.innerHTML=b;
	window.document.getElementById('outer').style.top = '280px';
	window.document.getElementById('allgraph').style.visibility = 'visible';
	window.document.getElementById('dlgraphdiv').style.visibility = 'visible';

}


function filluploadgraph(currentspeed){
	var b='<table class="graphtb"><tr><td colspan="9" align="center">Upload Speed<br><br></td></tr><tr>';
	var e=0;
	var c=uisp[uisp.length-1];
	var lognormalize=c/100000;
	var lognum=(100/Math.log(c/lognormalize));
	var d='<td class="barsec"><img src="images/green.gif" width="21" height="' + (Math.log(currentspeed/lognormalize)*lognum).toFixed(0) + '" alt="' + (currentspeed/1000).toFixed(2) + ' Kbps"></td>';
	for (i=0;i<nisp.length;i++) {
		if (currentspeed<uisp[i] && d!=''){
			b+=d;
			d="";
			e=i;
		}
		b+='<td class="barsec"><img src="images/red.gif" width="21" height="' + (Math.log(uisp[i]/lognormalize)*lognum).toFixed(0) + '" alt="' + (uisp[i]/1000).toFixed(2) + ' Kbps"></td>';
	}
	b+="</tr><tr>";
	for (i=0;i<nisp.length;i++) {
		if (e==i) b+='<td class="legsec"><div class="divrot"><strong>Your Results</strong></div></td>';
		b+='<td class="legsec"><div class="divrot">' + nisp[i] + '</div></td>';
	}
	b+="</tr></table>";
	var f=0;
	for (i=0;i<5;i++) {
		f=c/1000;
		if (f>.009999) ff=3;
		if (f>.099999) ff=2;
		if (f>.999999) ff=1;
		if (f>9.999999) ff=0;
		b+='<div class="taxis">' + f.toFixed(ff) + ' -</div>';
		c=c/10;
	}
	b+='<div class="taxis">0 -</div>';
	var a=window.document.getElementById('ultmod');
	a.innerHTML=b;
	window.document.getElementById('outer').style.top = '280px';
	window.document.getElementById('allgraph').style.visibility = 'visible';
	window.document.getElementById('ulgraphdiv').style.visibility = 'visible';


}

function cleargraphs(){
	var b='<table class="graphtb"><tr><td colspan="9" align="center">Getting Results...<br><br></td></tr><tr>';
	var c=visp[visp.length-1];
	var cc=uisp[uisp.length-1];
	b+='<td class="barsec"><img src="images/blank.png" width="21" height="100" alt="0 Kbps"></td>';
	for (i=0;i<nisp.length;i++) {
		b+='<td class="barsec"><img src="images/red.gif" width="21" height="0" alt="0 Kbps"></td>';
	}
	b+="</tr><tr>";
	b+='<td class="legsec"><div class="divrot"><strong>Your Results</strong></div></td>';
	for (i=0;i<nisp.length;i++) {
		b+='<td class="legsec"><div class="divrot">' + nisp[i] + '</div></td>';
	}
	b+="</tr></table>";
	var f=0;
	var ff=0;
	var bb=b;
	for (i=0;i<5;i++) {
		f=c/1000;
		ff=cc/1000;
		if (f>.009999) fff=3;
		if (f>.099999) fff=2;
		if (f>.999999) fff=1;
		if (f>9.999999) fff=0;
		if (ff>.009999) ffff=3;
		if (ff>.099999) ffff=2;
		if (ff>.999999) ffff=1;
		if (ff>9.999999) ffff=0;
		b+='<div class="taxis">' + f.toFixed(fff) + ' -</div>';
		bb+='<div class="taxis">' + ff.toFixed(ffff) + ' -</div>';
		c=c/10;
		cc=cc/10;
	}
	b+='<div class="taxis">0 -</div>';
	bb+='<div class="taxis">0 -</div>';
	window.document.getElementById('dltmod').innerHTML=b;
	window.document.getElementById('ultmod').innerHTML=bb;
	window.document.getElementById('outer').style.top = '280px';
	window.document.getElementById('allgraph').style.visibility = 'visible';
	window.document.getElementById('ulgraphdiv').style.visibility = 'visible';
	window.document.getElementById('dlgraphdiv').style.visibility = 'visible';

}



