var Cathmhaol = window.Cathmhaol || {};

/**
* Creates a pool of Cathmhaol.Ajax objects that can be used to process requests. According to the W3C spec, this should be limited to two simultaneous connections.
*
* @argument	{integer} poolSize
*
* @requires	Cathmhaol.Ajax	http://js.cathmhaol.com/cjl-ajax.js
* @requires	Cathmhaol.Request	http://js.cathmhaol.com/cjl-request.js
*
* @author	Robert King (hrobertking@cathmhaol.com)
*
* @example	var oConPool = new Cathmhaol.AjaxPool(); oConPool.send("http://www.cathmhaol.com/license/index.asp", true, function(xhr) { alert(xhr.responseText); }, "", document.forms[0]);
*/
Cathmhaol.AjaxPool = function(poolSize) {
	/**
	* @method	Opens an XmlHttpRequest session and sends the request
	* @returns	{void}
	* @argument	{Cathmhaol.Request} request
	* @argument	{function} callback
	* @argument	{integer} wait
	*/
	this.send = function(request, callback, wait) {
		_q.push({request: request, callback: callback, timeout: wait});
		return;
	};

	/**
	* @method	Processes the next request using the available connection.
	* @returns	{void}
	* @argument	{string} id
	*/
	function _nextRequest(id) {
		//Consider enforcing the specified limit of two simultaneous connections by checking the state of each connection in the pool.
		if (_q.length > 0) {
			_r[id] = _q.shift();
			if (_r[id]) {
				_s[id].unsubscribe();
				_s[id].finished.subscribe(_r[id].callback);
				_s[id].finished.subscribe(function() { me._n.apply(me, [id])});
				_s[id].timeout = _r[id].wait;
				_s[id].send(_r[id].request);
			}
		}
		return;
	}

	/**
	* Constructor
	*
	* PRIVATE VARIABLES
	* _c	Generic counter
	* _q	Array of requests
	* _r	Hash of open requests
	* _s	Hash of Cathmhaol.Ajax objects
	*/
	var me = this;
	var _c = 0, _q = new Array(), _r = [], _s = [];

	poolSize = poolSize || 2;
	for (_c = 0; _c < poolSize; _c++) {
		var _o = new Cathmhaol.Ajax();
		_s[_o.id] = _o;
		_s[_o.id].finished.subscribe(function() { me._n.apply(me, [_s[_o.id].id])});
	}
};

