var cacheAj = function(param_, url_, callFunc_) {
	this.param = param_;
	this.url = url_;
	this.callFunc = callFunc_;
};

var memCacheAj = function(param_, url_, callFunc_) {
	this.param = param_;
	this.url = url_;
	this.callFunc = callFunc_;
};

function sendAjax(){
	//Détruit les ckeditor des messages de l'accueil du portail
	actionSendAj = arguments[0];
	ajaxArgs = arguments;
	// Mise en mémoire des paramètres d'appel ajax, mais pas dans l'appel du TDB pour une impression
	if (actionSendAj.substr(0, 3) == 'Sup') {
		if (!confirm('Confirmez vous la supression ?')) {
			return false;
		}
	}
	var url = WEBROOT + 'inc/ajax/' + actionSendAj + '.php';
	var callFunc = eval("set" + actionSendAj);
	var param = '';
	var val;
	if (arguments[1] != null) {
		for (var i = 0; i < arguments.length; i++) {
			val = encodeURIComponent(arguments[i]);
			param += 'arg' + i + '=' + val + '&';
		}
	}
	ajax.tCache.push(new cacheAj(param, url, callFunc));
	// Mise en mémoire du type de fiche pour rafraichissement lors d'une modification
	// dans le pop-up d'une fiche, mais pas dans l'appel du TDB pour une impression
	ajax.sendAjax();
}

/*
 url-loading object and a request queue built on top of it
 */
/* namespacing object */
var net = new Object();

net.READY_STATE_UNINITIALIZED = 0;
net.READY_STATE_LOADING = 1;
net.READY_STATE_LOADED = 2;
net.READY_STATE_INTERACTIVE = 3;
net.READY_STATE_COMPLETE = 4;


/*--- content loader object for cross-browser requests ---*/
net.ContentLoader = function(contentType, headers, secure, paramExt){
    this.paramExt = paramExt;
    this.req = null;
    this.onerror = this.defaultError;
    this.secure = secure;
	this.onWork = 0;
	this.timeRelance;
	this.objParam;
	this.params;
	this.method = 'POST';
	this.tCache = new Array();
	
	this.contentType = contentType;
	this.headers = headers;
	this.secure = secure;
	this.paramExt = paramExt;
	
}

net.ContentLoader.prototype = {
	sendAjax : function(){
		//$('hautDCont').innerHTML = $('hautDCont').innerHTML +' - c:' +  tCacheAj.length + " w:" + this.onWork + " -- ";
		if(this.tCache.length > 0 & this.onWork != 1) {
			this.onWork = 1;
			this.objParam = this.tCache.shift();
			if(this.tCache.length == 0) {
				clearTimeout(this.timeRelance);
			}
			this.onload = this.objParam.callFunc;
		    this.url = this.objParam.url;
			this.params = this.objParam.param;
			//debug
			//$('fsaRef1').innerHTML = this.url + '&' + this.params;
			this.loadXMLDoc(this.url, this.method, this.params)
		}
		else {
			this.timeRelance = setTimeout("ajax.sendAjax()", 0);
		}
	},
		
    loadXMLDoc: function(url, method, params){
        if (!method) {
            method = "GET";
        }
        if (!this.contentType && method == "POST") {
            this.contentType = 'application/x-www-form-urlencoded;charset=utf-8';
        }
        if (window.XMLHttpRequest) {
            this.req = new XMLHttpRequest();
        }
        else 
            if (window.ActiveXObject) {
                this.req = new ActiveXObject("Microsoft.XMLHTTP");
            }
        //this.debug("got request object");
        if (this.req) {
            try {
                try {
                    if (this.secure) {
                        netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRead');
                    }
                } 
                catch (err) {
                }
                this.req.open(method, url, true);
                //this.debug("opened");
                if (this.contentType) {
                    this.req.setRequestHeader('Content-Type', this.contentType);
                }
                if (this.headers) {
                    for (var h in this.headers) {
                        this.req.setRequestHeader(h, this.headers[h]);
                    }
                }
                var loader = this;
                this.req.onreadystatechange = function(){
                    loader.onReadyState.call(loader);
                }
		        affWait();
		        
                this.req.send(params);
                //this.debug("sent");
            } 
            catch (err) {
		        hideWait();
                this.onerror.call(this);
            }
        }
    },
    
    onReadyState: function(){
        var req = this.req;
        var ready = req.readyState;
        if (ready == net.READY_STATE_COMPLETE) {
			this.onWork = 0;
	        hideWait();
            var httpStatus = req.status;
            if (httpStatus == 200 || httpStatus == 0) {
                try {
                    if (this.secure) {
                        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect UniversalBrowserAccess');
                    }
                } 
                catch (err) {
                }
                this.onload.call(this);
            }
            else {
                this.onerror.call(this);
            }
        }
    },
    
    defaultError: function(){
    	hideWait();
        alert("error fetching data!" +
        "\n\nreadyState:" +
        this.req.readyState +
        "\nstatus: " +
        this.req.status +
        "\nheaders: " +
        this.req.getAllResponseHeaders());
    }
    
    /*,debug:function(str){
     logger.append("["+this.url+"] "+str);
     }*/
}

var ajax = new net.ContentLoader();
ajax.tMemCache = new Array;


