// holds an instance of XMLHttpRequest
var xmlHttpCommentaires = createXmlHttpRequestObject();

// holds the remote server address
var serverAddressCommentaires = "validate_commentaire.php";
// when set to true, display detailed error messages
var showErrors = true;
// initialize the validation requests cache
var cache = new Array();


// creates an XMLHttpRequest instance
function createXmlHttpRequestObject()
{
  // will store the reference to the XMLHttpRequest object
  var xmlHttpCommentaires;
  // this should work for all browsers except IE6 and older
  try
  {
    // try to create XMLHttpRequest object
    xmlHttpCommentaires = new XMLHttpRequest();
  }
  catch(e)
  {
    // assume IE6 or older
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
    // try every id until one works
    for (var i=0; i<XmlHttpVersions.length && !xmlHttpCommentaires; i++)
    {
      try
      {
        // try to create XMLHttpRequest object
        xmlHttpCommentaires = new ActiveXObject(XmlHttpVersions[i]);
      }
      catch (e) {} // ignore potential error
    }
  }
  // return the created object or display an error message
  if (!xmlHttpCommentaires)
    displayError("Error creating the XMLHttpRequest object.");
  else
    return xmlHttpCommentaires;
}


// function that displays an error message
function displayError($message)
{
  // ignore errors if showErrors is false
  if (showErrors)
  {
    // turn error displaying Off
    showErrors = false;
    // display error message

    alert("Error encountered: \n" + $message);
    // retry validation after 10 seconds
    setTimeout("ajouterCommentaire();", 10000);
  }
}




//*******************************************************************
//		test des différents champs
//*******************************************************************
var nomChamp = null;
// the function handles the validation for any form field
function validateChamps(inputValue, fieldID)
{
  // only continue if xmlHttp isn't void
  if (xmlHttpCommentaires)
  {
    // if we received non-null parameters, we add them to cache in the
    // form of the query string to be sent to the server for validation
    if (fieldID)
    {
	  
      // encode values for safely adding them to an HTTP request query string
      inputValue = encodeURIComponent(inputValue);
      fieldID = encodeURIComponent(fieldID);
      
	  nomChamp = fieldID;
	  // add the values to the queue
      cache.push("inputValue=" + inputValue + "&fieldID=" + fieldID);


    }
    // try to connect to the server
    try
    {
      // continue only if the XMLHttpRequest object isn't busy
      // and the cache is not empty
      if ((xmlHttpCommentaires.readyState == 4 || xmlHttpCommentaires.readyState == 0)
         && cache.length > 0)
      {
        // get a new set of parameters from the cache
        var cacheEntry = cache.shift();
        // make a server request to validate the extracted data
        xmlHttpCommentaires.open("POST", serverAddressCommentaires, true);
        xmlHttpCommentaires.setRequestHeader("Content-Type",
                                 "application/x-www-form-urlencoded");
        xmlHttpCommentaires.onreadystatechange = handleRequestStateValidateChamps;
        xmlHttpCommentaires.send(cacheEntry);
      }
    }
    catch (e)
    {
      // display an error when failing to connect to the server
      displayError(e.toString());
    }
  }
}




// function that handles the HTTP response
function handleRequestStateValidateChamps()
{
  // when readyState is 4, we read the server response
  if (xmlHttpCommentaires.readyState == 4)
  {
    // continue only if HTTP status is "OK"
    if (xmlHttpCommentaires.status == 200)
    {
      try
      {
        // read the response from the server
        readResponseValidateChamps();
      }
      catch(e)

      {
        // display error message
        displayError(e.toString());
      }
    }
    else
    {
      // display error message
      displayError(xmlHttpCommentaires.statusText);
    }
  }
}


// read server's response
function readResponseValidateChamps()
{
  // retrieve the server's response
  var response = xmlHttpCommentaires.responseText;
  // server error?
  if (response.indexOf("ERRNO") >= 0
      || response.indexOf("error:") >= 0
      || response.length == 0)
    throw(response.length == 0 ? "Server error." : response);
  // get response in XML format (assume the response is valid XML)
  responseXml = xmlHttpCommentaires.responseXML;
  // get the document element
  xmlDoc = responseXml.documentElement;
  result = xmlDoc.getElementsByTagName("result")[0].firstChild.data;
  if(result==1)
  {
	//document.getElementById(nomChamp).className = "valid";	
	
	document.getElementById(nomChamp).style.borderColor = "";
	
	//document.getElementById('light').style.borderColor = "red";
  }
  else
  {
	document.getElementById(nomChamp).style.borderColor = "red";
	/*document.getElementById("etatEnvoiCommentaireOk").className = "valid";	
	document.getElementById("etatEnvoiCommentaireKo").className = "hidden";	
	
	document.getElementById("erreurauteur").className = "hidden";	
	document.getElementById("erreuremail").className = "hidden";	
	document.getElementById("erreurcommentaire").className = "hidden";	
	
	document.form.auteur.value = "";
	document.form.email.value = "";
	document.form.commentaire.value = "";*/
	
	//document.getElementById('light').style.borderColor = "#33CC00";
  }  
}










//*******************************************************************
//		envoi de l'email
//*******************************************************************

// the function handles the validation for any form field
function validateEnvoiCommentaire(auteur, email, nomDestinataire, emailDestinataire, commentaire, lien)
{
  // only continue if xmlHttp isn't void
  if (xmlHttpCommentaires)
  {
    // if we received non-null parameters, we add them to cache in the
    // form of the query string to be sent to the server for validation
 
      // encode values for safely adding them to an HTTP request query string
      auteur = encodeURIComponent(auteur);
      email = encodeURIComponent(email);
      nomDestinataire = encodeURIComponent(nomDestinataire);	  
      emailDestinataire = encodeURIComponent(emailDestinataire);
      commentaire = encodeURIComponent(commentaire);
	  lien = encodeURIComponent(lien);
      // add the values to the queue
	  
      cache.push("envoiCommentaire=1&auteur=" + auteur + "&email=" + email + "&nomDestinataire=" + nomDestinataire +"&emailDestinataire="+ emailDestinataire +"&commentaire=" + commentaire + "&lien=" + lien);
    // try to connect to the server
    try
    {
      // continue only if the XMLHttpRequest object isn't busy
      // and the cache is not empty
      if ((xmlHttpCommentaires.readyState == 4 || xmlHttpCommentaires.readyState == 0)
         && cache.length > 0)
      {
        // get a new set of parameters from the cache
        var cacheEntry = cache.shift();
        // make a server request to validate the extracted data
        xmlHttpCommentaires.open("POST", serverAddressCommentaires, true);
        xmlHttpCommentaires.setRequestHeader("Content-Type",
                                 "application/x-www-form-urlencoded");
        xmlHttpCommentaires.onreadystatechange = handleRequestStateEnvoiCommentaires;
        xmlHttpCommentaires.send(cacheEntry);
      }
    }
    catch (e)
    {
      // display an error when failing to connect to the server
      displayError(e.toString());
    }
  }
}


// function that handles the HTTP response
function handleRequestStateEnvoiCommentaires()
{
  // when readyState is 4, we read the server response
  if (xmlHttpCommentaires.readyState == 4)
  {
    // continue only if HTTP status is "OK"
    if (xmlHttpCommentaires.status == 200)
    {
      try
      {
        // read the response from the server
        readResponseEnvoiCommentaires();
      }
      catch(e)

      {
        // display error message
        displayError(e.toString());
      }
    }
    else
    {
      // display error message
      displayError(xmlHttpCommentaires.statusText);
    }
  }
}


// read server's response
function readResponseEnvoiCommentaires()
{
	

  // retrieve the server's response
  var response = xmlHttpCommentaires.responseText;
  // server error?
  if (response.indexOf("ERRNO") >= 0
      || response.indexOf("error:") >= 0
      || response.length == 0)
    throw(response.length == 0 ? "Server error." : response);
  // get response in XML format (assume the response is valid XML)
  responseXml = xmlHttpCommentaires.responseXML;
  // get the document element
  xmlDoc = responseXml.documentElement;
  result = xmlDoc.getElementsByTagName("result")[0].firstChild.data;
  
  if(result==0)
  {
	document.getElementById("etatEnvoiCommentaireOk").className = "hidden";	
	document.getElementById("etatEnvoiCommentaireKo").className = "error";	
	//document.getElementById('light').style.borderColor = "red";
  }
  else
  {
	document.form.auteur.value = "";
	document.form.email.value = "";
	document.form.nomDestinataire.value = "";
	document.form.emailDestinataire.value = "";	
	document.form.commentaire.value = "";


	document.getElementById("etatEnvoiCommentaireKo").className = "hidden";	
	document.getElementById("etatEnvoiCommentaireOk").className = "valid";	

	//document.getElementById('light').style.borderColor = "#33CC00";
  }  
}



