﻿$.fn.hasAttr = function (name, value) {
	return ( this.attr(name) !== undefined && value == undefined ) || ( this.attr(name) !== undefined && value == this.attr(name) );
};

jQuery.extend(jQuery.expr[':'], {
	focus: function (element) {
		return element == document.activeElement;
	}
});

function focusAndSelect(id)
{
	$('#' + id).focus();
	return false;
}

function ShowNotification(id) {
	//settings
	var fadeSpeed = 100, fadeTo = 0.5, topDistance = 5;
	var topbarME = function () { $('#' + id).fadeTo(fadeSpeed, 1); };
	var topbarML = function () { $('#' + id).fadeTo(fadeSpeed, fadeTo); };
	var inside = false;

	//do
	$(window).scroll(function () {
		position = $(window).scrollTop();
		if (position > topDistance && !inside) {
			//add events
			topbarML();
			$('#' + id).bind('mouseenter', topbarME);
			$('#' + id).bind('mouseleave', topbarML);
			inside = true;
		}
		else if (position < topDistance) {
			topbarME();
			$('#' + id).unbind('mouseenter', topbarME);
			$('#' + id).unbind('mouseleave', topbarML);
			inside = false;
		}
	});
}

function DetectBrowserCaps(url) {
    if (ReadCookie("_sr") == null) {
        CreateCookie("_sr", screen.width + "x" + screen.height, 30);
        CreateCookie("_cd", screen.colorDepth, 30);

        var st = new SpeedTest();
        if (url != null) st.imgUrl = url;
        st.run(
        {
            onEnd: function (speed) {
                CreateCookie("_cs", speed.Kbps, 30);

                /*
                var connectionType = "Unknown";
                if ( speed.Kbps == 0 ) connectionType = "Unknown";
                else if (speed.Kbps <= 28.8) connectionType = "Dial-up 28.8k";
                else if (speed.Kbps <= 33.6) connectionType = "Dial-up 33.6k";
                else if (speed.Kbps <= 56) connectionType = "Dial-up 56k";
                else if (speed.Kbps <= 384) connectionType = "DSL/Cable 384k";
                else if (speed.Kbps <= 768) connectionType = "DSL/Cable 768k";
                else if (speed.Kbps <= 1500) connectionType = "Cable/DSL 1.5Mbps";
                else if (speed.Kbps <= 1544) connectionType = "Full T1 1.544Mbps";
                else if (speed.Kbps <= 3000) connectionType = "High Speed Internet 3.0Mbps";
                else if (speed.Kbps <= 6000) connectionType = "High Speed Internet 6.0Mbps";
                else if (speed.Kbps <= 15000) connectionType = "High Speed Internet 15.0Mbps";
                else connectionType = "High Speed Internet 30.0Mbps+";

                CreateCookie("_cs", connectionType, 30);
                */
            }
        });
    }
}

function ReadCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function CreateCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

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 = {
    runCount: 3                 // how many times we want to run the test for
  , imgUrl: "Content/speedtest.jpg"    // Where the image is located at
  , size: 59917                // bytes
  , run: function (options) {
      this.results = []; // reset the results
      this.callback = (options && options.onEnd) ? options.onEnd : null;
      this.runTrial(0, options);
  }

  , runTrial: function (i, options) {
      var imgUrl = this.imgUrl + "?r=" + Math.random();
      var me = this;
      var testImage = new Image();
      testImage.onload = function () {
          me.results[i].endTime = (new Date()).getTime();
          me.results[i].runTime = me.results[i].endTime - me.results[i].startTime;

          if (i < me.runCount - 1)
              me.runTrial(i + 1); // run the next trial
          else {
              // Execute the callback
              if (me.callback)
                  me.callback(me.getResults());
          }
      };
      this.results[i] = { startTime: (new Date()).getTime() };
      testImage.src = imgUrl;
  }

  , getResults: function () {
      var totalRunTime = 0;
      for (var i = 0; i < this.runCount; i++) {
          if (!this.results || !this.results[i].endTime)
              return null; // exit if we found no endTime.  --> test’s not done yet
          else
              totalRunTime += this.results[i].runTime;
      }

      var avgRunTime = totalRunTime / this.runCount;

      return {
          avgRunTime: avgRunTime,
          Kbps: (this.size * 8 / 1024 / (avgRunTime / 1000)), 
          KBps: (this.size / 1024 / (avgRunTime / 1000))
      };
  }
}
