// pushes a small (4k) gif to the user if the cookie does not exist to test bandwidth
// then sets a cookie with a Number value.
var bandwidth;
var bandwidthNumeric = 0;
var hasCheckedBandwidth = false;




function bwChecker() {
	this.setCookie = function( name, value, expires, path, domain, secure ){
		var today = new Date();
		today.setTime( today.getTime() );
		if ( expires ){
			expires = expires * 1000 * 60 * 60 * 24;
		}
		var expires_date = new Date( today.getTime() + (expires) );
		document.cookie = name + "=" +( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
	}
	
	this.getCookie = function(name) {
		var dc = document.cookie;
	  	var prefix = name + "=";
	 	var begin = dc.indexOf("; " + prefix);
	  	if (begin == -1) {
	    	begin = dc.indexOf(prefix);
	    	
	    	if (begin != 0) {
	    		return null;
	    	}
	  	} 
	  	else {
	    	begin += 2;
	    }
	  	var end = document.cookie.indexOf(";", begin);
	  	if (end == -1) {
	    	end = dc.length;
	    }
	  	return unescape(dc.substring(begin + prefix.length, end));
	}

	this.checkForBWCookie = function() {
		var myCookie = this.getCookie('recordedBW');
		//alert(myCookie);
		if(myCookie != null) {
			bandwidthNumeric = myCookie;
			
			//alert('recordedBW cookie found '+bandwidthNumeric );
			this.setBWBucket(bandwidthNumeric);
		} else {
			this.drawCSImageTag( '/media/en_US/360s/ATTlogo.gif',66237,'style="display:none"');
		}
	}
	
	this.setBandwidth = function(bwInBps) { // called by bw sniffer
		this.setBWBucket(bwInBps);
		this.setCookie("recordedBW",bwInBps,"0","/");
	}
		// currently set to high
	this.setBWBucket = function(bw) {
		//alert('in setBWBucket '+bw );
		if(bw >= 64) {
			bandwidth = 'high';
		}
		hasCheckedBandwidth = true;
		//alert('bandwidth = ' + bw + ' KB, value=' + bandwidth);
	}
	
	
	this.drawCSImageTag = function( fileLocation, fileSize, imgTagProperties ) {
		start = (new Date()).getTime();
		loc = fileLocation + '?t=' + escape(start);	
		document.write('<img src="' + loc + '" ' + imgTagProperties + ' onload="bwCheck.computeConnectionSpeed(' + start + ',' + fileSize + ');">');
		return;
	}

	this.computeConnectionSpeed = function( start, fileSize ) {
		//alert('in computeConnectionSpeed');
		end = (new Date()).getTime();
		connectSpeed = (Math.floor((((fileSize * 8) / ((end - start) / 1000)) / 1024) * 10) / 10);
		this.setBandwidth(connectSpeed);
		bandwidthNumeric = connectSpeed;
		return connectSpeed;
	}
}
var bwCheck = new bwChecker();






