var xmlHttp = createXmlHttpRequestObject();// holds an instance of XMLHttpRequest
var serverAddress = "validate.php?appname=" + appname;// holds the remote server address
var showErrors = true;// when set to true, display detailed error messages
var cache = new Array();// initialize the validation requests cache
function createXmlHttpRequestObject()// creates an XMLHttpRequest instance
{
  var xmlHttp;// will store the reference to the XMLHttpRequest object
  try// this should work for all browsers except IE6 and older
  {
    xmlHttp = new XMLHttpRequest(); // try to create XMLHttpRequest object
  }
  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");
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)// try every id until one works
    {
      try
      {
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);// try to create XMLHttpRequest object
      }
      catch (e) {} // ignore potential error
    }
  }
  if (!xmlHttp)// return the created object or display an error message
    displayError("Error creating the XMLHttpRequest object.");
  else
    return xmlHttp;
}

function displayError($message)// function that displays an error message
{
  if (showErrors)// ignore errors if showErrors is false
  {
    showErrors = false;// turn error displaying Off
    alert("Error encountered: \n" + $message);// display error message
    setTimeout("validate();", 10000);// retry validation after 10 seconds
  }
}

function validate(inputValue, fieldID, inputValue2)// the function handles the validation for any form field
{
  if (xmlHttp)// only continue if xmlHttp isn't void
  {
    // 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)
    {
      inputValue = encodeURIComponent(inputValue);// encode values for safely adding them to an HTTP request query string
      fieldID = encodeURIComponent(fieldID);
      cache.push("inputValue=" + inputValue + "&fieldID=" + fieldID + "&inputValue2=" + inputValue2);// add the values to the queue
    }
    try// try to connect to the server
    {
      if ((xmlHttp.readyState == 4 || xmlHttp.readyState == 0) && cache.length > 0)// continue only if the XMLHttpRequest object isn't busy and the cache is not empty
      {
        var cacheEntry = cache.shift();// get a new set of parameters from the cache
        xmlHttp.open("POST", serverAddress, true);// make a server request to validate the extracted data
        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlHttp.onreadystatechange = handleRequestStateChange;
        xmlHttp.send(cacheEntry);
      }
    }
    catch (e)
    {
      displayError(e.toString());// display an error when failing to connect to the server
    }
  }
}

function handleRequestStateChange()// function that handles the HTTP response
{
  if (xmlHttp.readyState == 4)// when readyState is 4, we read the server response
  {
    if (xmlHttp.status == 200)// continue only if HTTP status is "OK"
    {
      try
      {
        readResponse();// read the response from the server
      }
      catch(e)
      {
        displayError(e.toString());// display error message
      }
    }
    else
    {
      displayError(xmlHttp.statusText);// display error message
    }
  }
}

function readResponse()// read server's response
{
  var response = xmlHttp.responseText;// retrieve the server's response
  if (response.indexOf("ERRNO") >= 0 || response.indexOf("error:") >= 0 || response.length == 0)// server error?
    throw(response.length == 0 ? "Server error." : response);
  responseXml = xmlHttp.responseXML;// get response in XML format (assume the response is valid XML)
  xmlDoc = responseXml.documentElement;// get the document element
  result = xmlDoc.getElementsByTagName("result")[0].firstChild.data;
  fieldID = xmlDoc.getElementsByTagName("fieldid")[0].firstChild.data;
  //message = document.getElementById(fieldID + "Failed");// find the HTML element that displays the error
  //message.className = (result == "0") ? "error" : "hidden";// show the error or hide the error
  if (result == "0" || result == "2")
  {
    //Show the errors
    if (result == "0")
    {
      message = document.getElementById(fieldID + "Failed");// find the HTML element that displays the error
      if(message != null){ message.className = "error";}
    }
    else if (result == "2")
    {
      message = document.getElementById(fieldID + "Failed2");// find the HTML element that displays the error
      if(message != null){ message.className = "error";}
    }
    //Hide the errors
    if (result == "0")
    {
      message = document.getElementById(fieldID + "Failed2");// find the HTML element that displays the error
      if(message != null){ message.className = "hidden";}
    }
    else if (result == "2")
    {
      message = document.getElementById(fieldID + "Failed");// find the HTML element that displays the error
      if(message != null){ message.className = "hidden";}
    }
  }
  else
  {
    message = document.getElementById(fieldID + "Failed");// find the HTML element that displays the error
    if(message != null){ message.className = "hidden";}
    message = document.getElementById(fieldID + "Failed2");// find the HTML element that displays the error
    if(message != null){ message.className = "hidden";}
  }
  setTimeout("validate();", 500);// call validate() again, in case there are values left in the cache
}


