var mostrarErrores = true;
var cache = new Array();

//Función que obtiene el objeto XMLHTTPRequest
function getXMLHTTPRequest() {
	try {
	req = new XMLHttpRequest();
	} catch(err1) {
	  try {
	  req = new ActiveXObject("Msxml2.XMLHTTP");
	  } catch (err2) {
	    try {
	    req = new ActiveXObject("Microsoft.XMLHTTP");
	    } catch (err3) {
	      req = false;
	    }
	  }
	}
	return req;
}

function solicitudGET(url, query, req) {
	myRand=parseInt(Math.random()*99999999);
	req.open("GET",url+'?'+query+'&rand='+myRand,true);
	req.send(null);
}

function solicitudPOST(url, query, req) {
	req.open("POST", url,true);
	req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	req.send(query);
}


function cargarpagina(myreq, id_contenedor,item){
  if (myreq.readyState == 4 && (myreq.status==200 || window.location.href.indexOf("http")==-1))
          document.getElementById(id_contenedor).innerHTML=item;
}



//doAjax('compra.php','','mostrar','post','1')
function doAjax(url,query,id_contenedor,metSolicitud,getxml) {
	// crea la instancia del objeto XMLHTTPRequest 
	var myreq = getXMLHTTPRequest();

	myreq.onreadystatechange = function() {
	if(myreq.readyState == 4) {
	   if(myreq.status == 200) {
		  var item = myreq.responseText;
		  if(getxml==1) {
			 item = myreq.responseXML;
			 cargarpaginaXML(myreq,id_contenedor,item);
		  }
		  //resultado(metRespuesta, item);
		  cargarpagina(myreq,id_contenedor,item);
		}
	  }
	}
	if(metSolicitud=='post') {
		solicitudPOST(url,query,myreq);
	} else {
		solicitudGET(url,query,myreq);
	}
}

var xmlhttp = getXMLHTTPRequest();

function validar(valorEntrada, idCampo, url,idFormulario)
{
  
  // 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 (idCampo)
    {
      // codifica valores para añadirlos de modo seguro a una petición string HTTP
      inputValue = encodeURIComponent(valorEntrada);
      fieldID = encodeURIComponent(idCampo);
      // adiciona los valores a la cola de peticiones
      cache.push("InputValue=" + inputValue + "&idForm=" + idFormulario + "&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", url, true);
	        xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	        xmlhttp.onreadystatechange = respuestaHttp;
	        xmlhttp.send(cacheEntry);
      	}
      	else{
			// si la conexión está ocupada, prueba de nuevo después de un segundo  
    		setTimeout('validar()', 1000);
    	}
    }
    catch (e){
    	// muestra un error cuando falla la conexión al servidor
      	mostrarError(e.toString());
    }
  }
}

function respuestaHttp(){
	// 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
	        
			// 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)
			xmlResponse = xmlhttp.responseXML;
			
			// obtenemos el "document element" (el elemento raíz) de la estructura XML
			xmlDoc = xmlResponse.documentElement;
			
			result = xmlDoc.getElementsByTagName("resultado")[0].firstChild.data;
			fieldID = xmlDoc.getElementsByTagName("idcampo")[0].firstChild.data;
			
			// encuentra el elemento HTML que muestra el error
			var mensaje = document.getElementById(fieldID+"Fallo");
			// muestra el error o bien oculta el error
			
			mensaje.className = (result == "0") ? "error" : "hidden"
			
			// llama a validar() de nuevo, en caso que haya valores en la cache
			setTimeout("validar();", 500)	
	      }
	      catch(e){
	        // muestra mensaje de error
	        mostrarError(e.toString());
	      }
	    }
    	else{
      		// muestra mensaje de error
      		mostrarError(xmlhttp.statusText);
    	}
  	}
}

// función que muestra un mensaje de error
function mostrarError($mensaje){
  // ignora errores si showErrors es falso
  if (mostrarErrores){
    // devuelve error mostrando Off
    mostrarErrores = false;
    // muestra mensaje error
    alert("Error encontrado: \n" + $mensaje);
    // reintenta validación después de 10 segundos
  }
}

