// (c)2008 Transinsight GmbH - www.transinsight.com - All rights reserved.

/*
features:
 - runs up to n ajax connections simulatniously
 - restarts connections that fail

usage:
 - you only need one instance of ConnectionPool per application.
 - but each frame has to include connection on it's own.
*/

function ConnectionPool()
{
 this.waiting = [];
 this.running = {};
 this.runningCount = 0;
 this.nextIndex = 0;
 this.maxRunning = 2;
 this.maxRetries = 3;

 this.add = ConnectionPool_add;
 this.run = ConnectionPool_run;
 this.terminate = ConnectionPool_terminate;

 this.handleFail = Connection_bind( this, ConnectionPool_handleFail );
 this.handleFinish = Connection_bind( this, ConnectionPool_handleFinish );
}

function ConnectionPool_add( connection )
{
 connection.pool = this;
 connection.retries = 0;
 this.waiting.push( connection );
 if( this.running.length < this.maxRunning )
  this.run();
}

function ConnectionPool_run()
{
 while( this.runningCount < this.maxRunning && 0 < this.waiting.length )
 {
  var connection = this.waiting.shift();
  connection.index = this.nextIndex++;
  connection.user_fail = connection.on_fail;
  connection.user_finish = connection.on_finish;
  connection.on_fail = this.handleFail;
  connection.on_finish = this.handleFinish;

  this.running[connection.index] = connection;
  this.runningCount++;

  connection.establish();
 }
}

function ConnectionPool_terminate( connection )
{
 delete this.running[connection.index];
 this.runningCount--;
 this.run();
}

function ConnectionPool_handleFail( connection )
{
 connection.retries++;
 if( connection.retries == this.maxRetries )
 {
  if( connection.user_Fail )
   connection.user_Fail( connection );
  this.terminate( connection );
 }
}

function ConnectionPool_handleFinish( connection )
{
 try {
  if( connection.user_finish )
   connection.user_finish( connection );
 }
 finally {
  this.terminate( connection );
 }
}

var connectionPool = new ConnectionPool();
