﻿function Ajax(url,method,cbf){
    this.ajax = this;
	this.act = false;
	this.xml = null;
    this.cbf = cbf;
    this.url = url;
	this.method = method;
	this.init();
}
Ajax.prototype.init = function(){
	this.xml = (window.XMLHttpRequest ? new XMLHttpRequest : (window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : null));
	if(!this.xml){
		this.act = false;
	}else{
		this.act = true;
	}
	this.encFunc = encodeURIComponent ? encodeURIComponent : escape;
}
Ajax.prototype.sendRQ = function (parameters){
	if(!this.act){ return; }
	if(this.xml.readyState != 0){ this.xml.abort(); }
	
	this.xml.onreadystatechange = function(){ajax.handleResponse(ajax);}
	var sParams = this.ParseParams(parameters);
	
	if(this.method.toUpperCase() == "GET"){
    	this.xml.open("GET",this.url +"?"+ sParams);
       	this.xml.send(null);
    }else{
        this.xml.open("POST",this.url);
        this.xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        this.xml.setRequestHeader("Content-length", sParams.length);
   	    this.xml.send(sParams);
    }
}

Ajax.prototype.ParseParams = function (parameters){
    var sParams = '';
    for(var i=0; i<parameters.length; i++){
        sParams += (sParams.length > 0 ? "&" : "") + parameters[i][0] +"="+ this.encFunc(parameters[i][1]);
    }
    return sParams;
}
Ajax.prototype.send = function (parameters){
	if(!this.act){ return; }
	if(this.xml.readyState != 0){ this.xml.abort(); }
	
	this.xml.onreadystatechange = function(){ajax.handleResponse(ajax);}

    //alert(this.url +"?"+ parameters);
	if(this.method.toUpperCase() == "GET"){
    	this.xml.open("GET",this.url + "?" + parameters);
       	this.xml.send(null);
    }else{
        this.xml.open("POST",this.url);
        this.xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        this.xml.setRequestHeader("Content-length", sParams.length);
   	    this.xml.send(parameters);
    }
}


Ajax.prototype.handleResponse = function(ajax){
    switch(ajax.xml.readyState){
        case 0:
            //unitialized
            break;
        case 1:
            //loading
            break;
        case 2:
            //loaded
            break;
        case 3:
            //interactive
            break;
        case 4:
            //complete
            if(ajax.xml.status==200){
                if(typeof(ajax.cbf)=='function'){
                    ajax.cbf(ajax.xml.responseText)
                }
            }else{
                 //alert(ajax.xml.responseText);
                ajax.cbf( 'WriteMessage(\'' + ajax.xml.responseText + '\');' );//  alert(ajax.xml.responseText);
            }
    }
}

