﻿    var xmlHttp;
    var dataSize=0;
    var startTime = 0;
    var endTime = 0;
    var imageURL = "";
    var objImage;
    var intBandWidthRate = 0;
    var sImageURL="/bwcheck/bandwidth.jpg";
     
    
    function createVODCookie(iBandWidthRate)
    {
        intBandWidthRate = iBandWidthRate;
		if (getCookie("bandwidth") == null)
        {
		    startRequest(sImageURL);
        }
    }
    
    function createXMLHttpRequest() 
    {
        if (window.XMLHttpRequest) 
        {
            xmlHttp = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) 
        {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    
    function startRequest(sURL) 
    {
        startTime = new Date().getTime(); 
        imageURL = sURL + "?startTime=" + Math.random();
        createXMLHttpRequest();
        xmlHttp.onreadystatechange = handleStateChange;
        xmlHttp.open("GET",imageURL, true);
        xmlHttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 1900 00:00:00 GMT");
        xmlHttp.setRequestHeader("Content-Type","image/jpeg");
        xmlHttp.send(null);
    }
    
    function calcThroughput()
    {
        var diffTimeMilliSeconds = endTime-startTime;
        var diffTimeSeconds = diffTimeMilliSeconds/1000;
        diffTimeSeconds = Math.round(diffTimeSeconds);
        if (diffTimeSeconds == 0)
        {
            diffTimeSeconds = 1; // This is so that we don't a division by zero.
        }
        var bits = Math.round(dataSize * 8); //convert to bits
        var kbits = Math.round(bits/1024); //convert bits to kbits;
        var throughput = Math.round(kbits/diffTimeSeconds);
        throughput = Math.round(throughput * .93); //account for IP packet header overhead -- averages about 7%

        if ((isNaN(throughput) == false) || (throughput != "undefined"))
        {
            var arrDomain = document.domain.split(".");
            var bandwidthCookieDomain = "";
	        if (arrDomain.length >= 2)
	        {
		        arrDomain1 = new Array(arrDomain[arrDomain.length-2], arrDomain[arrDomain.length-1]);
		        bandwidthCookieDomain = "." + arrDomain1.join(".");
		    }
            setCookie("bandwidth",throughput,null,"/",bandwidthCookieDomain,null);
        }
    }
    function handleStateChange() 
    {
        if(xmlHttp.readyState == 4) 
        {
            if(xmlHttp.status == 200) 
            {
                endTime = new Date().getTime();
                dataSize = 204337; //xmlHttp.getResponseHeader("Content-Length");
                if (dataSize == null || dataSize=="undefined")
                {
                    dataSize = 0;
                }
                calcThroughput();
            }
        }
    }

