var SpeedTest = function() {
  /* 
  From:  http://techallica.com/kilo-bytes-per-second-vs-kilo-bits-per-second-kbps-vs-kbps/
  256 kbps            31.3 KBps
  384 kbps            46.9 KBps
  512 kbps            62.5 KBps
  768 kbps            93.8 KBps
  1 mbps ~ 1000kbps   122.1 KBps
  */
};
SpeedTest.prototype = {
  imgUrl: "images/speedtest.jpg"    // Where the image is located at
  ,size: 59917                // bytes 
  ,run: function( options ) {
    
    if( options && options.onStart )
      options.onStart();
  
    var imgUrl = this.imgUrl + "?r=" + Math.random();
    this.startTime = (new Date()).getTime() ;

    var testImage = new Image();
    var me = this;
    testImage.onload = function() { 
      me.endTime = (new Date()).getTime();
      me.runTime = me.endTime - me.startTime;
    
      if( options && options.onEnd )
        options.onEnd( me.getResults() );
    };
    testImage.src = imgUrl; 
  }
  
  ,getResults: function() {
    if( !this.runTime ) 
      return null;
      
    return { 
      runTime: this.runTime
      ,Kbps: ( this.size * 8 / 1024 / ( this.runTime / 1000 ) )
      ,KBps: ( this.size / 1024 / ( this.runTime / 1000 ) )
    };
  }
}

var st = new SpeedTest();
st.run({
  onStart: function() {
    //alert('Before Running Speed Test');
  }
  
  ,onEnd: function(speed) {
    //alert( 'Speed test complete:  ' + speed.Kbps + ' Kbps');
    
    // slow speed detected and question user
    if( speed.Kbps < 40 )
    {      	
      	var question= confirm("Connection speed < 40kbps detected.\nWould you like to visit the Lite version of this website?\n(The lite version removes images and heavy scripts)");
		
		var explodedURL = location.href.split("/");
		var newURL = "";
		
		for (x in explodedURL)
		{
			if (x == explodedURL.length-1)
				newURL += explodedURL[x];
			else {
				newURL += explodedURL[x] + "/";
				if (x == 2)
					newURL += "lite/";
			}		
		}		
		
		if (question== true)
		{
			alert('Taking you to ' + newURL);
			window.location = newURL;
		}
    }
  }
});
