// ############################################################
// # cspeed.js                                               #
// #                                                         #
// # Connection speed detection via JavaScript 1.2. You      #
// # need to embed this js file in the head of your website. #
// # Then, AFTER the page is completely loaded, you can call #
// # the getConnectionSpeed( true / false ) function, to     #
// # determine the connection speed of your user.            #
// #                                                         #
// # author:          Alexander Graf                         #
// # e-mail:          alexander.graf@tiscover.com            #
// # created:         2006/08/21 15:22                       #
// # last modified:   2006/08/21 16:04                       #
// # version:         1.2                                    #
// #                                                         #
// # history:                                                #
// #     1.0    First Version                                #
// #     1.1    Fixed for Opera and IE                       #
// #     1.2    Added cookie support                         #
// #                                                         #
// ###########################################################

// #################################### USAGE EXAMPLE #####################################
// #	                                                                                  #
// #	<script type="text/javascript" src="cspeed.js" language="javascript1.2"><\script> #
// #	                                                                                  #
// #	<script type="text/javascript">                                                   #
// #	<!--//--><![CDATA[//><!--                                                         #
// #		addEvent( window, 'load', SetConnectionSpeed );                               #
// #		                                                                              #
// #		function SetConnectionSpeed() {                                               #
// #			document.write( getConnectionSpeed( false ) );                            #
// #		}                                                                             #
// #	//--><!]]>                                                                        #
// #	<\script>                                                                         #
// ########################################################################################


// Change this if you want. The first paraneter is the url of an image file and 
// the second parameter is the EXACT size of the image in bytes. 
drawCSImageTag( 'speedtest/noise.jpg', 69671 );

// #######################################################################
// ######################## DON'T EDIT BELOW HERE ########################
// #######################################################################


connectionSpeed = 0;


//
// addEvent()
// ##########
//
// Adds an event via the DOM.
//                           -- UNSUPPORTED!
//
function addEvent( objObject, evType, fnFunction ) { 
	if ( objObject.addEventListener ) {
		objObject.addEventListener( evType, fnFunction, false ); 
		return true;
	} else if ( objObject.attachEvent ) {
		return objObject.attachEvent( "on" + evType, fnFunction );
	} else {
		return false;
	}
}


//
// getConnectionSpeed()
// ####################
//
// Returns the connection speed or type
//
// parameters:
//     (boolean)  Whether to return the speed in kbps (false) or as a type from 1(slowest) to 3(fastest) (true)
//
// returns:
//     (integer)  Either the speed in kbps or a connection type between 1 and 3.
//
function getConnectionSpeed( asType ) {
	if( asType == true ) {
		return connectionType( connectionSpeed );
	} else {
		return parseInt( connectionSpeed );
	}
}


//
// drawCSImageTag()
// ################
//
// Draws an invisible image and records the time taken to load the image.
//
// parameters:
//     (string)   The location of the file to be loaded
//     (integer)  The size of the image file in bytes (must be accurate!)
//
// returns:
//     (void)
//
function drawCSImageTag( fileLocation, fileSize ) {
	if( readCookie( 'TSiteConnectionSpeed' ) != '' ) {
		connectionSpeed = computeConnectionSpeed( ' + start + ',' + fileSize + ' ); // don't do anything if we already know the speed
	}
	
	start = (new Date()).getTime();
	loc = fileLocation + '?t=' + escape(start);
	
	document.write( '<img style="display: none; visibility: hidden; width: 1px; height: 1px; overflow: hidden;" src="' + loc + '" onload="connectionSpeed=computeConnectionSpeed(' + start + ',' + fileSize + ');">' );
	return null;
}


//
// connectionType()
// ################
//
// Returns 1, 2 or 3 as the connection speed. 1 is very slow (modem speed)
// while 2 stands for ISDN or UMTS speed (below 256k). 3 is high speed
// connection.
//
// parameters:
//     (integer)   The speed determined by computeConnectionSpeed()
//
// returns:
//     (integer)   Integer describing the connection speed
//
function connectionType( speed ) {
	if( speed ) {
		if( speed < 128 )
			return 1;
		else if( speed < 256 )
			return 2;
		else
			return 3;
	} else
		return 2;
}


//
// computeConnectionSpeed()
// ########################
//
// This function returns the speed in kbps of the user's connection,
// based upon the loading of a single image.  It is called via onload 
// by the image drawn by drawCSImageTag().
//
// parameters:
//     (integer)   Start time of image loading
//
// returns:
//     (integer)   Connection speed in kbps
//
function computeConnectionSpeed( start, fileSize ) {
	tCSpeed = readCookie( 'TSiteConnectionSpeed' );
	
	if( tCSpeed == '' ) {
		tCSpeed = ( Math.floor( ( ( ( fileSize * 8 ) / ( ( ( new Date() ).getTime() - start ) / 1000 ) ) / 1024 ) * 10 ) / 10 );
		createCookie( 'TSiteConnectionSpeed', tCSpeed, 1 );
	} else {
		tCSpeed = parseFloat( tCSpeed );
	}
	
	return tCSpeed;
}


//
// createCookie()
// ##############
//
// This function creates a cookie.
//
// parameters:
//     (string)   Name of the cookie
//     (string)   Value of the cookie to set
//     (integer)  Number of days after which the cookie should expire
//
// returns:
//     (void)
//
function createCookie( name, value, days ) {
	if( days ) {
		var date = new Date();
		date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
		var expires = "; expires=" + date.toGMTString();
	} else
		var expires = "";
		
	document.cookie = name + "=" + value + expires + "; path=/";
}


//
// readCookie()
// ############
//
// This function reads a cookie.
//
// parameters:
//     (string)   Name of the cookie to read
//
// returns:
//     (string)   Value of the cookie
//
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 "";
}


//
// eraseCookie()
// #############
//
// This function erases a cookie.
//
// parameters:
//     (string)   Name of the cookie
//
// returns:
//     (void)
//
function eraseCookie( name ) {
	createCookie( name, "", -1 );
}
