/* Copyright 2004 Macromedia, Inc. All rights reserved.

The following is Sample Code and is subject to all restrictions

on such code as contained in the Macromedia Flash Communication

Server MX 1.5 End User License Agreement .

*/



application.onConnect = function(p_client, p_autoSenseBW)

{

	trace("onConnect");

	//Add security here



	this.acceptConnection(p_client);



	if (p_autoSenseBW)

		this.calculateClientBw(p_client);

	else

		p_client.call("onBWDone");

}



Client.prototype.getStreamLength = function(p_streamName) {

	trace("getStreamLength:"+p_streamName);

	return Stream.length(p_streamName);

}



application.calculateClientBw = function(p_client)

{

	p_client.payload = "";

	for (var i=0; i<1024; i++)

		p_client.payload += "1";	//2K



	var res = new Object();

	res.latency = 0;

	res.bwTime = 0;

	res.count = 0;

	res.sent = 0;

	res.client = p_client;

	var stats = p_client.getStats();

	res.beginningValues = {b_down:stats.bytes_out, b_up:stats.bytes_in, time:(new Date()).getTime()};

	res.onResult = function(p_val) {

		this.count++;

		var timePassed = ( (new Date()).getTime() - this.beginningValues.time );



		if ( this.count == 1 )

		{

			this.latency = timePassed;

		}



		// If we have a hi-speed network with low latency send more to determine

		// better bandwidth numbers, send no more than 6 packets

		if (( this.count >= 4 && this.count < 6)&&(timePassed < 2000))

		{

			this.sent++;

			this.client.payload += this.client.payload;

			this.client.call("onBWCheck", this, this.client.payload);

		}

		else if ( this.sent == this.count )

		{	delete this.client.payload;

			// Got back responses for all the packets compute the bandwidth.

			var stats = this.client.getStats();

			var deltaDown = (stats.bytes_out - this.beginningValues.b_down)*8/1024;

			var deltaTime = (((new Date()).getTime() - this.beginningValues.time) -

							(this.count - 3) * this.latency)/1000;

			var kbitDown = Math.round(deltaDown/deltaTime);

			trace("(d) down:"+kbitDown+" kilobits/s " );



			this.client.call("onBWDone", null, kbitDown );

		}

	}

	// First payload is empty to check latency

	res.sent++;

	p_client.call("onBWCheck", res, "");

	for ( var k = 0; k < 3; k++ )

	{

		res.sent++;

		p_client.call("onBWCheck", res, p_client.payload);

		p_client.payload += p_client.payload;

	}

}

