function httpRequest()
{
  var xmlHttp=null;
  try
  {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
  }
  catch(e)
  {
    // Internet Explorer
    try
    {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  return xmlHttp;
}

var requestRefs = new Array();

function request(parent, type)
{
	this.parent = parent;
	this.type = type;
	
	this.request = new httpRequest();
	this.loading = 0;
	this.response = "";
	this.tokens = new Array();
	this.callback = null;
	
	this.urlBase = "api/?cmd=";
	
	this.get = function(url, callback)
	{
		this.callback = callback;
		
		this.request.open("GET", this.urlBase + url, true);
		this.request.send(null);
		
		this.loading = 1;

		var r = requestRefs.length;
		this.request.onreadystatechange = function(){ requestRefs[r].ready(); };
		requestRefs[r] = this;
	}
	
	this.post = function(url, jsonText, callback)
	{
		this.callback = callback;
		
		this.request.open("POST", this.urlBase + url, true);
		this.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		this.request.setRequestHeader('Content-Length', jsonText.length);
		this.request.send("cmd="+jsonText);
		
		this.loading = 1;
		
		var r = requestRefs.length;
		this.request.onreadystatechange = function(){ requestRefs[r].ready(); };
		requestRefs[r] = this;
	}
		
	this.ready = function()
	{
		if(this.request.readyState == 4 || this.request.readyState == "complete")
		{		
			this.loading = 0;
			
			this.response = this.request.responseText;
			
			var data = null;
			
			try
			{
				data = JSON.parse(this.response);				
			}
			catch(e)
			{
				if(debug)
				{
					alert("ERROR: Request response exception "+e+" catched.\n"+this.response);
				}
			}
			
			//could be replaced with eval
			if(this.callback)
				this.callback(this.type, data);
				
			if(this.parent.requestCallback)
				this.parent.requestCallback(this.type, data);
		}
	}
}

function CReqs(parent)
{
	this.parent = parent;
	
	this.requests = new Array();
	
	this.get = function(url, type, callback)
	{
		var r = new request(this.parent, type);
		r.get(url, callback);
		
		this.requests.push(r);
	}
	
	this.post = function(url, parameters, type, callback)
	{
		var r = new request(this.parent, type);
		r.post(url, parameters, callback);
		
		this.requests.push(r);
	}
			
	this.areLoading = function()
	{
		for(var i = 0; i < this.requests.length; i++)
		{
			if(this.requests[i].loading)
			{
				return 1;
			}
		}
		
		return 0;
	}
}

