var EJSC_DEBUG = "ON";

var XMLPool = {
	activePool: [],
	requestPool: [],
	activeXObjects: ["MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"],
	activeRequestType: null,

	MaxPoolSize: 8,
	
	__createHTTPRequest: function() {
		if (this.activeRequestType == null) {
			try { 
				this.activeRequestType = "Native";
				return new XMLHttpRequest(); 
			} catch (e) {}
			for (var i=0; i < this.activeXObjects.length; i++) {
				try {
					this.activeRequestType = this.activeXObjects[i];
					return new ActiveXObject(this.activeXObjects[i]);
				} catch (e) {}
			}
		} else {
			if (this.activeRequestType == "Native") {
				try { return new XMLHttpRequest(); } catch (e) {}
			} else {
				try { return new ActiveXObject(this.activeRequestType); } catch (e) {}
			}
		}
		this.activeRequestType = null;
		throw "Unable to create XMLHttpRequest object!";
	},
	
	__getHttpRequest: function() {
		if (this.requestPool.length > 0) {
			return this.requestPool.pop();
		}
		return this.__createHTTPRequest();
	},
	
	__returnHttpRequest: function(request) {
		request.onreadystatechange = function() { };
		if (this.requestPool.length >= this.MaxPoolSize) { delete request; }
		else this.requestPool.push(request); 
	},

	sendRequest: function(url, handler, data, reference) {
		var request = this.__getHttpRequest();
		request.open((data==undefined?"GET":"POST"), url, (handler != undefined));
		if(handler) {
			var self = this;
			request.onreadystatechange = function() {
				if (request.readyState == 4) {
					request.onreadystatechange = function () {	};
					handler(request, reference);
					self.__returnHttpRequest(request);
				}
			};
		} else {
			request.onreadystatechange = function() {};
		}
		try {
			if (data == undefined) { data = null; }
			else request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			request.send(data);
		} catch (e) {
			this.__returnHttpRequest(request);
			throw "Connection failed!";
		}
		if (handler == undefined) this.__returnHttpRequest(request);
	}
}

function debug(msg) {
	if (EJSC_DEBUG == "ON") {
		alert(msg);
	}	
}