var http = createRequestObject();
requestsCounter = 0;

function createRequestObject(htmlObjectId){
  var xmlhttp;
  try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
      xmlhttp = false;
    }
  }
	  if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		xmlhttp = new XMLHttpRequest();
	  }
  return xmlhttp;
  
}

function ajaxObject(initVal) {
	this.STATE_NOT_READY = 0;
	this.STATE_READY = 1;
	this.STATE_INPROGRESS = 2;
	this.STATE_ERROR = 2;

	this.state = this.STATE_NOT_READY;
	this.data = initVal;
	this.callback = null;
	this.httpObj = null;
	this.waitResponse = false;
	this.requestParams = null;

	this.httpObj = createRequestObject();
}

ajaxObject.ajaxAvailable = function()
{
	return http != false;
}
ajaxObject.prototype = {

	ready: function() {
		return this.state ==  this.STATE_READY;
	},
	request: function(url, params, callback, waitResponse) {
		this.waitResponse = waitResponse;
		this.requestParams = params;
		var self = this;
		var paramStr = '';
		for(var name in params) {
			if(paramStr != '') paramStr += '&';
			if(params[name] instanceof Array) {
				paramStr += name+'=';
				for(var i in params[name]) {
					if(i>0) paramStr += '|';
					paramStr += params[name][i];
				}
			}
			else
				paramStr += name+'='+Url.encode(params[name]);
		}
	   	this.httpObj.open('POST', url, true);
	   	this.httpObj.setRequestHeader('Content-Length', paramStr.length);
	   	this.httpObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
		this.callback = callback;
		this.state = this.STATE_INPROGRESS;

	    this.httpObj.onreadystatechange = function() { self.onreadystatechange(); }
		if(this.waitResponse) requestsCounter++;
	    this.httpObj.send(paramStr);
	},
	load: function(url, params, callback, waitResponse) {
		this.request(url, params, callback, waitResponse)
	},
	upload: function(url, command, values, callback,waitResponse) {
		if(typeof(waitResponse) == 'undefined')
			waitResponse = 1;
		var params = { action: command };
		for(name in values) {
			params[name] = values[name];
		}
		this.request(url, params, callback, waitResponse);
	},
	command: function(url, command, values, callback, waitResponse) {
		this.upload(url, command, values, callback,waitResponse);
	},
	setReady: function() {
		this.state = this.STATE_READY;
	},
	onreadystatechange: function() {
		if (this.httpObj.readyState == 4)
		{
			if(this.httpObj.status == 200)
			{
				if(this.waitResponse) requestsCounter--;
				var responseText = this.httpObj.responseText;
				if(!responseText)
				{
					return;
				}
				var qs = new Querystring(responseText)
				var result = qs.get('error', '');

				if(result == 'SESSION_EXP')
				{
					if(confirm("Your session is expired. Click OK to login"))
					{
						location.href=location.href;
					}
				}
				else if(this.callback)
					this.callback(this, qs);
			}
		}
	}
}