//based on prototype's ajax class
//to be used with prototype.lite, moofx.mad4milk.net.

ajax = Class.create();
ajax.prototype = {
	initialize: function(url, options){
		this.transport = this.getTransport();
		this.postBody = options.postBody || '';
		this.method = options.method || 'post';
		this.onComplete = options.onComplete || null;
		this.update = $(options.update) || null;
		//JML
		this.loading = $(options.loading) || $("mooAjaxLoading") || null; 
		if(this.loading==null) this.initLoading;
		//JML (Mode asynchrone par défaut)
		this.async = true;
		if(options.async == 'false') this.async = false;
		
    this.request(url);
    
    //JML si pas mode asynchrone retourne le résultat directement
    this.responseText = "";
    if(!this.async) {
    	this.responseText = this.transport.responseText;
    }
	},

	request: function(url){
		this.transport.open(this.method, url, this.async);
		this.transport.onreadystatechange = this.onStateChange.bind(this);
        
        this.transport.setRequestHeader('Charset', 'UTF-8');
		if (this.method == 'post') {
			this.transport.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			if (this.transport.overrideMimeType) this.transport.setRequestHeader('Connection', 'close');
		}
		this.transport.send(this.postBody);
	},

	onStateChange: function(){
	  if (this.transport.readyState == 1) {
      if(this.loading!=null) this.loading.style.display='block';  
    }
    if (this.transport.readyState == 4) {
      if(this.loading!=null) this.loading.style.display='none';
    }
		if (this.transport.readyState == 4 && this.transport.status == 200) {
			if (this.onComplete) 
				setTimeout(function(){this.onComplete(this.transport);}.bind(this), 10);
			if (this.update)
				setTimeout(function(){this.update.innerHTML = this.transport.responseText;}.bind(this), 10);
			this.transport.onreadystatechange = function(){};
		}
	},

	getTransport: function() {
		if (window.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP');
		else if (window.XMLHttpRequest) return new XMLHttpRequest();
		else return false;
	},
	
	//Ajout du div pour le chargement
	//il faut le positionner en CSS plus gif animé en background
	initLoading: function() {
    var div = document.createElement('div');
    div.id = "mooAjaxLoading";
    document.body.appendChild(div);
    this.loading = div;
  }
};


