// JavaScript Document
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: "/img/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 ) )
    };
  }
}


