/**
 *  Inspired by Sean Kane (http://celtickane.com/programming/code/ajax.php)
 *  Feather Ajax v1.0.0
 *  customised by La Mire (www.lammire.com)
 *
 *
 * usage : 
 * 
 * 
 * <script type="text/javascript" >
 * function doit(str){
 *   alert (str);
 * }
 * 
 * // ajax call helper
 * function ajaxUpdate (){
 *  var ao = new AjaxObject();
 *   ao.setCallback (doit, 'text');
 *   ao.sndReq('POST','ajax_func.php', {action:'gettext',b1:'testing'});
 * }
 * </script>
 * <input type="button" value="Click Me" onClick="ajaxUpdate();" />   
 */ 

// Ajax Object definition
function AjaxObject() {
	this.callback = null; // callback function
	this.sendXML = false; // text or xml, default to text
	
	/** public : setCallback()
	 *  fixe la fonction callback et le mode de retour des données
	 *
	 */   	
	this.setCallback = function (fn, mode){
		this.callback = fn;
		this.sendXML=  (mode=='xml') ? true : false;
	}

	/** initialise un object XMLHttp
	 *  private function - appellé à l'instanciation
	 */   	
	this.createRequestObject = function() {	
	// This is called at the very bottom -- 
  // it sets this.http to the Ajax request object (ro)
		var ro;	
		
	 try {//IE ?
			ro = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try { ro = new ActiveXObject("Microsoft.XMLHTTP");}
      catch (e2) { ro = null;	}
		}
    // standard
		if (!ro && typeof XMLHttpRequest!='undefined') {
				ro = new XMLHttpRequest();
			}

		return ro; //instance of AjaxObject
	}
	
	/**
	 *	This function will start the Ajax process, and is called manually by the user
	 *	action is either 'get' or 'post'	
	 *	url can contain GET variables -- like myajax.php?action=test
	 *	method : GET or POST	 
	 */	 	  
	this.sndReq = function(action, url, vars) { 
		// encode datas (parameters)
		tmp = new Array();
    for (var i in vars) {
    tmp.push (encodeURIComponent(i)+'='+encodeURIComponent(vars[i])); 
   }
   // ajoute un paramètre aléatoire pour palier les pb de cache
   tmp.push ('rand'+'='+new Date().getTime());
   datas = tmp.join('&');
    //alert (url + datas);
   /*this.http.abort();*/
   
    switch (action.toUpperCase()){
    case 'GET':
      this.http.onreadystatechange = this.handleResponse; 
      this.http.open('GET',url+'?'+datas,true);
		  this.http.send(null);	
      break;
      
    case 'POST' : // default to POST
      this.http.onreadystatechange = this.handleResponse; 
      this.http.open('POST',url,true);
      this.http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      this.http.send(datas);	
    }
	}
	/**
	 *	This function is called when this.http's state changes
	 *	 0=uninitialized,1=loading,2=loaded,3=interactive,4=complete	 
	 */	 	
	this.handleResponse = function() { 
      if(me.http.readyState != 4 ) return;
      if(me.http.status != 200) alert ('Erreur serveur : '+ me.http.status);
     // alert(me.http.getAllResponseHeaders())
      var data = (me.sendXML) ? me.http.responseXML : me.http.responseText;
      data = eval( '('+data+')');
      if (me.callback!=null ) me.callback (data);
      else alert ('Callback  function no set');
	}
	
	// constructor
	var me = this;	
  // necessary because this.http won't work in the callback
  // function 'handleResponse' (we have to use me.http instead)
	this.http = this.createRequestObject(); 

}

/**
 serialize un objet Javascript en chaine de 
 type php serialized object
boolean (variable OUI/NON),
string (variable de chaîne de caractères),
number (variable numérique),
function (fonction),
object (objet),
undefined (type indéterminé).

*/
function php_serialize(obj) {
  var tok, tmp, count;
  var typo = typeof(obj);

	switch (typo){
		case 'string':
		// check utf-8 ?
      tok = 's:'+obj.length+':"'+obj+'";';
      break;
		
		case 'boolean':
			tok = (obj) ? 'b:1;': 'b:0;';
			break;
			
		case 'number':
			tok =  (obj - Math.floor(obj) != 0) ? 'd:'+obj+';' : 'i:'+obj+';';
			break;
			
		case 'function':
			tok = obj;
			break;
			
		case 'object':
		  if (obj instanceof Array) { // tableau avec index numériques
            tmp = '';
            count = 0;
            for (var key in obj) {
                tmp += 'i:'+key+';'+php_serialize(obj[key]);
                count++;
            }
            tok = 'a:'+count+':{'+tmp+'}';

        } else { // tableau associatif
        	
            tmp = '';
            count = 0;
            for (var key in obj) {
                tmp += php_serialize(key);
                tmp += (obj[key]) ? php_serialize(obj[key]) :php_serialize('');
                count++;
            }
            tok = 'a:'+count+':{'+tmp+'}';
        }
		break;
	
		default : 
			string = 's:0:"";'; // empty string
			break;

	}

    return tok;
}
