// contiene una instancia de XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
// contiene la dirección del archivo de lado del servidor 
var serverAddress = "registrar_v.php";

// inicializa la cache para las peticiones de validación 
var cache = new Array();
 // cuando se configura como true, muestra mensajes de error detallados
var showErrors = true;
//
// FUNCION GENERAL - crea una instancia XMLHttpRequest
//
function createXmlHttpRequestObject() 
{
 
  // almacenará la referencia al objeto XMLHttpRequest
   var xmlHttp;
   // esto debe funcionar para todos los navegadores excepto IE6 y más antiguos
  try
  {
    // intenta crear el objeto XMLHttpRequest
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    // asume IE6 o más antiguo
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.7.0",
									"MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
    // prueba cada id hasta que uno funciona
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
    {
      try 
      { 
        // prueba a crear el objeto XMLHttpRequest
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {} // ignora error potencial
    }
  }
  // devuelve el objeto creado o muestra un mensaje de error
  if (!xmlHttp)
    displayError("Error al crear el objeto XMLHttpRequest.");
  else 
    return xmlHttp;
}

// función que muestra un mensaje de error
function displayError($message)
{
  // ignora errores si showErrors es falso
  if (showErrors)
  {
    // devuelve error mostrando Off
    showErrors = false;
    // muestra mensaje error
 
    alert("Error encontrado: \n" + $message);
    // reintenta validación después de 10 segundos
    setTimeout("validar();", 10000);
  }
}// contiene una instancia de XMLHttpRequest

//
// CONTROL DE FORMULARIO - la función maneja la validación para todos los campos del formulario
//
function validar(inputValue, fieldID)
{
// sólo continúa si xmlHttp no está vacío
  if (xmlHttp)
  {
    // si recibimos parámetros no-null, los añadimos al cache en el
    // formulario del string de petición a enviar al servidor para validación
    if (fieldID)
    {
      // codifica valores para añadirlos de modo seguro a una petición string HTTP
      inputValue = encodeURIComponent(inputValue);
      fieldID = encodeURIComponent(fieldID);
      // add the values to the queue
      cache.push("inputValue=" + inputValue + "&fieldID=" + fieldID);
    }
    // prueba a conectar al servidor
    try
    {
      // continúa sólo si el objeto MLHttpRequest no está completo
      // y el cache no está vacío
      if ((xmlHttp.readyState == 4 || xmlHttp.readyState == 0) 
         && cache.length > 0)
      {
        // configura un nuevo set de parámetros desde el cache
        var cacheEntry = cache.shift();
        // hace una petición al servidor para validar los datos extraídos
        xmlHttp.open("POST", serverAddress, true);
        xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xmlHttp.onreadystatechange = handleRequestStateChange;
        xmlHttp.send(cacheEntry);
      }
    }
    catch (e)
    {
      // muestra un error cuando falla la conexión al servidor
      displayError(e.toString());
    }
  }
}

// función que maneja la respuesta HTTP
function handleRequestStateChange() 
{
// cuando readyState es 4, leemos la respuesta del servidor
  if (xmlHttp.readyState == 4) 
  {
    // continúa sólo si el status HTTP es "OK"
    if (xmlHttp.status == 200) 
    {
      try
      {
        // lee la respuesta del servidor
        readResponse();
      }
      catch(e)
 
      {
        // muestra mensaje de error
        displayError(e.toString());
      }
    }
    else
    {
      // muestra mensaje de error
      displayError(xmlHttp.statusText);
    }
  }
}

// CONTROL DE FORMULARIO - lee respuesta del servidor 
function readResponse()
{
  // recupera la respuesta del servidor 
  var response = xmlHttp.responseText;
  // ¿error del servidor?
  if (response.indexOf("ERRNO") >= 0 
      || response.indexOf("error:") >= 0
      || response.length == 0)
    throw(response.length == 0 ? "Server error." : response);
  // obtiene la respuesta en formato XML(se asume que la respuesta es XML válido)
  responseXml = xmlHttp.responseXML;
  // obtiene el document element
  xmlDoc = responseXml.documentElement;
  result = xmlDoc.getElementsByTagName("result")[0].firstChild.data;
  fieldID = xmlDoc.getElementsByTagName("fieldid")[0].firstChild.data;
  // encuentra el elemento HTML que muestra el error
  message = document.getElementById(fieldID + "Failed");
  // muestra el error o bien oculta el error
  message.className = (result == "0") ? "error" : "hidden";
  // llama a validate() de nuevo, en caso que haya valores en la cache
  setTimeout("validar();", 500);
}

// CONTROL DE FORMULARIO - configura el focus en el primer campo del formulario
function setFocus()    
{
  document.getElementById("nombre").focus();
}
//
