/*****************************************************
	Function trim() requise pour certain pb
*****************************************************/

String.prototype.trim = function()
{
	return this.replace(/(^[\s\r\n]*)|([\s\n\r]*$)/g, "");
}

/*****************************************************
	Objet HTTPCLIENT
*****************************************************/

function HTTPClient() {};

/*****************************************************
	On ajoute toutes les methodes et les propriétés
*****************************************************/
HTTPClient.prototype.url = null

 // Instance of XMLHttpRequest
HTTPClient.prototype.xmlhttp = null

HTTPClient.prototype.requete_en_cours = false

// The user defined handler - see MyHandler below
HTTPClient.prototype.userhandler = null

HTTPClient.prototype.init = function(url) 
{
  this.url = url;
  
  var xmlhttp = false; 
	
	try 
	{
      // Mozilla / Safari
      xmlhttp = new XMLHttpRequest();
  } 
  catch (e) 
  {
  	// IE
  	var MSXML_XMLHTTP_PROGIDS = new Array(
  	    'MSXML2.XMLHTTP.4.0',
  	    'MSXML2.XMLHTTP.3.0',
  	    'MSXML2.XMLHTTP',
  	    'Microsoft.XMLHTTP'
  	);
  	var success = false;
  	for (var i=0;i < MSXML_XMLHTTP_PROGIDS.length && !success; i++) 
  	{
  		try 
  		{
  		  xmlhttp = new ActiveXObject(MSXML_XMLHTTP_PROGIDS[i]);
  		  success = true;
  		} 
  		catch (e) 
  		{
  		}
  	}
  }
	
	this.xmlhttp = xmlhttp
	
	if(!this.xmlhttp)
	{
		alert('Votre browser internet (' +  navigator.appName + navigator.appVersion + ') ne supporte pas ce script!')
	}
}

HTTPClient.prototype.changeState = function(client) 
{
  switch (client.xmlhttp.readyState) 
  {
    // Requete non commencée
    case 1:
      try 
      {
      	client.userhandler.onInit();
      } 
      catch (e) 
      { 
      	/* Handler method not defined */ 
      }
    	break;

    // Contact etabli avec le serveur mais téléchargement non commencé
    case 2:
      try 
      {
        // Check for HTTP status 200: OK ?
        if ( client.xmlhttp.status != 200 ) 
        {
            client.userhandler.onError(
                client.xmlhttp.status,
                client.xmlhttp.statusText
                );

            // Abort the request
            client.xmlhttp.abort();

            // Call no longer in progress
            client.requete_en_cours = false;
        }
        else 
        {
        	client.userhandler.onWaiting();
        }                  	
      } 
      catch (e) 
      {
          /* Handler method not defined */
      }
    	break;

    // Appelé plusieurs fois au cours du téléchargement
    case 3:
      // Notify user handler of download progress
      try 
      {
      	// Get the total content length
      	// -useful to work out how much has been downloaded
      	try 
      	{
      	  var contentLength = client.xmlhttp.getResponseHeader("Content-Length");
      	} 
      	catch (e) 
      	{
      	  var contentLength = NaN;
      	} 
      	
      	// Call the progress handler with what we've got
      	client.userhandler.onProgress(client.xmlhttp.responseText,contentLength)

      } 
      catch (e) 
      { 
      	/* Handler method not defined */ 
      }
    	break;

    // Download completé
    case 4:
      try 
      {
        client.userhandler.onLoaded(client.xmlhttp.responseText.trim());
      } 
      catch (e) 
      {
        /* Handler method not defined */
      } 
      finally 
      {
        // Call no longer in progress
        client.requete_en_cours = false;
      }
    	break;
  }
}

// Le 'handler' est une methode du client pour gerer la reponse asynchronisée avec le deroulement du script. cf fin de page
HTTPClient.prototype.asyncGET = function (handler) 
{
  // Empeche l'execution de deux requetes a la fois
  if (this.requete_en_cours) 
  {
    throw "Requette HTTP en cours! Veuillez attendre.";
  }
	
	this.requete_en_cours = true;
	
  this.userhandler = handler;

  // Open an async request - third argument makes it async
  this.xmlhttp.open('GET',this.url,true);

	var self = this;
	
  // Assign a closure to the onreadystatechange callback
  this.xmlhttp.onreadystatechange = function() 
  {
  	self.changeState(self)
  }

  // Send the request
  this.xmlhttp.send(null);
}
  
HTTPClient.prototype.syncGET = function (handler) 
{
	// Empeche l'execution de deux requetes a la fois
	if (this.requete_en_cours) 
	{
	    throw "Requette HTTP en cours! Veuillez attendre.";
	}
	
	//alert('deb GET')
	
	this.requete_en_cours = true;
	
	this.userhandler = handler;
	
	this.userhandler.onInit();
	// Open a sync request - third argument makes it sync
	this.xmlhttp.open('GET',this.url,false);    	
	this.userhandler.onWaiting();    	
	
	//alert('sending')
	
	// Send the request
	this.xmlhttp.send(null);
	
	//alert('sent')
	
	if(this.xmlhttp.status != 200)
	{
		this.userhandler.onError();
	}
	else
	{
		this.userhandler.onLoaded(this.xmlhttp.responseText.trim());
	}
	//alert('reponse:\n'+this.xmlhttp.responseText)    	
}



/*******************************************************
	Classe Handler 
	
		-méthodes à redéfinir au cas par cas
*******************************************************/

function Handler() {}
Handler.prototype.onInit = function() {}
Handler.prototype.onWaiting = function() {}
Handler.prototype.onError = function(status,statusText) {}
Handler.prototype.onProgress = function(responseText,length) {}
Handler.prototype.onLoaded = function(result) {}


//var Handler = {
//    onInit: function() {},
//    onWaiting: function() {},
//    onError: function(status,statusText) {},
//    onProgress: function(responseText,length) {},
//    onLoaded: function(result) {}
//}