// ***************************************************************************
// ***************************************************************************
//
// Funciones relacionadas con la BOTONERA
//
// ***************************************************************************
// ***************************************************************************

var objAjax;
var objAjaxPaises, objAjaxEspecies, objAjaxTemas;
var temporizacionPaises, temporizacionEspecies, temporizacionTemas;
objAjaxPaises = null;
objAjaxEspecies = null;
objAjaxTemas = null;
temporizacionPaises = null;
temporizacionEspecies = null;
temporizacionTemas = null;
temporizacionMensajito = null;

function B1_onclick() {
contenedor = document.getElementById("zonatrabajo");
contenedor.innerHTML = "Holaaaa";                
}

function B2_onclick() {
contenedor = document.getElementById("zonatrabajo");
contenedor.innerHTML = "Adios";                
}

function B3_onclick() {
boton = document.getElementById("B1");
if (boton.disabled == true)
   boton.disabled = false;
else
	 boton.disabled = true;
   
contenedor = document.getElementById("zonatrabajo");
contenedor.innerHTML = "Boton B1 disabled a " + boton.disabled;                
}

function B4_onclick() {
contenedor = document.getElementById("B1");
//alert("Valor: " + contenedor.value);
//contenedor.value = 'OK';                
//contenedor.setAttribute("value", "OK");
contenedor.innerHTML = "OK";
}

function B5_onclick() {
contenedor = document.getElementById("botonera");
//alert("Valor de visibilidad: " + contenedor.style.visibility);
if (contenedor.style.visibility == 'hidden')
   contenedor.style.visibility = 'visible';   
else     
	 contenedor.style.visibility = 'hidden'        
}

function FinSesion_onclick(paginaderetorno)
{  	
  CancelarPeticionesAJAX();
  OcultarBotonera();
  FinSesion(paginaderetorno); 
}

function Buscar_onclick()
{  
	//alert("Buscar_onclick");
  CancelarPeticionesAJAX();	
  Buscar(); 
}

function Buscar_Simple_Anidada_onclick()
{
  //alert("Preparar Busqueda anidada simple");
  	BusquedaAnidada();
}

function VerTodo_onclick()
{
	CancelarPeticionesAJAX();
	BusquedaSimple(2,0);
}

function Buscar_Simple_onclick()
{
	//alert("Buscar_Simple_onclick");
	limpiar_mensajecero("ceroresultados_simple");
	BusquedaSimple(0,0);
}

function Buscar_Avanzado_onclick()
{
	limpiar_mensajecero("ceroresultados_avanzado");
	BusquedaAvanzada(0,0);
}

function SubirImagen_onclick()
{
  var boton = document.getElementById("subirimg");
  //alert("Texto del botón: " + boton.innerHTML);
  if (boton.innerHTML == "CANCELAR")
     ; //DESDocumentandoImg()
  else
     Upload();		
}

function SubirLote_onclick()
{
  UploadLote();		
}

function DeshabilitarUpload()
{
   var boton;
   boton = document.getElementById("subirimg");
   boton.onclick = SinPermiso;
   boton = document.getElementById("subirlote");
   boton.onclick = SinPermiso;
}

function SinPermiso()
{
    var pagina = 'ay_nopermiso.asp';
    var contenedor = document.getElementById("areatrabajo");
        
    //Se crea un objeto XMLHttpRequest
    objAjax = crearAjax();     
    objAjax.open("GET", pagina, true);  	
	
    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");        
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {      	
      	 //var scs = objAjax.responseText.extractScript();    //capturamos los scripts
       	 contenedor.innerHTML = objAjax.responseText;     
       	 objAjax = null;  	            
         //scs.evalScript();       //ahora sí, comenzamos a interpretar todo                         
      }
    }
    objAjax.send(null);    
	
}

function VisualizarBotonera()
{
  var botonera = document.getElementById("botonera");	
  botonera.style.visibility = 'visible';
}

function Desactivar()
{
  var x = document.getElementById("vertodo");
  if (x != null) {
     x.style.disabled = "disabled";
  }
}

function HanilitarBotonInicio(habilitar)
{
  var valor;
  valor = habilitar == true ? '' : 'disabled';
  var x = document.getElementById("buscar");
  x.disabled = valor;	
  x.className = habilitar == true ? 'opaco' : 'transparente';
}

//function HabilitarBotonera(habilitar)
//{
//   alert("HabilitarBotonera");
//   HabilitarBotonera(true, habilitar);
//}

function HabilitarBotonera(todo, habilitar)
{
  var valor, x;
  if (todo)
  {  
     valor = habilitar == true ? '' : 'disabled';
     x = document.getElementById("buscar");
     x.disabled = valor;
     x.onclick = Buscar_onclick;
     x.className = habilitar == true ? 'opaco' : 'transparente';
     x = document.getElementById("vertodo");
     x.disabled = valor;
     x.className = habilitar == true ? 'opaco' : 'transparente';
     x = document.getElementById("subirimg");
     x.disabled = valor;
     x.className = habilitar == true ? 'opaco' : 'transparente';
     x = document.getElementById("subirlote");
     x.disabled = valor;
     x.className = habilitar == true ? 'opaco' : 'transparente';
     x = document.getElementById("cerrarsesion");
     x.disabled = valor;
     x.className = habilitar == true ? 'opaco' : 'transparente';
  } else // Solo se aplica el cambio al botón Buscar/Inicio:  // De todas formas, por aqui no va a pasar nunca.
  {
     x = document.getElementById("buscar");
     x.disabled = valor;
     x.className = habilitar == true ? 'opaco' : 'transparente';  
     if (habilitar == true)
        x.onclick = FinSesion_onclick;
     else
     	x.onclick = Buscar_onclick;
  }
  
  //x = document.getElementById("botonera");
  //x.className = habilitar == true ? 'opaco' : 'transparente';
  //alert("x.class=" + x.className);
  
}

function OcultarBotonera()
{
  //var botonera = document.getElementById("botonera");	  	
  //botonera.style.disabled = "disabled";
  HabilitarBotonera(true, false);	
}

function Habilitar_Boton(id) {
  var boton;
  boton = document.getElementById(id);
  boton.disabled = '';
  boton.className = 'opaco';
}

function Deshabilitar_Boton(id) {
  var boton;
  boton = document.getElementById(id);
  boton.disabled = 'disabled';
  boton.className = 'transparente';
}

function DocumentandoImg()
{ 
  // Mientras se documenta, se deshabilitan todos los botones de la botonera
  // y sólo se habilita el de "Subir Imagen" o "Subir Lote" pero con el texto "CANCELAR":
  var boton;  
  boton = document.getElementById("buscar");
  boton.disabled = true;
  boton = document.getElementById("vertodo");
  boton.disabled = true;
  boton = document.getElementById("cerrarsesion");
  boton.disabled = true;
  boton = document.getElementById("subirimg");
  boton.innerHTML = "CANCELAR";
  //boton.disabled = true;
  boton = document.getElementById("subirlote");
  boton.innerHTML = "CANCELAR";
}

function DESDocumentandoImg()
{ 
  // Mientras se documenta, se deshabilitan todos los botones de la botonera
  // y sólo se habilita el de "Subir Imagen" o "Subir Lote" pero con el texto "CANCELAR":
  var boton;  
  boton = document.getElementById("buscar");
  boton.disabled = false;
  boton = document.getElementById("vertodo");
  boton.disabled = false;
  boton = document.getElementById("cerrarsesion");
  boton.disabled = false;
  boton = document.getElementById("subirimg");
  boton.innerHTML = "Subir Imagen";
  boton.disabled = false;
  boton = document.getElementById("subirlote");
  boton.innerHTML = "Subir Lote";
  boton.disabled = false;
}

function tecla(evento, opcion) 
{ 	
    //alert("evento.keyCode="+evento.keyCode);
    if (evento.keyCode==13) // RETURN
    { 
    	//alert("evento.keyCode==13");
        //evento.keyCode=0; 
        if (opcion==1) 
        { 
            //alert("opcion == 1");
            document.formulario.txtPassword.focus();  
            return false;           
        } 
        else 
        { 
            //alert("opcion != 1");
            enviar(); 
            return false;
        } 
    }  
    return true;

/*
var keynum;

if(window.event) // IE
  {
  keynum = evento.keyCode;
  }
else if(evento.which) // Netscape/Firefox/Opera
  {
  keynum = evento.which;
  }
alert("keynum=" + keynum);
*/
}

function tecla_caja_buscar(evento, caja, id_carpeta) 
{ 	
    //alert("evento.keyCode="+evento.keyCode);
    if (evento.keyCode==13) // RETURN
    { 
    	  //alert("evento.keyCode==13  caja.value=" + caja.value);
    	  if (caja.name == "caja_busqueda_simple")
    	     Buscar_Simple_onclick();  
    	  else if (caja.name == "caja_busqueda_anidada")
    	  	 Buscar_Simple_Anidada_onclick();
    	  else if (caja.name == "caja_busqueda_anidada_privada")
    	  	 if (id_carpeta != null)
    	  	    VerCarpeta(id_carpeta , 1, true);
    	  	      
    }  
    return true;
}

function limpiar()
{
   var contenedor_mensaje = document.getElementById("errorusuario");	
   if (contenedor_mensaje != null)
   {
      contenedor_mensaje.innerHTML = "Tampoco se ve esto";
      contenedor_mensaje.className = 'errorusuarioinv';
   }
}

function limpiar_mensajecero(caja_mensaje)
{
   var contenedor_mensaje = document.getElementById(caja_mensaje);	
   if (contenedor_mensaje != null)
   {
      contenedor_mensaje.innerHTML = "Tampoco se debe ver esto";
      contenedor_mensaje.className = 'ceroresultadosinv';
   }
}


function IconoEspera(activar)
{
    //Si Cambiamos el icono del cursor a "espera":
    var body = document.getElementsByTagName("body")[0];
    var ya_tiene = new RegExp('punteroEspera').test(body.className);
    
    if (activar)
    {
       //alert("Pon ESPERA " + body.className + "   ya_tiene=" + ya_tiene);
       if (!ya_tiene)
          body.className += " punteroEspera";
    } else
    {	      
    	 //alert("Quita ESPERA: " + body.className + "   ya_tiene=" + ya_tiene);           
         if (ya_tiene)
         {                      
            var rep = body.className.match(' punteroEspera') ? ' punteroEspera' : 'punteroEspera';
            body.className = body.className.replace(rep,'');      
         }      	
    }	
}

function nuevoUsuario()
{
	/*var posY;
	if ((screen.width == 640) && (screen.height == 480))
	{
		posY=0;
	}
	if ((screen.width == 800) && (screen.height == 600))
	{
		posY=0;
	}
	if ((screen.width > 800) && (screen.height > 600))
	{
		posY=150;
	}
	//window.open("http://www.cesefor.com/usuariopt/usuariopt.asp","","top=" + posY + "px,left=0px,titlebar=no,toolbar=no,scrollbars=no,status=no,width=785,height=496,resizable=no");*/
	window.open("http://www.cesefor.com/login.asp");
}

function recordar()
{
	//window.open("http://www.cesefor.com/recordarpass.asp","","titlebar=no,toolbar=no,scrollbars=no,status=no,width=300,height=180,resizable=no");
	window.open("http://www.cesefor.com/recordarpass.asp");
}

function trim(texto)
	{
		var longitud=texto.length;
		var i;
		var j;
		for (i=0; i<longitud; i++){
			if (texto.substring(i,i+1)!==" "){
				break;
			}
		}
		for (j=longitud; j>0; j--){
			if (texto.substring(j-1,j)!==" "){
				break;
			}
		}
		if (j==0) {
			texto = "";
		}else{
			texto = texto.substring(i,j);
		}
		return texto;
	}
	
function enviar()
{
	//alert ("action: " + document.formulario.action);
	if (trim(document.formulario.txtLogin.value)=="" || trim(document.formulario.txtPassword.value)=="")
	{
		//alert ("Introduzca usuario y contraseña");
		var contenedor_mensaje = document.getElementById("errorusuario");             
                contenedor_mensaje.innerHTML = "Introduzca usuario y contrase&ntilde;a";
                contenedor_mensaje.className = 'errorusuariovis';  
                //if (trim(document.formulario.txtLogin.value)=="")
                //   document.formulario.txtLogin.focus();              
	}
	else if (document.formulario.txtLogin.value.indexOf("'") != -1 || document.formulario.txtPassword.value.indexOf("'") != -1)
	{
		var contenedor_mensaje = document.getElementById("errorusuario");             
                contenedor_mensaje.innerHTML = "Caracteres no permitidos";
                contenedor_mensaje.className = 'errorusuariovis'; 		
	}
	else
	{				
		ValidarUsuario(false);
		
	}	
	//alert ("Despues de enviarrrr");
}


// ***************************************************************************
// ***************************************************************************
//
// Funciones del fichero "script.jse"
//
// ***************************************************************************
// ***************************************************************************

function abrirVentana(url){ 
  var winFototeca;
  var ancho = screen.width;
  var alto = screen.height;
  var anchoUtil = screen.availwidth;
  var altoUtil = screen.availheight;
  var coorX=0;
  var coorY=0;
  var opciones="";
  var opciones="";
  if (ancho < 1024) {
    opciones="scrollbars=yes,resizable=no,width=791,height=550,status=yes,location=no,toolbar=no";
  }
  else {
    opciones="scrollbars=no,resizable=no,width=800,height=600,status=yes,location=no,toolbar=no";
    coorX=(ancho-800)/2;
    coorY=(alto-600)/2;
  }
  winFototeca=window.open(url,"fototeca",opciones);
  winFototeca.moveTo(coorX,coorY);
  winFototeca.focus();
  return;
}

function abrirVentana2(url){ 
  var winFototeca2;
  var ancho = screen.width;
  var alto = screen.height;
  var coorX=(ancho-790)/2;
  var coorY=(alto-525)/2;
  opciones="scrollbars=no,resizable=no,width=790,height=525,status=yes,location=no,toolbar=no";
  winFototeca2=window.open(url,"upload",opciones);
  winFototeca2.moveTo(coorX,coorY);
  winFototeca2.focus();
  return;
}

function abrirVentana3(url){ 
  var winFototeca3;
  var ancho = screen.width;
  var alto = screen.height;
  var coorX=(ancho-800)/2;
  var coorY=(alto-600)/2;
  var opciones="scrollbars=yes,resizable=no,width=500,height=320,status=yes,location=no,toolbar=no";
  winFototeca3=window.open(url,"aviso",opciones);
  winFototeca3.moveTo(coorX,coorY);
  winFototeca3.focus();
  return;
}

function abrirFoto(idfoto,foto){
 popup=window.open("","visualizador","scrollbars=no,resizable=no,width=792,height=525,status=yes,location=no,toolbar=no");
 popup.location.href="aviso_legal.asp?i="+idfoto+"&f="+foto;
// popup.location.href="ampliar.asp?i="+idfoto+"&f="+foto;
 popup.moveTo(0,0);
 popup.focus();
 return;
}

function saveImageAs (imgOrURL) { 
 if (typeof imgOrURL == 'object') imgOrURL = imgOrURL.src; 
 alert("Si no consigue guadar con el formato requerido \npulse sobre la imagen con el botón derecho \ny elija la opción Guardar imagen como...");
 var win;
 win = window.open(imgOrURL);
 win.document.execCommand("SaveAs");
 win.close();
} 

function miprueba()
{
  alert("mierda pura");
  return false;		
}

 function ValidaFoto(formu){
  if ((formu.fechatoma.value=="") || (formu.nombreautor.value=="") || (formu.apellidosautor.value=="") || (formu.toma.value=="") || (formu.descripcion.value=="")){
   alert("Es obligatorio rellenar los siguientes campos \nen la documentación de la fotografía: \n\n * Fecha de toma\n * Nombre y apellidos del autor\n * Tipo de toma\n * Descripción");
   return false;
  }
  else {
   formu.seguir.value="si";
   return true;
  }
 }

// Al documentar una fotografía, se comprueba si se pasa el nombre del fichero de alguna:
 function ValidaNombreFoto(nombre) {
  if (trim(nombre).length > 0)
     return true;
  else
     return false; 
 }
 
 // Para comprobar si al documentar por lotes se pasa alguna fotografía:
 function ValidaNombresFotosLote(numFotosLote) {
  //var elemento;
  
  for (i=1; i<=numFotosLote; i++)
  {
    //elemento = 'attach' + i;
    //alert('elemento = ' + elemento);
    if (trim(document.getElementById('attach' + i).value).length > 0)
       return true;
  }
  
  return false; // Todos los campos estaban vacíos.
 }
 
// Para eliminar los espacios en blanco por la izquierda:
function ltrim(s) {
	return s.replace(/^\s+/, "");
}
// Para eliminar los espacios en blanco por la derecha:
function rtrim(s) {
	return s.replace(/\s+$/, "");
}
// Para eliminar los espacios en blanco por ambos lados:
function trim(s) {
	return rtrim(ltrim(s));
}


// ***************************************************************************
// ***************************************************************************
//
// Fichero "interpretadorAjax.js" de http://www.forosdelweb.com/f77/howto-ejecutar-javascript-que-viene-ajax-510438/
// Relacionado con ejecutar código javascript en una llamada AJAX:
//
// ***************************************************************************
// ***************************************************************************

	var tagScript = '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)';
        /**
        * Eval script fragment
        * @return String
        */
        String.prototype.evalScript = function()
        {
                return (this.match(new RegExp(tagScript, 'img')) || []).evalScript();
        };
        /**
        * strip script fragment
        * @return String
        */
        String.prototype.stripScript = function()
        {
                return this.replace(new RegExp(tagScript, 'img'), '');
        };
        /**
        * extract script fragment
        * @return String
        */
        String.prototype.extractScript = function()
        {
                var matchAll = new RegExp(tagScript, 'img');
                return (this.match(matchAll) || []);
        };
        /**
        * Eval scripts
        * @return String
        */
        Array.prototype.evalScript = function(extracted)
        {
                var s=this.map(function(sr){
                         var sc=(sr.match(new RegExp(tagScript, 'im')) || ['', ''])[1];
                         if(window.execScript){
                              window.execScript(sc);
                         }
                        else
                       {
                           window.setTimeout(sc,0);
                        }
                });
                return true;
        };
        /**
        * Map array elements
        * @param {Function} fun
        * @return Function
        */
        Array.prototype.map = function(fun)
        {
                if(typeof fun!=="function"){return false;}
                var i = 0, l = this.length;
                for(i=0;i<l;i++)
                {
                        fun(this[i]);
                }
                return true;
        };  



// ***************************************************************************
// ***************************************************************************
//
// Funciones AJAX:
//
// ***************************************************************************
// ***************************************************************************

function AbortarPeticionAJAX()
{
	 if (objAjax != null)
	 {
	    objAjax.abort();
	    objAjax = null;
	 }	
}

function CancelarPeticionesAJAX()
{	 
	 if (objAjaxPaises != null)
	 {
	    objAjaxPaises.abort();
	    objAjaxPaises = null;
	 }
	 
	 if (objAjaxEspecies != null)
	 {
	    objAjaxEspecies.abort();
	    objAjaxEspecies = null;	    
	 }
	 
	 if (objAjaxTemas != null)
	 {
	    objAjaxTemas.abort();
	    objAjaxTemas = null;
	 }
	 
	 // Y también anulamos las posibles temporizaciones pendientes:
	 if (temporizacionPaises!= null)
	 {
	 	  clearTimeout(temporizacionPaises);
	 	  temporizacionPaises = null;
	 }
	 if (temporizacionEspecies!= null)
	 {
	 	  clearTimeout(temporizacionEspecies);
	 	  temporizacionEspecies = null;
	 }
	 if (temporizacionTemas	!= null)
	 {
	 	  clearTimeout(temporizacionTemas);
	 	  temporizacionTemas = null;
	 }	 	
	 if (temporizacionMensajito != null)
	 {
	 	  clearTimeout(temporizacionMensajito);
	 	  temporizacionMensajito = null;
	 }	 	 
}


//Función para crear un objeto XMLHttpRequest
function crearAjax() 
{
   var Ajax;
   
   AbortarPeticionAJAX();
   
   if (window.XMLHttpRequest) { // Intento de crear el objeto para Mozilla, Safari,...
     Ajax = new XMLHttpRequest();
     if (Ajax.overrideMimeType) {
       //Se establece el tipo de contenido para el objeto
       Ajax.overrideMimeType('text/xml');
       //http_request.overrideMimeType('text/html');
     }
    } else if (window.ActiveXObject) { // IE
       try { //Primero se prueba con la mas reciente versión para IE
          Ajax = new ActiveXObject("Msxml2.XMLHTTP");
       } catch (e) {
          try { //Si el explorer no esta actualizado se prueba con la versión anterior
            Ajax = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (e) {}
       }
    }
 
    if (!Ajax) {
       alert('¡Por favor, actualice su navegador!');
       return false;
    }
    else
    {
       return Ajax;
    }
 
}

// The var docForm should be a reference to a <form>

function formData2QueryString(docForm) {

	var strSubmitContent = '';
	var formElem;
	var strLastElemName = '';
	
	for (i = 0; i < docForm.elements.length; i++) {
		
		formElem = docForm.elements[i];
		switch (formElem.type) {
			// Text fields, hidden form elements
			case 'text':
			case 'hidden':
			case 'password':
			case 'textarea':
			case 'select-one':
				strSubmitContent += formElem.name + '=' + escape(formElem.value) + '&'
				break;
				
			// Radio buttons
			case 'radio':
				if (formElem.checked) {
					strSubmitContent += formElem.name + '=' + escape(formElem.value) + '&'
				}
				break;
				
			// Checkboxes
			case 'checkbox':
				if (formElem.checked) {
					// Continuing multiple, same-name checkboxes
					if (formElem.name == strLastElemName) {
						// Strip of end ampersand if there is one
						if (strSubmitContent.lastIndexOf('&') == strSubmitContent.length-1) {
							strSubmitContent = strSubmitContent.substr(0, strSubmitContent.length - 1);
						}
						// Append value as comma-delimited string
						strSubmitContent += ',' + escape(formElem.value);
					}
					else {
						strSubmitContent += formElem.name + '=' + escape(formElem.value);
					}
					strSubmitContent += '&';
					strLastElemName = formElem.name;
				}
				break;
				
		}
	}
	
	// Remove trailing separator
	strSubmitContent = strSubmitContent.substr(0, strSubmitContent.length - 1);
	return strSubmitContent;
}

// Para el tratamiento de los mensajes de error devueltos por AJAX: (debajo pongo cómo usarlo)
function handleErrFullPage(strIn) {

        var errorWin;

        // Create new window and display error
        try {
                errorWin = window.open('', 'errorWin');
                errorWin.document.body.innerHTML = strIn;
        }
        // If pop-up gets blocked, inform user
        catch(e) {
                alert('An error occurred, but the error message cannot be' +
                        ' displayed because of your browser\'s pop-up blocker.\n' +
                        'Please allow pop-ups from this Web site.');
        }
}


	// if (xmlHttpReq.readyState == 4) {
  //    strResponse = xmlHttpReq.responseText;
  //    switch (xmlHttpReq.status) {
  //    // Page-not-found error
  //      case 404:
  //         alert('Error: Not Found. The requested URL ' + 
  //              strURL + ' could not be found.');
  //              break;
  //    // Display results in a full window for server-side errors
  //      case 500:
  //         handleErrFullPage(strResponse);
  //         break;
  //      default:
  //         // Call JS alert for custom error or debug messages
  //         if (strResponse.indexOf('Error:') > -1 || 
  //             strResponse.indexOf('Debug:') > -1) {
  //            alert(strResponse);
  //         }
  //         // Call the desired result function
  //         else {
  //            eval(strResultFunc + '(strResponse);');
  //         }
  //         break;
  //   }
  // }

function MostrarAgradecimientos(vienede)
{
    var pagina = 'ay_agradecimientos.asp';
    var params = 'paginaderetorno=' + vienede;
    var contenedor = document.getElementById("areatrabajo");
        
    //Se crea un objeto XMLHttpRequest
    objAjax = crearAjax();     
    objAjax.open("POST", pagina, true);  	

    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    objAjax.setRequestHeader("Content-length", params.length);
    objAjax.setRequestHeader("Connection", "close");    	        
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {
      	
      	 //var scs = objAjax.responseText.extractScript();    //capturamos los scripts
       	 contenedor.innerHTML = objAjax.responseText;  
       	 objAjax = null;     	            
         //scs.evalScript();       //ahora sí, comenzamos a interpretar todo  
         //alert("scs=" + scs);
         //Se escribe el resultado en la capa contenedora
         //_xx_ contenedor.innerHTML = objAjax.responseText;   
         //HabilitarBotonera(true); 
         //HanilitarBotonInicio(true);     
         //_botonera_ HabilitarBotonera(false, true);
      }
    }
    objAjax.send(params);    	    	
}	

function MostrarNovedades(vienede)
{
    var pagina = 'ay_novedades.asp';
    var params = 'paginaderetorno=' + vienede;
    var contenedor = document.getElementById("areatrabajo");
        
    //Se crea un objeto XMLHttpRequest
    objAjax = crearAjax();     
    objAjax.open("POST", pagina, true);  	

    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    objAjax.setRequestHeader("Content-length", params.length);
    objAjax.setRequestHeader("Connection", "close");    	        
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {
      	
      	 //var scs = objAjax.responseText.extractScript();    //capturamos los scripts
       	 contenedor.innerHTML = objAjax.responseText;  
       	 objAjax = null;     	            
         //scs.evalScript();       //ahora sí, comenzamos a interpretar todo  
         //alert("scs=" + scs);
         //Se escribe el resultado en la capa contenedora
         //_xx_ contenedor.innerHTML = objAjax.responseText;   
         //HabilitarBotonera(true); 
         //HanilitarBotonInicio(true);     
         //_botonera_ HabilitarBotonera(false, true);
      }
    }
    objAjax.send(params);    	    	
}

function MostrarAyuda()
{
    var pagina = 'ay_ayuda.asp';
    //alert("MostrarAyuda()");
    var contenedor = document.getElementById("areatrabajo");
        
    //Se crea un objeto XMLHttpRequest
    objAjax = crearAjax();     
    objAjax.open("GET", pagina, true);  	
	
    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");        
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {
      	
      	 //var scs = objAjax.responseText.extractScript();    //capturamos los scripts
       	 contenedor.innerHTML = objAjax.responseText;  
       	 objAjax = null;     	            
         //scs.evalScript();       //ahora sí, comenzamos a interpretar todo  
         //alert("scs=" + scs);
         //Se escribe el resultado en la capa contenedora
         //_xx_ contenedor.innerHTML = objAjax.responseText;   
         //HabilitarBotonera(true); 
         //HanilitarBotonInicio(true);     
         //_botonera_ HabilitarBotonera(false, true);
      }
    }
    objAjax.send(null);    	    	
}	


function AceptarCondiciones()
{     
    var pagina = 'ay_buscador.asp';
    var contenedor = document.getElementById("areatrabajo");
        
    //Se crea un objeto XMLHttpRequest
    objAjax = crearAjax();     
    objAjax.open("GET", pagina, true);  	
	
    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");        
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {      	 
      	 var scs = objAjax.responseText.extractScript();    //capturamos los scripts
       	 contenedor.innerHTML = objAjax.responseText;  
       	 objAjax = null;     	            
         scs.evalScript();       //ahora sí, comenzamos a interpretar todo  
         //alert("scs=" + scs);
         //Se escribe el resultado en la capa contenedora
         //_xx_ contenedor.innerHTML = objAjax.responseText;   
         HabilitarBotonera(true, true);      
      }
    }
    objAjax.send(null);    	    	
}

function PresentarCondiciones()
{     
    var pagina = 'ay_condiciones.asp';
    var contenedor = document.getElementById("areatrabajo");
    
    OcultarBotonera();
        
    //Se crea un objeto XMLHttpRequest
    objAjax = crearAjax();     
    objAjax.open("GET", pagina, true);  	
	
    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");        
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {      	 
      	 var scs = objAjax.responseText.extractScript();    //capturamos los scripts
       	 contenedor.innerHTML = objAjax.responseText;  
       	 objAjax = null;     	            
         scs.evalScript();       //ahora sí, comenzamos a interpretar todo  
         //alert("scs=" + scs);
         //Se escribe el resultado en la capa contenedora
         //_xx_ contenedor.innerHTML = objAjax.responseText;   
         HabilitarBotonera(true, true);      
      }
    }
    objAjax.send(null);    	    	
}

// Si "visitante" es true significa que se va a acceder al Banco de Imágenes a través del "Acceso ABIERTO" (a través
// del usuario visitante/visitante. Si es false, se trata del "Acceso RESTRINGIDO" que exige un usuario y un password y se dará 
// paso a la ventana de login (ay_login.asp).
function ValidarUsuario(visitante)
{     
    var pagina = 'ay_comprobarusuario.asp';
    var contenedor_mensaje = document.getElementById("errorusuario");
    var params;
    if (visitante == true) // Se trata de un Acceso ABIERTO:   
       params = 'txtLogin=jr_xx_&txtPassword=jr_xx_';    
    else // Se trata de un Acceso RESTRINGIDO y debe proporcionarsew un usuario y un password:
    {
       params = 'txtLogin=' + document.formulario.txtLogin.value;
       params += '&';
       params += 'txtPassword=';
       params += document.formulario.txtPassword.value;	
    }
    contenedor_mensaje.innerHTML = "Comprobando...";	 
    contenedor_mensaje.className = 'errorusuariovis';   	
	    
    //Se crea un objeto XMLHttpRequest
    objAjax = crearAjax();     
    objAjax.open("POST", pagina, true);  	
	
    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    objAjax.setRequestHeader("Content-length", params.length);
    objAjax.setRequestHeader("Connection", "close");
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {
         //Se escribe el resultado en la capa contenedora
         if (objAjax.responseText.length < 35)
         {
            contenedor_mensaje.innerHTML = objAjax.responseText;
            contenedor_mensaje.className = 'errorusuariovis';
            //document.formulario.txtLogin.focus();
         }
         else
         {
            var areaTrabajo = document.getElementById("areatrabajo");
            VisualizarBotonera();
            var scs = objAjax.responseText.extractScript();    //capturamos los scripts
       	    areaTrabajo.innerHTML = objAjax.responseText;       	            
            scs.evalScript();       //ahora sí, comenzamos a interpretar todo  
            window.scrollTo(0,150);
         }
         objAjax = null;
      }
    }
    objAjax.send(params);    	
}


function FinSesion(paginaderetorno)
{     
    var pagina;
    if ((undefined == paginaderetorno) || paginaderetorno == null)
       paginaderetorno = "ay_inicio.asp";
    
    if (paginaderetorno == 'ay_login.asp')
       pagina = 'ay_login.asp?finsesion=si';  // Posiblemente habría que llamar a una pagina que sea "ay_finsesion.asp" que borre la sesión y luego cargue el "ay_login.asp" en el area de trabajo.    
    else
       pagina = 'ay_inicio.asp';
       
    var contenedor = document.getElementById("areatrabajo");    
	    
    //Se crea un objeto XMLHttpRequest
    objAjax = crearAjax();     
    objAjax.open("GET", pagina, true);  	
	
    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {
      	 CancelarPeticionesAJAX();
         //Se escribe el resultado en la capa contenedora
         contenedor.innerHTML = objAjax.responseText; 
         objAjax = null;
         //HabilitarBotonera(false);  
         window.scrollTo(0,150);      
      }
    }
    objAjax.send(null);    	
}

function CambiarMensajito(id)
{
	var contenedor_mensaje = document.getElementById(id);
	if (contenedor_mensaje.innerHTML.indexOf("Consultando") != -1)
	   contenedor_mensaje.innerHTML = "Espere por favor...";
	else
	   contenedor_mensaje.innerHTML = "Consultando base de datos...";
}

function Buscar()
{     
    var pagina = 'ay_buscador.asp';  
    var contenedor = document.getElementById("areatrabajo");    
	  //alert("Buscar");
        
    //Se crea un objeto XMLHttpRequest
    objAjax = crearAjax();     
    objAjax.open("GET", pagina, true);  	
	
    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");        
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {
      	 CancelarPeticionesAJAX();
         //Se escribe el resultado en la capa contenedora             
         var scs = objAjax.responseText.extractScript();    //capturamos los scripts         
         //alert("scs=" + scs);
       	 contenedor.innerHTML = objAjax.responseText;     	            
       	 objAjax = null;
         scs.evalScript();       //ahora sí, comenzamos a interpretar todo  
         window.scrollTo(0,150);    
      }
    }
    objAjax.send(null);    	
}

function BusquedaAnidada()
{
    var params;
    var pagina = 'ay_resultados.asp?tipo=anidada&sb=0';  
    var contenedor = document.getElementById("areatrabajo");  
    var contenedor_mensaje = document.getElementById("ceroresultados_simple");
    
    if (contenedor_mensaje != null)
    {
       contenedor_mensaje.innerHTML = "Consultando base de datos...";
       contenedor_mensaje.className = 'ceroresultadosvis';
       temporizacionMensajito = setInterval('CambiarMensajito("ceroresultados_simple")', 2000);
    }
    
    params = 'busqueda=' + encodeURIComponent(document.formulario_anidado.caja_busqueda_anidada.value);

    //Se crea un objeto XMLHttpRequest
    objAjax = crearAjax();     
    objAjax.open("POST", pagina, true);  	     
    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    
    objAjax.setRequestHeader("Content-length", params.length);
    objAjax.setRequestHeader("Connection", "close");
    
    IconoEspera(true); 
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {
      	 IconoEspera(false); 
      	 CancelarPeticionesAJAX();
      	 if (objAjax.responseText.length < 66)
         {
            if (contenedor_mensaje != null)
            {
               contenedor_mensaje.innerHTML = objAjax.responseText;
               contenedor_mensaje.className = 'ceroresultadosvis';
               var resultados, tabla, botones, botonbuscar;
               resultados = document.getElementById("id_resultados");
               if (resultados != null)
                  resultados.innerHTML = '<span id="resultados">' + objAjax.responseText + '</span>'; //No hay fotos en esta carpeta
               tabla = document.getElementById("tabla_fotos_resultados");
               if (tabla != null)             
                  tabla.innerHTML = "";                             
               botones = document.getElementById("botones_fotos_resultados");
               if (botones != null)             
                  botones.innerHTML = ""; 
               // Deshabilito el botón de busqueda anidada simple:                 
               botonbuscar = document.getElementById("buscar_simple_anidada");
               if (botonbuscar != null)             
                  botonbuscar.disabled = "disabled";                                         
            }
            //alert("Error: " + objAjax.responseText);            
         } else
         {
      	    //CancelarPeticionesAJAX();      	 
            //Se escribe el resultado en la capa contenedora             
            var scs = objAjax.responseText.extractScript();    //capturamos los scripts
            //alert("scs=" + scs);
       	    contenedor.innerHTML = objAjax.responseText;     	            
            scs.evalScript();       //ahora sí, comenzamos a interpretar todo               
         }
         objAjax = null;
      }
    }
    objAjax.send(params);    	    
    
}


// Botón situado en "ay_buscador.asp" que inicia la búsqueda simple:
function BusquedaSimple(nuevabusqueda, numpag)
{     
	  // Los posibles valores de "nuevabusqueda" son:
	  // 0: Se va a realizar una nueva busqueda
	  // 1: Se cambia la pagina de resultados de la busqueda en curso
	  // 2: Se ha pulsado "VerTodo" por lo que borramos los datos de sesión de la busqueda en curso
	  
    var params;
    var pagina = 'ay_resultados.asp?tipo=simple&sb=' + nuevabusqueda;  
    var contenedor = document.getElementById("areatrabajo");  
    var contenedor_mensaje = document.getElementById("ceroresultados_simple");
    //alert("contenedor_mensaje=" + contenedor_mensaje);
    if (contenedor_mensaje != null)
    {
       contenedor_mensaje.innerHTML = "Consultando base de datos...";
       contenedor_mensaje.className = 'ceroresultadosvis';
       // Activo temporización para que cambie el mensajito cada cierto tiempo:
       temporizacionMensajito = setInterval('CambiarMensajito("ceroresultados_simple")', 2000);
    }
   
    var contenedor_msjevores = document.getElementById("msjevores");    
    if (contenedor_msjevores != null)
    {
       contenedor_msjevores.innerHTML = "Consultando base de datos...";
       contenedor_msjevores.className = 'ceroresultadosvis';
       // Activo temporización para que cambie el mensajito cada cierto tiempo:
       //temporizacionMensajito = setInterval('CambiarMensajito("ceroresultados_simple")', 2000);
    }
   
    if (nuevabusqueda == 0)
    {
       params = 'busqueda=' + encodeURIComponent(document.formulario_simple.caja_busqueda_simple.value);
       //alert("params="+params);
       //params += '&';
       //params += 'txtPassword=';
       //params += document.formulario.txtPassword.value;	  
     } else
     {
       params = '';
       pagina = pagina + '&pagina=' + numpag;
     }
	  
    //alert("params=" + params);
    //Se crea un objeto XMLHttpRequest    
    objAjax = crearAjax();     
    objAjax.open("POST", pagina, true);  	
    //alert("pagina=" + pagina);      
    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    
    objAjax.setRequestHeader("Content-length", params.length);
    objAjax.setRequestHeader("Connection", "close");
    
    IconoEspera(true);    
  
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {
      	 IconoEspera(false);
      	 CancelarPeticionesAJAX();
      	 if (objAjax.responseText.length < 66)
         {
            if (contenedor_mensaje != null)
            {
               contenedor_mensaje.innerHTML = objAjax.responseText;
               contenedor_mensaje.className = 'ceroresultadosvis';
            } //else
            //	 alert("Mensaje inesperado: " + objAjax.responseText);
            //document.formulario.txtLogin.focus();
            if (contenedor_msjevores != null)
            {
               contenedor_msjevores.innerHTML = objAjax.responseText;
               contenedor_msjevores.className = 'ceroresultadosvis';
            } 
         } else
         {
      	    //CancelarPeticionesAJAX();      	 
            //Se escribe el resultado en la capa contenedora             
            var scs = objAjax.responseText.extractScript();    //capturamos los scripts
            //alert("scs=" + scs);
       	    contenedor.innerHTML = objAjax.responseText;          	      	            
            scs.evalScript();       //ahora sí, comenzamos a interpretar todo               
         }
         objAjax = null;         
      }
    }
    objAjax.send(params);    	
}


// Botón situado en "ay_buscador.asp" que inicia la búsqueda simple:
function BusquedaAvanzada(nuevabusqueda, numpag)
{     
	  // Los posibles valores de "nuevabusqueda" son:
	  // 0: Se va a realizar una nueva busqueda
	  // 1: Se cambia la pagina de resultados de la busqueda en curso	  
	  
    var params;
    var pagina = 'ay_resultados.asp?tipo=avanzada&sb=' + nuevabusqueda;  
    var contenedor = document.getElementById("areatrabajo");  
    var contenedor_mensaje = document.getElementById("ceroresultados_avanzado");
    //alert("contenedor_mensaje=" + contenedor_mensaje);
    if (contenedor_mensaje != null)
    {
       contenedor_mensaje.innerHTML = "Consultando base de datos...";
       contenedor_mensaje.className = 'ceroresultadosvis';
    }

    var contenedor_msjevores = document.getElementById("msjevores");    
    if (contenedor_msjevores != null)
    {
       contenedor_msjevores.innerHTML = "Consultando base de datos...";
       contenedor_msjevores.className = 'ceroresultadosvis';
       // Activo temporización para que cambie el mensajito cada cierto tiempo:
       //temporizacionMensajito = setInterval('CambiarMensajito("ceroresultados_simple")', 2000);
    }
       
    if (nuevabusqueda == 0)
    {   
       params = 'especie=';   
       if ((undefined == window.cbEspecies) || cbEspecies == null)
          params += ""; //encodeURIComponent("-1");
       else
       {            
          if (isNaN(cbEspecies.value)) {
       	     params += encodeURIComponent("-1");         
          } else {
       	     params += encodeURIComponent(cbEspecies.value);          
          }
       }
       
       params += '&tema=';
       if ((undefined == window.cbTemas) || cbTemas == null)
          params += ""; //encodeURIComponent("-1");       
       else
       {
          if (isNaN(cbTemas.value))       	     
       	     params += encodeURIComponent("-1");         
          else       	    
       	     params += encodeURIComponent(cbTemas.value);                    
       }
       
       params += '&municipio=';
       if (!(undefined == document.formulario_avanzado.municipio))
          params += encodeURIComponent(document.formulario_avanzado.municipio.value);
       
       params += '&provincia=';
       if (!(undefined == document.formulario_avanzado.provincia))
          params += encodeURIComponent(document.formulario_avanzado.provincia.value);      
       
       params += '&pais=';
       if (!(undefined == document.formulario_avanzado.pais))
          params += encodeURIComponent(document.formulario_avanzado.pais.value);
       
       params += '&autor=';
       params += encodeURIComponent(document.formulario_avanzado.autor.value);       
       
       params += '&fechatoma=';
       params += encodeURIComponent(document.formulario_avanzado.fechatoma.value);
       
       //alert("params=" + params);         
    } else
    {
       params = '';
       pagina = pagina + '&pagina=' + numpag;
    }
	  
    //alert("params=" + params);
    
    IconoEspera(true);  
       
    //Se crea un objeto XMLHttpRequest
    objAjax = crearAjax();     
    objAjax.open("POST", pagina, true);  	
    //alert("pagina=" + pagina);      
    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    
    objAjax.setRequestHeader("Content-length", params.length);
    objAjax.setRequestHeader("Connection", "close");
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {
      	 IconoEspera(false); 
      	 CancelarPeticionesAJAX();
      	 if (objAjax.responseText.length < 66)
         {
            if (contenedor_mensaje != null)
            {
               contenedor_mensaje.innerHTML = objAjax.responseText;
               contenedor_mensaje.className = 'ceroresultadosvis';
            } else
            	 alert("Mensaje inesperado: " + objAjax.responseText);
            //document.formulario.txtLogin.focus();
            if (contenedor_msjevores != null)
            {
               contenedor_msjevores.innerHTML = objAjax.responseText;
               contenedor_msjevores.className = 'ceroresultadosvis';
            } 
         } else
         {
      	    //CancelarPeticionesAJAX();      	 
            //Se escribe el resultado en la capa contenedora             
            var scs = objAjax.responseText.extractScript();    //capturamos los scripts
            //alert("scs=" + scs);
       	    contenedor.innerHTML = objAjax.responseText;     	            
            scs.evalScript();       //ahora sí, comenzamos a interpretar todo               
         }
         objAjax = null;
      }
    }
    objAjax.send(params);    	
}

function VerCarpeta(id, numpag, esAnidada)
{         // id: identificador de la carpeta
	  // numpag: número de página de resultados a visualizar	  
	  
    var params, texto;    
    var pagina = 'ay_privadas.asp';
    var contenedor = document.getElementById("areatrabajo");
    var contenedor_mensaje = document.getElementById("ceroresultados_simple");
    //alert("contenedor_mensaje=" + contenedor_mensaje);
    if (contenedor_mensaje != null)
    {
       contenedor_mensaje.innerHTML = "Accediendo a la carpeta...";
       contenedor_mensaje.className = 'ceroresultadosvis';
    }
    
    var contenedor_msjevores = document.getElementById("msjevores");    
    if (contenedor_msjevores != null)
    {
       contenedor_msjevores.innerHTML = "Consultando base de datos...";
       contenedor_msjevores.className = 'ceroresultadosvis';
       // Activo temporización para que cambie el mensajito cada cierto tiempo:
       //temporizacionMensajito = setInterval('CambiarMensajito("ceroresultados_simple")', 2000);
    }
    	
    params = 'id=' + id + '&pagina=' + numpag;  
    if (esAnidada)
    {
    	texto = document.formulario_anidado.caja_busqueda_anidada_privada.value
        if (trim(texto).length > 0)
        {
           params += '&busqueda=';
           params += encodeURIComponent(texto);
        }
    }
        
    //Se crea un objeto XMLHttpRequest
    objAjax = crearAjax();     
    objAjax.open("POST", pagina, true);  	
     
    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    
    objAjax.setRequestHeader("Content-length", params.length);
    objAjax.setRequestHeader("Connection", "close");  
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {
      	 CancelarPeticionesAJAX();
      	 if (objAjax.responseText.length < 66)
         {
            if (contenedor_mensaje != null)
            {
               contenedor_mensaje.innerHTML = objAjax.responseText;
               contenedor_mensaje.className = 'ceroresultadosvis';
               //contenedor.innerHTML ="";
               var resultados, tabla, botones, botonbuscar;
               resultados = document.getElementById("id_resultados08");
               if (resultados != null)
                  resultados.innerHTML = '<span id="resultados08">' + objAjax.responseText + '</span>'; //No hay fotos en esta carpeta
               tabla = document.getElementById("tabla_fotos_privadas");
               if (tabla != null)             
                  tabla.innerHTML = "";                             
               botones = document.getElementById("botones_fotos_privadas");
               if (botones != null)             
                  botones.innerHTML = ""; 
               // Deshabilito el botón de busqueda anidada simple:                 
               botonbuscar = document.getElementById("buscar_simple_anidada");
               if (botonbuscar != null)             
                  botonbuscar.disabled = "disabled";                   
            } 
            if (contenedor_msjevores != null)
            {
               contenedor_msjevores.innerHTML = objAjax.responseText;
               contenedor_msjevores.className = 'ceroresultadosvis';
            } 
         } else
         {
      	    //CancelarPeticionesAJAX();      	 
            //Se escribe el resultado en la capa contenedora             
            var scs = objAjax.responseText.extractScript();    //capturamos los scripts
            //alert("scs=" + scs);
       	    contenedor.innerHTML = objAjax.responseText;     	            
            scs.evalScript();       //ahora sí, comenzamos a interpretar todo               
         }
         objAjax = null;
      }
    }
    objAjax.send(params);    	
}


function Upload()
{     
    var pagina = 'ay_Upload-Progress.asp?';
    var contenedor = document.getElementById("areatrabajo");    
	    
    //Se crea un objeto XMLHttpRequest
    CancelarPeticionesAJAX(); // Tengo que cancelar todo lo pendiente antes porque surgían problemas con el temporizador de CargarPais
                              // que hacía que al llamar a crearAJAX cancelaba esta petición.
    objAjax = crearAjax();     
    objAjax.open("GET", pagina, true);  	
	
    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");        
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {
      	 CancelarPeticionesAJAX();
      	 //if (objAjax.responseText.length < 66)
         //{
         //   if (contenedor_mensaje != null)
         //   {
         //      contenedor_mensaje.innerHTML = objAjax.responseText;
         //      contenedor_mensaje.className = 'ceroresultadosvis';
         //   } else
         //   	 alert("Mensaje inesperado: " + objAjax.responseText);
            //document.formulario.txtLogin.focus();
         //} else
         //{
      	    //CancelarPeticionesAJAX();      	 
            //Se escribe el resultado en la capa contenedora             
            var scs = objAjax.responseText.extractScript();    //capturamos los scripts
            //alert("scs=" + scs);
       	    contenedor.innerHTML = objAjax.responseText; 
       	    objAjax = null;    	            
            scs.evalScript();       //ahora sí, comenzamos a interpretar todo               
         //}
      }
    }
    objAjax.send(null);    	 	
}

//Open window with progress bar.
function ProgressBar(id){
  var ProgressURL  
  
  ProgressURL = 'ay_progress.asp?UploadID=' + id;

  // Lo siguiente ya no lo hago aquí sino que lo hago en el script que carga el iFORM:
  //document.getElementById("upload_target").onload = uploadDone; //This function should be called when the iframe has compleated loading
			// That will happen when the file is completely uploaded and the server has returned the data we need.
  SubirImagen(id);
  
  //alert("ProgressURL=" + ProgressURL);
  
  var myWidth = 0, myHeight = 0;
  var myLeft = 0, myTop = 0;
  
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  //myLeft = document.body.clientLeft;
  //myTop = document.body.clientTop;
  //alert( 'Width=' + myWidth + '   Height=' + myHeight + '  myLeft=' + myLeft + '   myTop=' + myTop);  
  
  myTop = (myHeight/2) - 100;
  myLeft = (myWidth/2) - 175;
  var opciones;
  opciones = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,';
  opciones = opciones + 'width=350,height=200,' + 'top=' + myTop + ', left=' + myLeft;
  var v = window.open(ProgressURL,'_blank',opciones);  
   
  //OcultarBotonera(); 
    
  return true;
}

function SubirImagen(idupload)
{
    //var pagina = 'ay_subir_imagen.asp?UploadID=' + idupload;
    var miform;
    miform = document.getElementById("form_oculto"); // Utilizado para cancelar la subida de fotos desde la ventanita con la barra de progreso
    miform.campo_oculto.value = "false"; // Asigno valor inicial
    
    miform = document.getElementById("form_file_upload");
    //alert("miform.action.value = " + miform.action);
    miform.submit();
}



function uploadDone(idfoto) { //Function will be called when iframe is loaded
	//var ret = frames['upload_target'].document.getElementsByTagName("body")[0].innerHTML;
	//var data = eval("("+ret+")"); //Parse JSON // Read the below explanations before passing judgment on me
	
	//if(data.success) { //This part happens when the image gets uploaded.
	//	document.getElementById("image_details").innerHTML = "<img src='image_uploads/" + data.file_name + "' /><br />Size: " + data.size + " KB";
	//}
	//else if(data.failure) { //Upload failed - show user the reason.
	//	alert("Upload Failed: " + data.failure);
	//}	
	//alert("iFRAME cargado totalmete con idfoto=" + idfoto);	
	   
	if (idfoto > 0)
	{
           var pagina = "ay_documentar_imagen.asp?id=" + idfoto;
           var contenedor = document.getElementById("areatrabajo");    
		   
           //Se crea un objeto XMLHttpRequest
           objAjax = crearAjax();     
           objAjax.open("GET", pagina, true);  	
	
           //Send the proper header information along with the request
           objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");        
    
           objAjax.onreadystatechange = function() {
              if (objAjax.readyState == 4) {
              	 var scs = objAjax.responseText.extractScript();    //capturamos los scripts
       	         contenedor.innerHTML = objAjax.responseText;    
       	         objAjax = null;   	            
                 scs.evalScript();       //ahora sí, comenzamos a interpretar todo 
                 OcultarBotonera();
                 //_xx_ DocumentandoImg();      
              }
           }
           objAjax.send(null);    									 
        } else
	{
	   var contenedor = document.getElementById("mensajecancel");
	   contenedor.innerHTML = "La fotografía no ha podido ser incluida al Banco de Imágenes. \nPor favor, vuelva a intentarlo.";
	}
}

function UploadLote()
{     
    var pagina = 'ay_UploadLote-Progress.asp?';
    var contenedor = document.getElementById("areatrabajo");    
    var contenedor_mensaje = null;    

    CancelarPeticionesAJAX(); // Tengo que cancelar todo lo pendiente antes porque surgían problemas con el temporizador de CargarPais
                              // que hacía que al llamar a crearAJAX cancelaba esta petición.
    //Se crea un objeto XMLHttpRequest
    objAjax = crearAjax();     
    objAjax.open("GET", pagina, true);  	
	
    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");        
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {
      	 CancelarPeticionesAJAX();
      	 //if (objAjax.responseText.length < 66)
         //{
         //   if (contenedor_mensaje != null)
         //   {
         //      contenedor_mensaje.innerHTML = objAjax.responseText;
         //      contenedor_mensaje.className = 'ceroresultadosvis';
         //   } else
         //   	 alert("Mensaje inesperado: " + objAjax.responseText);
            //document.formulario.txtLogin.focus();
         //} else
         //{
      	    //CancelarPeticionesAJAX();      	 
            //Se escribe el resultado en la capa contenedora             
            var scs = objAjax.responseText.extractScript();    //capturamos los scripts
            //alert("scs=" + scs);
       	    contenedor.innerHTML = objAjax.responseText;    
       	    objAjax = null; 	            
            scs.evalScript();       //ahora sí, comenzamos a interpretar todo               
         //}
      }
    }
    objAjax.send(null);    	 	
}

//Open window with progress bar.
function ProgressBarLote(id){
  var ProgressURL
  ProgressURL = 'ay_progress.asp?UploadID=' + id;

  // Lo siguiente ya no lo hago aquí sino que lo hago en el script que carga el iFORM:
  //document.getElementById("upload_target").onload = uploadDone; //This function should be called when the iframe has compleated loading
			// That will happen when the file is completely uploaded and the server has returned the data we need.
  SubirImagen(id);
  
  //alert("ProgressURL=" + ProgressURL);
  
  var myWidth = 0, myHeight = 0;
  var myLeft = 0, myTop = 0;
  
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  //myLeft = document.body.clientLeft;
  //myTop = document.body.clientTop;
  //alert( 'Width=' + myWidth + '   Height=' + myHeight + '  myLeft=' + myLeft + '   myTop=' + myTop);  
  
  myTop = (myHeight/2) - 100;
  myLeft = (myWidth/2) - 175; //  175 = 350 / 2
  var opciones;
  opciones = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,';
  opciones = opciones + 'width=350,height=200,' + 'top=' + myTop + ', left=' + myLeft;
  var v = window.open(ProgressURL,'_blank',opciones);  
  
  //OcultarBotonera(); 
    
  return true;
}

function uploadLoteDone(idlote) { //Function will be called when iframe is loaded
	//var ret = frames['upload_target'].document.getElementsByTagName("body")[0].innerHTML;
	//var data = eval("("+ret+")"); //Parse JSON // Read the below explanations before passing judgment on me
	
	//if(data.success) { //This part happens when the image gets uploaded.
	//	document.getElementById("image_details").innerHTML = "<img src='image_uploads/" + data.file_name + "' /><br />Size: " + data.size + " KB";
	//}
	//else if(data.failure) { //Upload failed - show user the reason.
	//	alert("Upload Failed: " + data.failure);
	//}	
	//alert("iFRAME cargado totalmete con idfoto=" + idfoto);
	if (idlote > 0)
	{
           var pagina = "ay_documentar_lote.asp?id=" + idlote;
           var contenedor = document.getElementById("areatrabajo");    
	
	   //Se crea un objeto XMLHttpRequest
           objAjax = crearAjax();     
           objAjax.open("GET", pagina, true);  	
	
           //Send the proper header information along with the request
           objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");        
    
           objAjax.onreadystatechange = function() {
              if (objAjax.readyState == 4) {
              	 var scs = objAjax.responseText.extractScript();    //capturamos los scripts
       	         contenedor.innerHTML = objAjax.responseText;  
       	         objAjax = null;     	            
                 scs.evalScript();       //ahora sí, comenzamos a interpretar todo 
                 //_xx_ DocumentandoImg();   
                 OcultarBotonera();   
              }
           }
           objAjax.send(null);    									 
        } else
	{
	   var contenedor = document.getElementById("mensajecancel");
	   contenedor.innerHTML = "La fotografía no ha podido ser incluida al Banco de Imágenes. \nPor favor, vuelva a intentarlo.";
	}
}

//Función para actualizar el combo para las provincias y municipios
function ActualizarDatos (pagina, cmbDelimitador, cmbDelimitador2, divContenedora, clase)
{
    //Se obtiene la referencia del div
    //donde se mostrarán los resultados
    var contenedor = document.getElementById(divContenedora);
 
    //Se obtiene el valor seleccionado en el combo delimitador
    var valdelimitador = document.getElementById(cmbDelimitador);
 
    var x = valdelimitador.value;
    
    //Se contruye la url pasando, como parámetro, el valor seleccionado
    //var url_final = pagina+'?IdPais='+x;
    var params = 'IdPais='+x;
    
    if (cmbDelimitador2 != null)
    {
       var valdelimitador2 = document.getElementById(cmbDelimitador2);
       var y = valdelimitador2.value;
       params += '&IdProv=';
       params += y;
    }    
 
    //Se muestra una imagen de espera en la capa contenedora del combo delimitado       
    //contenedor.innerHTML = "Cargando...";
    contenedor.innerHTML = '<span id="aloja_paises" class="combo"> Cargando... </span>';
 	 
     
    //Se crea un objeto XMLHttpRequest
    objAjax = crearAjax();
          
    objAjax.open("POST", pagina, true);  

    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    objAjax.setRequestHeader("Content-length", params.length);
    objAjax.setRequestHeader("Connection", "close");
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {
       //Se escribe el resultado en la capa contenedora
       contenedor.innerHTML = objAjax.responseText;
       objAjax = null;
      }
    }
    objAjax.send(params);    
  
    // Eliminamos los municipios si es menester:
    if (cmbDelimitador2 == null)
    {
    	 var contenedorMunicipios = document.getElementById("municipios");
    	 //contenedorMunicipios.innerHTML = '<div id="municipios"> <SELECT name="municipio" class="caja">	<OPTION VALUE="" selected>&nbsp; &nbsp;</OPTION> </SELECT> </div>';
    	 if (clase == null)
    	    clase = "combodocumentar";
    	 contenedorMunicipios.innerHTML = '<SELECT name="municipio" id="municipio" class="' + clase + '" onfocus="limpiar_mensajecero(\'ceroresultados_avanzado\');">	<OPTION VALUE="" selected>- todos -</OPTION> </SELECT>';    	 
    }
}


function CargarPaises(id, todos)
{
    // Si hay una petición AJAX en curso, no hacemos nada. Esto se hace para solucionar un error producido cuando al cargarse
    // la ventana de Inicio (la pantalla con los buscadores, ay_buscador.asp), se lanzaba una temporización para que pasados 
    // unos segundos se cargasen los países en el combo. Pero si entremedias se pulsaba, por ejemplo, en una de las carpetas privadas,
    // como la temporización de los países acababa saltando, pues se abortaba la petición AJAX de la carpeta privada:
    if (objAjax != null)        
       return;
    // Cancelo una posible temporizacion en curso que volvería a pedir la lista de países:
    if (temporizacionPaises!= null)
    {
       clearTimeout(temporizacionPaises);
       temporizacionPaises = null;
    }
	 
    // El argumento "todos" valdrá "true" si queremos obtener todos los paises y valdrá "false" si sólo 
    // queremos obtener la lista de paises asociados a alguna foto.
    if (todos == null)
       todos = true;
    var pagina = "ay_paises.asp?todos=" + todos;
    var contenedor = document.getElementById(id);
    if (contenedor == null)
       return; // Salimos porque cuando es NULL se debe a que el usaurio a cambiado de página antes de que se carguen los países.
       
    contenedor.innerHTML = '<span id="aloja_paises" class="combo"> Cargando paises... </span>';
	  
    //Se crea un objeto XMLHttpRequest
    objAjaxPaises = crearAjax();
          
    objAjaxPaises.open("GET", pagina, true);  
 
    //Send the proper header information along with the request
    objAjaxPaises.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
        
    objAjaxPaises.onreadystatechange = function() {
      if (objAjaxPaises.readyState == 4) {
      	 //alert("ajax.status=" + objAjaxPaises.status);      	 
       	 contenedor.innerHTML = objAjaxPaises.responseText;
       	 objAjaxPaises = null;  
       	 temporizacionPaises = null;     	                     
      }       
    }
    objAjaxPaises.send(null);    	
}


function CargarEspecies(id, todas, clase)
{
    // El argumento "todas" valdrá "true" si queremos obtener todas las especies y valdrá "false" si sólo 
    // queremos obtener la lista de especies asociadas a alguna foto.
    //alert("CargarEspecies");
    if (todas == null)
       todas = true;
    var pagina = "ay_especies.asp?todas=" + todas + "&clase=" + clase;    
    var contenedor = document.getElementById(id);
    contenedor.innerHTML = '<span id="aloja_especies" class="combo2"> Cargando especies... </span>';
	  
    //Se crea un objeto XMLHttpRequest
    objAjaxEspecies = crearAjax();
          
    objAjaxEspecies.open("GET", pagina, true);  

    //Send the proper header information along with the request
    objAjaxEspecies.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 

    objAjaxEspecies.onreadystatechange = function() {
      if (objAjaxEspecies.readyState == 4) {
      	 //alert("ajax.status=" + objAjax.status);
      	 var scs = objAjaxEspecies.responseText.extractScript();    //capturamos los scripts
       	 contenedor.innerHTML = objAjaxEspecies.responseText;       	            
         scs.evalScript();       //ahora sí, comenzamos a interpretar todo
         //CargarTemas("temas");
         objAjaxEspecies = null;
         temporizacionEspecies = null;
      } 
      
    }
    objAjaxEspecies.send(null);    	
}


function CargarTemas(id, todos, clase)
{
    // El argumento "todos" valdrá "true" si queremos obtener todos los temas y valdrá "false" si sólo 
    // queremos obtener la lista de temas asociados a alguna foto.
    //alert("CargarTemas");
    if (todos == null)
       todos = true;
    var pagina = "ay_temas.asp?todos=" + todos + "&clase=" + clase;  
    var contenedor = document.getElementById(id);
    contenedor.innerHTML = '<span id="aloja_temas" class="combo"> Cargando temas... </span>';
 
    //Se crea un objeto XMLHttpRequest
    objAjaxTemas = crearAjax();
          
    objAjaxTemas.open("GET", pagina, true);  

    //Send the proper header information along with the request
    objAjaxTemas.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    
    objAjaxTemas.onreadystatechange = function() {
      if (objAjaxTemas.readyState == 4) {
      	 var scs = objAjaxTemas.responseText.extractScript();    //capturamos los scripts
       	 contenedor.innerHTML = objAjaxTemas.responseText;       	            
         scs.evalScript();       //ahora sí, comenzamos a interpretar todo
         //CargarEspecies("temas");
         objAjaxTemas = null;
         temporizacionTemas = null;
      }
    }
    objAjaxTemas.send(null);    	
}


//Función para actualizar los combos de valores EUROVOC NT2 y NT3:
function ActualizarEUROVOC (pagina, cmbDelimitador, divContenedora)
{
    //Se obtiene la referencia del div
    //donde se mostrarán los resultados
    var contenedor = document.getElementById(divContenedora);
 
    //Se obtiene el valor seleccionado en el combo delimitador
    var valdelimitador = document.getElementById(cmbDelimitador);
 
    var x = valdelimitador.value;
    
    //Se contruye la url pasando, como parámetro, el valor seleccionado    
    var params = 'NT='+x;    
 
    //Se muestra una imagen de espera en la capa contenedora del combo delimitado       
    //contenedor.innerHTML = "Cargando...";
    contenedor.innerHTML = '<span id="unspan" class="comboseurovoc"> Cargando valores... </span>';
     
    //Se crea un objeto XMLHttpRequest
    objAjax = crearAjax();
          
    objAjax.open("POST", pagina, true);  

    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    objAjax.setRequestHeader("Content-length", params.length);
    objAjax.setRequestHeader("Connection", "close");
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {
       //Se escribe el resultado en la capa contenedora
       contenedor.innerHTML = objAjax.responseText;
       objAjax = null;
      }
    }
    objAjax.send(params);    
  
    // Eliminamos los municipios si es menester:
    if (cmbDelimitador == "snt1")
    {
    	 var contenedorNT3 = document.getElementById("NT3");    	 
    	 contenedorNT3.innerHTML = '<SELECT name="snt3" id="snt3" class="comboseurovoc"> <OPTION VALUE="" selected>-</OPTION> </SELECT>';    	 
    }
}


function CargarNT1(id)
{    
    var pagina = "ay_nt1.asp?";
    var contenedor = document.getElementById(id);
    contenedor.innerHTML = '<span id="aloja_nt1" class="combo"> Cargando valores... </span>';
	      	  
    //Se crea un objeto XMLHttpRequest
    objAjax = crearAjax();
          
    objAjax.open("GET", pagina, true);  

    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {
      	 //alert("ajax.status=" + objAjax.status);      	 
       	 contenedor.innerHTML = objAjax.responseText; 
       	 objAjax = null;      	    	                     
      }       
    }
    objAjax.send(null);    	
}

function AsignarTema(esIdLote, id)
{
    var pagina = 'ay_asignar_tema.asp'; 
    var params;
    if (esIdLote)
       params = 'IdLote=' + id;
    else
       params = 'IdFoto=' + id;
    
    params += '&IdTema='
    
    var contenedor;

    if ((undefined == window.cbTemas) || cbTemas == null)
       return false; //params += encodeURIComponent("-1");
    else
    {
       if (isNaN(cbTemas.value))
          return false;
       else
          params += encodeURIComponent(cbTemas.value);
    }
   
    contenedor = document.getElementById("temasasignados");
        
    objAjax = crearAjax();     
    objAjax.open("POST", pagina, true);  	
    //alert("pagina=" + pagina);      
    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    
    objAjax.setRequestHeader("Content-length", params.length);
    objAjax.setRequestHeader("Connection", "close");
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {      	       	    
       	 contenedor.innerHTML = objAjax.responseText;  
       	 objAjax = null;   	                                            
      }
    }
    objAjax.send(params);    	  
  
}

function QuitarTema(esIdLote, id)
{
    var pagina = 'ay_quitar_tema.asp'; 
    var params;
    if (esIdLote)
       params = 'IdLote=' + id;
    else
       params = 'IdFoto=' + id;
    
    params += '&IdTema='
       
    var contenedor, idtema

    var entrada = document.getElementById("IdTema");
    
    if (entrada.selectedIndex == -1)
       return false;
    
    idtema = entrada.options[entrada.selectedIndex].value;       
    //alert("selectedIndex =" + entrada.selectedIndex + "   value=" +  entrada.options[entrada.selectedIndex].value + "  text=" + entrada.options[entrada.selectedIndex].text);

    params += encodeURIComponent(idtema);
   
    contenedor = document.getElementById("temasasignados");
        
    objAjax = crearAjax();     
    objAjax.open("POST", pagina, true);  	
    //alert("pagina=" + pagina);      
    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    
    objAjax.setRequestHeader("Content-length", params.length);
    objAjax.setRequestHeader("Connection", "close");
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {      	       	    
       	 contenedor.innerHTML = objAjax.responseText;     	                                   
         objAjax = null;
      }
    }
    objAjax.send(params);    	    
}

function AsignarEspecie(esIdLote, id)
{
    var pagina = 'ay_asignar_especie.asp';    
    var params;
    if (esIdLote)
       params = 'IdLote=' + id;
    else
       params = 'IdFoto=' + id;
    
    params += '&IdEspecie='
        
    var contenedor;

    if ((undefined == window.cbEspecies) || cbEspecies == null)
       return false; //params += encodeURIComponent("-1");
    else
    {
       if (isNaN(cbEspecies.value))
          return false;
       else
          params += encodeURIComponent(cbEspecies.value);
    }
   
    contenedor = document.getElementById("especiesasignadas");
        
    objAjax = crearAjax();     
    objAjax.open("POST", pagina, true);  	
    //alert("pagina=" + pagina);      
    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    
    objAjax.setRequestHeader("Content-length", params.length);
    objAjax.setRequestHeader("Connection", "close");
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {      	       	    
       	 contenedor.innerHTML = objAjax.responseText;     	                                   
         objAjax = null;
      }
    }
    objAjax.send(params);    	    
}

function QuitarEspecie(esIdLote, id)
{
    var pagina = 'ay_quitar_especie.asp'; 
    var params;
    if (esIdLote)
       params = 'IdLote=' + id;
    else
       params = 'IdFoto=' + id;
    
    params += '&IdEspecie='    
    
    var contenedor, idespecie

    var entrada = document.getElementById("IdEspecie");
    
    if (entrada.selectedIndex == -1)
       return false;
    
    idespecie = entrada.options[entrada.selectedIndex].value;       
    //alert("selectedIndex =" + entrada.selectedIndex + "   value=" +  entrada.options[entrada.selectedIndex].value + "  text=" + entrada.options[entrada.selectedIndex].text);

    params += encodeURIComponent(idespecie);
   
    contenedor = document.getElementById("especiesasignadas");
        
    objAjax = crearAjax();     
    objAjax.open("POST", pagina, true);  	
    //alert("pagina=" + pagina);      
    //Send the proper header information along with the request
    objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    
    objAjax.setRequestHeader("Content-length", params.length);
    objAjax.setRequestHeader("Connection", "close");
    
    objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {      	       	    
       	 contenedor.innerHTML = objAjax.responseText;     	                                   
         objAjax = null;
      }
    }
    objAjax.send(params);    	  
  
}

function ComprobarMaxCadena(elemento, mensaje)
{
  var texto = elemento.value;
  var posini, posfin;
  var error = false;
  var maxlongitud = 21;
  //alert("texto=" + texto);
  if (texto.length <= maxlongitud)
     return true;
  
  posini = 0;
  posfin = 0;
  while ((posfin = texto.indexOf(' ', posini)) != -1)
  {
     //alert("posfin - posini = " + (posfin - posini));
     if (posfin - posini > maxlongitud)
     {
        error = true;
        break;
     }
        
     posini = posfin + 1;	
  }   
  
  // Si la cadena larga estuviese al final, hay que detectarla también:
  if (posfin == -1 && (texto.length - posini > maxlongitud))
     error = true;
  
  if (error) 
  {
     	mensaje.innerHTML = "Ha introducido una cadena demasiado larga (sin espacios) en la descripción";
        mensaje.className = 'ceroresultadosvis';
        return false;
  }          
  
  return true;		
}


function AnularDocumentacion(esIdLote, id)
{
//alert("Falta implementar AnularDocumentacion() en fototeca.js");	
   var pagina = 'ay_anular.asp?';
   var params;
   if (esIdLote)
      params = 'IdLote=' + id;
   else
      params = 'IdFoto=' + id;   
   
   var contenedor = document.getElementById("areatrabajo"); 
   
   HabilitarBotonera(true, true);
      
   objAjax = crearAjax();     
   objAjax.open("POST", pagina, true);  	
         
   //Send the proper header information along with the request
   objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    
   objAjax.setRequestHeader("Content-length", params.length);
   objAjax.setRequestHeader("Connection", "close");
    
   objAjax.onreadystatechange = function() {
      if (objAjax.readyState == 4) {      	       	    
       	 //Se escribe el resultado en la capa contenedora             
         var scs = objAjax.responseText.extractScript();    //capturamos los scripts
         //alert("scs=" + scs);
       	 contenedor.innerHTML = objAjax.responseText;  
       	 objAjax = null;   	            
         scs.evalScript();       //ahora sí, comenzamos a interpretar todo   	 
         window.scrollTo(0,150);                                           
      }
   }
   objAjax.send(params); 
}


 

function FinalizarDocumentacion(esIdLote, id)
{
    var formu = document.getElementById("form_doc_img");
    var contenedor_mensaje = document.getElementById("ceroresultados_avanzado");
    
    if ((formu.fechatoma.value=="") || (formu.nombreautor.value=="") || (formu.apellidosautor.value=="") || (formu.toma.value=="") || (formu.descripcion.value==""))
    {
       //alert("Es obligatorio rellenar los siguientes campos \nen la documentación de la fotografía: \n\n * Fecha de toma\n * Nombre y apellidos del autor\n * Tipo de toma\n * Descripción");
       contenedor_mensaje.innerHTML = "Los campos fecha de toma, nombre y apellidos del autor, tipo de toma y descripción son obligatorios";
       contenedor_mensaje.className = 'ceroresultadosvis';
       return false;
    }
    else
    {
       // Comprobamos que no haya cadenas demasiado largas (sin espacios) en la descripción (que luego nos descuadrarían la visualización de resultados):
       if (ComprobarMaxCadena(formu.descripcion, contenedor_mensaje) == false)
          return false;       
       
       //formu.submit();  
       var pagina;
       if (esIdLote)
          pagina = "ay_grabardatos.asp?IdLote=" + id;    
       else
       	  pagina = "ay_grabardatos.asp?IdFoto=" + id;    
       	  
       var contenedor = document.getElementById("areatrabajo");
       var longitudFormulario = formu.elements.length;
       var cadenaFormulario = "";
       var sepCampos;
       
       contenedor_mensaje.innerHTML = "Guardando datos...";
       contenedor_mensaje.className = 'ceroresultadosvis';
       
       sepCampos = "";
       for (var i=0; i <= formu.elements.length-1;i++) {
           //_xx_ cadenaFormulario += sepCampos+formu.elements[i].name+'='+encodeURI(formu.elements[i].value);
           if (formu.elements[i].type == "checkbox")
              cadenaFormulario += sepCampos+formu.elements[i].name+'='+encodeURI(formu.elements[i].checked);
           else
              cadenaFormulario += sepCampos+formu.elements[i].name+'='+encodeURI(formu.elements[i].value);
           //   alert("name=" + formu.elements[i].name + "  type=" + formu.elements[i].type + "   checked=" + formu.elements[i].checked + "  value=" + formu.elements[i].value);
           //alert("cadenaFormulario=" +cadenaFormulario);
           sepCampos="&";
       }                   
              
       objAjax = crearAjax();     
       objAjax.open("POST", pagina, true);  	
       //alert("pagina=" + pagina);      
       //Send the proper header information along with the request
       objAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");   // peticion.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');  
       objAjax.setRequestHeader("Content-length", cadenaFormulario.length);
       objAjax.setRequestHeader("Connection", "close");
    
       objAjax.onreadystatechange = function() {
       	 if (objAjax.readyState == 4) {
       	  if (objAjax.status == 200)  
       	  {     	  
       	     if (objAjax.responseText.length < 66)
             {
                if (contenedor_mensaje != null)
                {
                   contenedor_mensaje.innerHTML = objAjax.responseText;
                   contenedor_mensaje.className = 'ceroresultadosvis';
                }
             } else     
             {	  	
             	   HabilitarBotonera(true, true);               	           	       	    
                   contenedor.innerHTML = objAjax.responseText;     	                                                            
                   window.scrollTo(0,150);
             }
          } else
          {
             if (contenedor_mensaje != null)
             {
                contenedor_mensaje.innerHTML = "Error " + objAjax.status + "  . Reintente";
                contenedor_mensaje.className = 'ceroresultadosvis';
             }
             alert("Error " + objAjax.status + ":  " + objAjax.statusText);
          }
          objAjax = null;
         }
       }
       
       objAjax.send(cadenaFormulario);    
       
       return true;
  }
}


