// holds an instance of XMLHttpRequest
var xmlHttpCommentaires = createXmlHttpRequestObject();
var xmlHttpEnvoiCommentaires = 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);
  }
}


// the function handles the validation for any form field
function validateEnvoiCommentaire(emailDestinataire, auteur, email, commentaire)
{
  // only continue if xmlHttp isn't void
  if (xmlHttpEnvoiCommentaires)
  {
    // 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
      emailDestinataire = encodeURIComponent(emailDestinataire);	  
      auteur = encodeURIComponent(auteur);
      email = encodeURIComponent(email);
      commentaire = encodeURIComponent(commentaire);
      // add the values to the queue
	  
      cache.push("envoiCommentaire=1&emailDestinataire=" + emailDestinataire + "&auteur=" + auteur + "&email=" + email + "&commentaire=" + commentaire);

    // try to connect to the server
    try
    {
      // continue only if the XMLHttpRequest object isn't busy
      // and the cache is not empty
      if ((xmlHttpEnvoiCommentaires.readyState == 4 || xmlHttpEnvoiCommentaires.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
        xmlHttpEnvoiCommentaires.open("POST", serverAddressCommentaires, true);
        xmlHttpEnvoiCommentaires.setRequestHeader("Content-Type",
                                 "application/x-www-form-urlencoded");
        xmlHttpEnvoiCommentaires.onreadystatechange = handleRequestStateEnvoiCommentaires;
        xmlHttpEnvoiCommentaires.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 (xmlHttpEnvoiCommentaires.readyState == 4)
  {
    // continue only if HTTP status is "OK"
    if (xmlHttpEnvoiCommentaires.status == 200)
    {
      try
      {
        // read the response from the server
        readResponseEnvoiCommentaires();
      }
      catch(e)

      {
        // display error message
        displayError(e.toString());
      }
    }
    else
    {
      // display error message
      displayError(xmlHttpEnvoiCommentaires.statusText);
    }
  }
}


// read server's response
function readResponseEnvoiCommentaires()
{
  // retrieve the server's response
  var response = xmlHttpEnvoiCommentaires.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 = xmlHttpEnvoiCommentaires.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.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.auteurCommentairePourCreateurBlog.value = "";
	document.form.emailAuteurCommentairePourCreateurBlog.value = "";
	document.form.commentaireAuteurPourCreateurBlog.value = "";
	
	document.getElementById('light').style.borderColor = "#33CC00";
  }  
}


// the function handles the validation for any form field
function validateEnvoiCommentaireAuteur(emailDestinataire, auteur, email, commentaire)
{
  // only continue if xmlHttp isn't void
  if (xmlHttpEnvoiCommentaires)
  {
	  	
    // 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
      emailDestinataire = encodeURIComponent(emailDestinataire);	  
      auteur = encodeURIComponent(auteur);
      email = encodeURIComponent(email);
      commentaire = encodeURIComponent(commentaire);
      // add the values to the queue
      cache.push("envoiCommentaire=1&emailDestinataire=" + emailDestinataire + "&auteur=" + auteur + "&email=" + email + "&commentaire=" + commentaire);
	 
    // try to connect to the server
    try
    {
      // continue only if the XMLHttpRequest object isn't busy
      // and the cache is not empty
      if ((xmlHttpEnvoiCommentaires.readyState == 4 || xmlHttpEnvoiCommentaires.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
        xmlHttpEnvoiCommentaires.open("POST", serverAddressCommentaires, true);
        xmlHttpEnvoiCommentaires.setRequestHeader("Content-Type",
                                 "application/x-www-form-urlencoded");
        xmlHttpEnvoiCommentaires.onreadystatechange = handleRequestStateEnvoiCommentairesAuteur;
        xmlHttpEnvoiCommentaires.send(cacheEntry);
      }
    }
    catch (e)
    {
      // display an error when failing to connect to the server
      displayError(e.toString());
    }
  }
}


// function that handles the HTTP response
function handleRequestStateEnvoiCommentairesAuteur()
{
  // when readyState is 4, we read the server response
  if (xmlHttpEnvoiCommentaires.readyState == 4)
  {
    // continue only if HTTP status is "OK"
    if (xmlHttpEnvoiCommentaires.status == 200)
    {
      try
      {
        // read the response from the server
        readResponseEnvoiCommentairesAuteur();
      }
      catch(e)

      {
        // display error message
        displayError(e.toString());
      }
    }
    else
    {
      // display error message
      displayError(xmlHttpEnvoiCommentaires.statusText);
    }
  }
}


// read server's response
function readResponseEnvoiCommentairesAuteur()
{
  // retrieve the server's response
  var response = xmlHttpEnvoiCommentaires.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 = xmlHttpEnvoiCommentaires.responseXML;
  // get the document element
  xmlDoc = responseXml.documentElement;
  result = xmlDoc.getElementsByTagName("result")[0].firstChild.data;

  if(result==0)
  {
	document.getElementById("etatEnvoiCommentaireAuteurEpisodeOk").className = "hidden";	
	document.getElementById("etatEnvoiCommentaireAuteurEpisodeKo").className = "error";	
	document.getElementById('lightAuteurEpisode').style.borderColor = "red";
  }
  else
  {
	document.getElementById("etatEnvoiCommentaireAuteurEpisodeOk").className = "valid";	
	document.getElementById("etatEnvoiCommentaireAuteurEpisodeKo").className = "hidden";	
	
	document.getElementById("erreurAuteurEpisode").className = "hidden";	
	document.getElementById("erreurEmailAuteurEpisode").className = "hidden";	
	document.getElementById("erreurCommentaireAuteurEpisode").className = "hidden";	
	
	document.formAuteur.auteurEpisode.value = "";
	document.formAuteur.emailAuteurEpisode.value = "";
	document.formAuteur.commentaireAuteurEpisode.value = "";
	
	document.getElementById('lightAuteurEpisode').style.borderColor = "#33CC00";
  }  
}


// ****************************************************************************************************
// CONTROLE DES CHAMPS LORSQU'UNE PERSONNE VEUT AJOUTER UN COMMENTAIRE A UN EPISODE
// ****************************************************************************************************

// the function handles the validation for any form field
function validateChampsCommentairePourEpisode(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);
      // 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 = handleRequestStateChangeCommentairePourEpisode;
        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 handleRequestStateChangeCommentairePourEpisode()
{
  // 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
        readResponseCommentairePourEpisode();
      }
      catch(e)

      {
        // display error message
        displayError(e.toString());
      }
    }
    else
    {
      // display error message
      displayError(xmlHttpCommentaires.statusText);
    }
  }
}


// read server's response
function readResponseCommentairePourEpisode()
{
	
  // 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;
  nomChamp = xmlDoc.getElementsByTagName("fieldID")[0].firstChild.data;
  
  if(result==0)
  {
	document.getElementById(nomChamp).style.borderColor = "red";	
  }
  else
  {
	document.getElementById(nomChamp).style.borderColor = "";
  }  
}


// ****************************************************************************************************
// CONTROLE DES CHAMPS LORSQU'UNE PERSONNE VEUT ENVOYER UN COMMENTAIRE AU CREATEUR DU BLOG
// ****************************************************************************************************

// the function handles the validation for any form field
function validateChampsPourCreateurBlog(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);
      // 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 = handleRequestStateChangePourCreateurBlog;
        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 handleRequestStateChangePourCreateurBlog()
{
  // 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
        readResponsePourCreateurBlog();
      }
      catch(e)

      {
        // display error message
        displayError(e.toString());
      }
    }
    else
    {
      // display error message
      displayError(xmlHttpCommentaires.statusText);
    }
  }
}


// read server's response
function readResponsePourCreateurBlog()
{
	
  // 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;
  nomChamp = xmlDoc.getElementsByTagName("fieldID")[0].firstChild.data;
    
  if(result==0)
  {
	document.getElementById(nomChamp).style.borderColor = "red";	
  }
  else
  {
	document.getElementById(nomChamp).style.borderColor = "";
  }  

}


// 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);
      // 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 = handleRequestStateChangeCommentaires;
        xmlHttpCommentaires.send(cacheEntry);
      }
    }
    catch (e)
    {
      // display an error when failing to connect to the server
      displayError(e.toString());
    }
  }
}


// the function handles the validation for any form field
function validateChampsAuteur(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);
      // 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 = handleRequestStateChangeCommentairesAuteur;
        xmlHttpCommentaires.send(cacheEntry);
      }
    }
    catch (e)
    {
      // display an error when failing to connect to the server
      displayError(e.toString());
    }
  }
}


// the function handles the validation for any form field
function ajouterCommentaire(auteur, email, commentaire, episodeID)
{
  // 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 (auteur && email && commentaire)
    {
      // encode values for safely adding them to an HTTP request query string
      auteur = encodeURIComponent(auteur);
	  email = encodeURIComponent(email);
	  commentaire = encodeURIComponent(commentaire);
	  episodeID = encodeURIComponent(episodeID);

      // add the values to the queue
      cache.push("auteur=" + auteur + "&email=" + email + "&commentaire=" + commentaire + "&episodeID=" + episodeID);
    }
    // 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 = handleRequestStateChangeCommentaires;
        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 handleRequestStateChangeCommentaires()
{
  // 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
        readResponseCommentaires();
      }
      catch(e)
      {
        // display error message
        displayError(e.toString());
      }
    }
    else
    {
      // display error message
      displayError(xmlHttpCommentaires.statusText);
    }
  }
}


// function that handles the HTTP response
function handleRequestStateChangeCommentairesAuteur()
{
  // 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
        readResponseCommentairesAuteur();
      }
      catch(e)
      {
        // display error message
        displayError(e.toString());
      }
    }
    else
    {
      // display error message
      displayError(xmlHttpCommentaires.statusText);
    }
  }
}


// read server's response
function readResponseCommentaires()
{
  // 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;
  nomChamp = xmlDoc.getElementsByTagName("fieldID")[0].firstChild.data;
    
  if(result==0)
  {
	if(nomChamp.match("auteur"))
	{
		document.getElementById("auteur").style.borderColor = "red";
	}
	else if(nomChamp.match("email"))
	{
		document.getElementById("email").style.borderColor = "red";
	}
	else if(nomChamp.match("commentaire"))
	{
		document.getElementById("commentaire").style.borderColor = "red";
	}
  }
  else
  {
	if(nomChamp.match("auteur"))
	{
		document.getElementById("erreurauteur").className = "hidden";		
		document.getElementById("auteur").style.borderColor = "";
	}
	else if(nomChamp.match("email"))
	{
		document.getElementById("erreuremail").className = "hidden";	
		document.getElementById("email").style.borderColor = "";
	}
	else if(nomChamp.match("commentaire"))
	{
		document.getElementById("erreurcommentaire").className = "hidden";	
		document.getElementById("commentaire").style.borderColor = "";
	}
  }  
}


// read server's response
function readResponseCommentairesAuteur()
{
  // 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;
  nomChamp = xmlDoc.getElementsByTagName("fieldID")[0].firstChild.data;
    
  if(result==0)
  {
	if(nomChamp.match("auteur"))
	{
		alert('erreur nom pour auteur');
		
		document.getElementById("auteurEpisode").style.borderColor = "red";
	}
	else if(nomChamp.match("email"))
	{
		alert('erreur email pour auteur');
		
		document.getElementById("emailAuteurEpisode").style.borderColor = "red";
	}
	else if(nomChamp.match("commentaire"))
	{
		alert('erreur commentaire pour auteur');
		
		document.getElementById("commentaireAuteurEpisode").style.borderColor = "red";
	}
  }
  else
  {
	if(nomChamp.match("auteur"))
	{
		alert('nom pour auteur ok');
		
		document.getElementById("auteurEpisode").style.borderColor = "";
	}
	else if(nomChamp.match("email"))
	{
		alert('email pour auteur ok');		
		
		document.getElementById("emailAuteurEpisode").style.borderColor = "";
	}
	else if(nomChamp.match("commentaire"))
	{
		alert('commentaire pour auteur ok');		
		
		document.getElementById("commentaireAuteurEpisode").style.borderColor = "";
	}
  }  
}



