// HtmlRequest: multi-threaded ajax/html request handler
// callback function accepts two arguments- data, and request type
function HtmlRequest(){
	this.threads = [];
};

// rType is passed through to the callback function if set, to identify what sort of request was made
// if rType is a function, it will be used as the callback
HtmlRequest.prototype.makeRequest = function(url, p, rType){

	//console.log(url);

	var that = this, i;
	
	// post = null if no post variables
	if (!p) p = null;
	
	
	// get idle (or new) thread
	if (!(i = this.getThread()) == null) return false;
	r = this.threads[i].obj;
	
	
	// set up the request
	if (p){
		r.open('POST', url, true);
		r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		r.setRequestHeader("Content-length", p.length);
		r.setRequestHeader("Connection", "close");
	}
	else r.open('GET', url, true);
	
	
	// set up the callback function
	if (typeof rType === 'function')
		r.onreadystatechange = function(){ 
			if (that.threads[i].obj.readyState == 4){
				that.clearThread(i);
				rType(that.threads[i].obj.responseText);
			}
		};
	else
		r.onreadystatechange = function(){
			if (that.threads[i].obj.readyState == 4)
				that.clearThread(i); 
		};
	
	
	// send the request
	r.send(p);

	// return true- TODO: return false if request somehow fails...
	return true;
};
// sets a current request object to available
HtmlRequest.prototype.clearThread = function(i){
	var that = this;
	setTimeout(function(){that.threads[i].busy = false;}, 2000);
};

// find an unused request object, or 
HtmlRequest.prototype.getThread = function(){
	for (i = 0; i < this.threads.length; i++){
		if (!this.threads[i].busy)
			break;
	}
	if (!this.threads[i])
		this.threads[i] = this.makeObj();
	
	this.threads[i].busy = true;	
	return this.threads[i] ? i : null;
};
// create a new XMLHttpRequest object
HtmlRequest.prototype.makeObj = function(){
	if (window.XMLHttpRequest) // Mozilla, Safari,...
		r = {'busy' : 0, 'obj' : new XMLHttpRequest()};
  else if (window.ActiveXObject) { // IE
    try {
        r = {'busy' : 0, 'obj' : new ActiveXObject("Msxml2.XMLHTTP")};
    } catch (e) {
      try {
          r = {'busy' : 0, 'obj' : new ActiveXObject("Microsoft.XMLHTTP")};
      } catch (e) {}
  }}
		
	return r ? r : false;
};
