var XHRFactory = (function(){
 // static private member
 var stack = new Array();
 var poolSize = 10;
 
 var nullFunction = function() {}; // for nuking the onreadystatechange
 
 // private static methods
 
 function createXHR_old() {
  if (window.XMLHttpRequest) {
       return new XMLHttpRequest();
     } else if (window.ActiveXObject) {
       return new ActiveXObject('Microsoft.XMLHTTP')
     }
	 return null;
    }

function createXHR() {
	var req;
	if( window.XMLHttpRequest && ! ( window.ActiveXObject ) ) {
		try {
			req = new XMLHttpRequest();
		} catch(e) {
			try {
				req = window.createRequest();
			} catch( e ) {
				req = false;
			}
		}
	// branch for IE/Windows ActiveX version
	} else if ( window.ActiveXObject ) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				req = false;
			}
		}
	}
	return req;
}
 // cache a few for use
 for (var i = 0; i < poolSize; i++) {
  stack.push(createXHR());
 }
 
 // shared instance methods
 return ({
  release:function(xhr){
   xhr.onreadystatechange = nullFunction;
   stack.push(xhr);
  },
  destroy:function(xhr){
	  xhr.onreadystatechange = nullFunction;
	  xhr = null;
	  stack.push(createXHR());
  },
  annihilate:function(){
	  while( stack.length > 0 ) {
		  stack.pop();
	  }
	 for (var i = 0; i < poolSize; i++) {
	  stack.push(createXHR());
	 }
  },
  getInstance:function(){
   if (stack.length < 1) {
    return createXHR();
   } else {
    return stack.pop();
   }
  },
  toString:function(){
   return "stack size = " + stack.length;
  }
 });
})();

