// {{{
/**
 * class for sending AJAX requests
 *
 * upon completion of the request, response_method (a reference of which should be passed to 
 * the constructor) is called with 3 parameters: 
 * (1) http status code, (2) response headers and (3) response content
 */

Ajax = function()
{   
    if(arguments[0])
        Ajax.construct.apply(this,arguments);
}
Ajax.construct = function(_response_method,_response_args)
{
    if(!_response_args)
        _response_args = [];
    
    // Create a new XMLHttpRequest object to talk to the Web server 
    var xmlHttp = false;
    
    try {
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e) {
        try {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(e2) {
            xmlHttp = false;
        }
    }
    
    if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
        xmlHttp = new XMLHttpRequest();
    }
    
    this.response_method = _response_method;
    this.response_args = _response_args;
    this.xml_http = xmlHttp;
    this.request_method = 'GET';
    this.asynch = true;
    this.response_type = 'JSON';
}

Ajax.prototype.send = function(url,content)
{
    if(!url) return false;
    if(!content) content = null;
    
    var receiver = this;
    
    this.xml_http.open(this.request_method,url,this.asynch);
    
    // {{{ in IE, request headers can only be modified after open() is called
    if(this.request_method == 'POST')
    {
        this.xml_http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    }
    this.xml_http.setRequestHeader('Connection', 'close');
    // }}}
    
    this.xml_http.onreadystatechange = function(){receiver.stateChange()}
    this.xml_http.send(content);
}
Ajax.prototype.stateChange = function()
{
    if(this.xml_http.readyState==4)
    {
        var arg,i;
        var re = this[this.response_type+'Response']();
        var args = [this.xml_http.status,this.xml_http.getAllResponseHeaders(),re];
        for(i=0; this.response_args[i] != undefined; i++)
        {
            args.push(this.response_args[i]);
        }
        this.response_method.apply(this,args);
        //this.response_method(1,2);
        //alert(this[this.response_type+'Response']()[0]);
    }
    //alert(this.xml_http.responseText);
}
Ajax.prototype.JSONResponse = function()
{
    eval('var re = ' + this.xml_http.responseText+';');
    return re;
}
// }}}