//---------------- MENSAJES DE ALERTA DE JAVASCRIPT -----------------
// Primero el IDIOMA y después el NÚMERO DE ALERTA

var aArrayAlertasCastellano =  new Array();
var aArrayAlertasIngles  =  new Array();

aArrayAlertasCastellano[1] = "Debe introducir al menos 3 caracteres para realizar la búsqueda.";
aArrayAlertasIngles[1] = "You must introduce at least 3 characters to make the search.";

aArrayAlertasCastellano[2] = " (Se abre en ventana nueva)";
aArrayAlertasIngles[2] = " (Open in a new window)";

aArrayAlertasCastellano[3] = "Una vez enviada la respuesta, no se podrá modificar.\n\n ¿Continuar?";
aArrayAlertasIngles[3] = "After sending, the reply can not be changed. \n \ n Continue?";

var aArrayAlertas = new Array();
aArrayAlertas[1] = aArrayAlertasCastellano;
aArrayAlertas[2] = aArrayAlertasIngles;

//-------------------- FUNCIÓN QUE SE CARGA EN EL ONLOAD DEL BODY ---------------------------
function inicio(iResolucion, iIdidioma){
	resolucion(iResolucion);
	imgAdjuntas(iIdidioma);
	externalLinks();
	cargarUtilidades();
	cargarCategorias();
}

// Función para obtener la resolución mediante la "carga" (llamada) de una página oculta
function resolucion(iResolucion){
	var xmlHttp
	if (iResolucion == 0) {
		ajax("/resolucion.asp","?resolucion="+screen.width+"*"+screen.height);
	}
}

//--------------------------------------------------------------
//Esta función modifica el alt de la imagenes que tiene imagen adjunta, advirtiendo que la amplicación se abrirá en ventana nueva
function imgAdjuntas(iIdidioma){
	 var imgs = document.getElementsByTagName("img");
	 for (var i=0; i<imgs.length; i++) {
		var img = imgs[i];
		var sClass = img.className
		if (sClass.indexOf("cursorAdjunto") != -1){

   		img.alt = img.alt + aArrayAlertas[iIdioma][2];
	  }
	}
}

//--------------------------------------------------------------
//Como el atributo target no esta permitido usamos esta función para poder abrir enlaces en ventanas nuevas
//en el enlace debemos añadir el atributo rel="external", esta funcion lo detectará y pondrá el target mediante javascript
function externalLinks(){
	if (!document.getElementsByTagName) return;
 	var anchors = document.getElementsByTagName("a");
 	for (var i=0; i<anchors.length; i++) {
   		var anchor = anchors[i];
   		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external"){
       		anchor.target = "_blank";
	   }
	}
}

//--------------------------------------------------------------
//Esta función se encarga de mostrar las utilidades que utilizan javascript (que viene ocultas mediante css por defecto)
//además de mostrar los botones les añade el evento onclick con la funcion correspondiente,
//Esto es debido a que en el front utilizamos un <a href=""> para poder asignar un accesskey, a parte de que sería obligatorio usar eventos duplicados
function cargarUtilidades(){

	var oEnlace;

	oServicioVolver = document.getElementById("atajoVolver");
	if(oServicioVolver) {
		oServicioVolver.style.display = "inline";
		oEnlace = oServicioVolver.getElementsByTagName("A");
		oEnlace[0].href="javascript:volver();"
	}
	
	oServicioVolver = document.getElementById("servicioImprimir");
	if(oServicioVolver) {
		oServicioVolver.style.display = "inline";
		oEnlace = oServicioVolver.getElementsByTagName("A");
		oEnlace[0].href="javascript:window.print();"
	}

	/*oReadSpeaker = document.getElementById("enlacereadspeaker");
	if(oReadSpeaker) {
		oReadSpeaker.style.display = "inline";
		oEnlace = oReadSpeaker.getElementsByTagName("A");
		oEnlace[0].href="javascript:abrirReadspeaker();"
	}
	
	oReadSpeaker2 = document.getElementById("ereadspeaker");
	if(oReadSpeaker2) {
		oReadSpeaker2.style.display = "inline";
		oEnlace = oReadSpeaker2.getElementsByTagName("A");
		oEnlace[0].href="javascript:abrirReadspeaker();"
	}*/

}
//--------------------------------------------------------------
// Función que se utiliza para mostrar las imágenes adjuntas que se insertan en los contenidos
function VerImagen(iIdImagen){

	var windowImagen;
	windowImagen = window.open("/popup/popupimagen.asp?idimagen=" + iIdImagen,"Imagen","width=100,height=100,top=10,left=10,scrollbars=yes,resizable=yes");

}
// Función que se utiliza para mostrar las imágenes adjuntas de la galería fotografica
function VerFoto(iIdImagen){

	var windowImagen;
	windowImagen = window.open("/popup/popupgaleria.asp?id=" + iIdImagen,"Imagen","width=100,height=100,top=10,left=10,scrollbars=yes,resizable=yes");

}

//--------------------------------------------------------------
// Comprueba que el campo textobusqueda del formulario que se pasa por parámetro, tenga al menos 3 caracteres
// Esto es muy importante si la búsqueda se realiza mediante index server.
function comprobarPatron(fBusqueda){

	if(fBusqueda.textobusqueda.value.length < 3){
		alert(aArrayAlertas[iIdioma][1])
		return false;
	}else{
		return true;
	}
}

//--------------------------------------------------------------
// Función que se llama en los onsubmit de los formularios.
// Se encarga de la validación AJAX
function validarFormulario(oFormulario){

	var sParametros, sTipo, sNombre, sValor, bOk, nombrefichero, oCapa;

	bOk = true;
	nombrefichero = oFormulario.nombrefichero.value;
	sParametros = "?";
	sCapa = "a_alerta";

	for(var i=0;i<oFormulario.elements.length;i++){

	 	sTipo = oFormulario.elements[i].type;

	 	if(sTipo=="text" || sTipo=="password" || sTipo=="checkbox" || sTipo=="textarea" || sTipo=="select-one" || sTipo=="radio") {

			if (sTipo != "checkbox" &&  sTipo != "radio" ){
				sNombre = oFormulario.elements[i].name;
				sValor  = escape(oFormulario.elements[i].value);
			}
			else {

				sNombre = oFormulario.elements[i].name;

				if(oFormulario.elements[i].checked){
					sValor  = escape(oFormulario.elements[i].value);
				}else {
					sValor = "";
				}

			}

			//Problemas con los radios (todos con el mismo nombre)
			if( sTipo != "radio" || sValor != "" ) {
				sParametros +=sNombre+"="+sValor;
				sParametros +="&";
			}

		}

		// Si existe el campo oculto IdForm , mostramos los mensajes en una capa específica
		if(sTipo=="hidden" && oFormulario.elements[i].name=="IdForm") {
			sCapa = "a_alerta_" + oFormulario.elements[i].value;
		}
	}

	sParametros += "nombrefichero=" + nombrefichero;

	ajax("/recursos/formularios/validar.asp",sParametros,sCapa,true,oFormulario);

	return false;
}

//---------------------------------------------------------------------
// Carga una página web mediante AJAX.
// Parámetros:
// - Url a cargar
// - Parámetros para la url
// - Capa para cargar el resultado (NO OBLIGATORIO)
// - Petición asincrona (true/false) (NO OBLIGATORIO, ASINCRONO POR DEFECTO) 
//		ATENCIÓN -- EN EL FIREFOX FUNCIONA DE FORMA ASINCRONA --
// - Objeto representando al formulario a validar (NO OBLIGATORIO)
//---------------------------------------------------------------------
function ajax(){
	
	var sFichero	= arguments[0];
	var sParametros	= arguments[1];
	var sDiv		= arguments[2];
	var bAsincrono	= arguments[3] ? arguments[3] : true;
	var oForm		= arguments[4];
	
	var peticion = false;
	if (window.XMLHttpRequest){
		peticion = new XMLHttpRequest();
	}else if (window.ActiveXObject) {
		peticion = new ActiveXObject("Microsoft.XMLHTTP");
	}

	//prompt('',fichero+parametros);

	if(peticion) {
	  	peticion.open("GET", sFichero+sParametros, bAsincrono);
	  	if (sDiv!=""){devolverResultado(peticion, sDiv, oForm);}
		peticion.send(null);
	}
}

//---------------------------------------------------------------------
// Devuelve el resultado de la petición AJAX.
// Parámetros:
// - Objeto httpRequest
// - Nombre de la capa para escribir los resultados
// - Objeto representado al formulario a validar (NO OBLIGATORIO)
//		Submita el formulario si no hay errores de validación
//---------------------------------------------------------------------
function devolverResultado(){

	var peticion	= arguments[0];
	var sDiv		= arguments[1];
	var oFormulario	= arguments[2];
	
	var obj = document.getElementById(sDiv);
	if(obj){
		peticion.onreadystatechange = function(){

			if (peticion.readyState == 4){
				
				// Submitar el formulario
				if (!peticion.responseText && oFormulario){
					//oFormulario.action = '../recursos/aplicaciones/buscadorGeneralAvanzado.asp';
					oFormulario.submit();
				}
				else {
					obj.innerHTML = peticion.responseText;
					
					if(oFormulario!="") {
						// Ocultar la capa de los errores de ASP
						if(document.getElementById("errorvalidacion") && obj.innerHTML=="") document.getElementById("errorvalidacion").style.display = "none";
		
						// Mostrar alertas 
						obj.style.display='block';
						location.hash = sDiv;
					}
				}
			}
		}
	}
}

//---------------------------------------------------------------------
// Función volver al contenido anterior.
// Se utiliza en el botón volver de los atajos.
//---------------------------------------------------------------------
function volver() {
 history.back(-1);
}

//---------------------------------------------------------------------
// Función para escribir un flash.
// Parámetros:
// - Ruta del flash
// - Ancho del flash
// - Alto del flash
// - Color de fondo (Sin la #)
// - Valor para el parámetro flashVars
// - Parámetros (separados por ;)
function escribirFlash(sRuta,sAncho,sAlto,sColorFondo,sFlashVars,sParametros) {

      if (sColorFondo == "") {
            sColorFondo = '000000';
      } 

      if(navigator.appName=="Microsoft Internet Explorer") {
            var sGenerado = '<object type="application/x-shockwave-flash" width="' + sAncho + '"  height="' + sAlto + '" >';
      } else {
            var sGenerado = '<object type="application/x-shockwave-flash" data="' + sRuta + '" width="' + sAncho + '"  height="' + sAlto + '" >';
      }

      sGenerado += '<param name="movie" value="' + sRuta + '" />';
	  sGenerado += '<param name="allowScriptAccess" value="sameDomain" />';
      sGenerado += '<param name="quality" value="high" />';
      sGenerado += '<param name="bgcolor" value="' + sColorFondo + '" />';
	  
	  if(sFlashVars) sGenerado += '<param name="flashVars" value="' + sFlashVars + '" />';
	  
      if (sParametros.indexOf(';')>-1) {
            var array_parametros = sParametros.split(';');
            for (var i=0; i<array_parametros.length-1; i++) {
                  sGenerado += '<param name="'+array_parametros[i].split("=")[0]+'" value="'+array_parametros[i].split("=")[1]+'" />';
            }
      }     

      sGenerado += '</object>';
	  
	  document.write(sGenerado);
}

//***** Cargar evento onClick para el combo de los paises *****
function cargarCategorias () {
		if( document.getElementById("idSubCategoria") ) {
		if( document.getElementById("idCategoria") ) {
			document.getElementById("idCategoria").onchange = function(event) { 
				// Cambio de categoría principal en la búsqueda de videos
				var idCategoria = document.getElementById("idCategoria").value;
				ajaxCombos("../../inc/aplicacionesPerso/cargaCategoriasCombos.asp","?idCategoria=" + idCategoria,"idSubCategoria");
			}
		}
		}
}

/*function abrirReadspeaker(){
	if(document.getElementById("readspeaker").style.display=="none"||document.getElementById("readspeaker").style.display==""){
		document.getElementById("readspeaker").style.display="block";
	}else{
		document.getElementById("readspeaker").style.display="none";
	}
}*/

var rutaMP3
function generarMP3(url){
	
	var fichero="/inc/aplicacionesperso/readspeaker/audio.asp?mp3="+url
	var peticion = false; 
	if (window.XMLHttpRequest){
		peticion = new XMLHttpRequest();
	}else if (window.ActiveXObject) {
		peticion = new ActiveXObject("Microsoft.XMLHTTP");	
	}
		
	if(peticion) {
		peticion.open("GET", fichero);
		
			var obj = document.getElementById("readspeaker");
			obj.style.display="block";
			var parent = obj.parentNode;
			peticion.onreadystatechange = function(){ 
			if (peticion.readyState == 4){
				obj.innerHTML = peticion.responseText; 
			} 
			} 
		
			peticion.send(null); 
	}

}

function abrirReadspeaker(url){

	var fichero="/inc/aplicacionesperso/readspeaker/generarRutaMp3.asp?url="+url.replace(/&/gi,"*");
	var peticion = false; 
	if (window.XMLHttpRequest){
		peticion = new XMLHttpRequest();
	}else if (window.ActiveXObject) {
		peticion = new ActiveXObject("Microsoft.XMLHTTP");	
	}
		
	if(peticion) {
		peticion.open("GET", fichero);
		var obj = document.getElementById("readspeaker");
		obj.style.display="block";
		obj.innerHTML="<img src='/img/es/iconos/ajax_loader.gif' />";
		peticion.onreadystatechange = function(){ 
		if (peticion.readyState == 4){
			rutaMP3 = peticion.responseText; 
			generarMP3(rutaMP3);
		} 
		} 
			
			peticion.send(null); 
	}

}

function addLoadEvent(func) {
    var oldonload = window.onload;

    if (typeof window.onload != 'function') {
        window.onload = func;

    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
           	func();
        }
    }
}

// Función para escribir un flash.
// Parámetros:
// - Ruta del flash
// - Ancho del flash
// - Alto del flash
// - Color de fondo (Sin la #)
// - Parámetros (separados por ;)
function escribeFlash(sRuta,sAncho,sAlto,sColorFondo,sFlashVars,sParametros) {

      if (sColorFondo == "") {
            sColorFondo = '000000';
      } 

      if(navigator.appName=="Microsoft Internet Explorer") {
            var sGenerado = '<object type="application/x-shockwave-flash" width="' + sAncho + '"  height="' + sAlto + '" >';
      } else {
            var sGenerado = '<object type="application/x-shockwave-flash" data="' + sRuta + '" width="' + sAncho + '"  height="' + sAlto + '" >';
      }

      sGenerado += '<param name="movie" value="' + sRuta + '" />';
	  sGenerado += '<param name="allowScriptAccess" value="sameDomain" />';
      sGenerado += '<param name="quality" value="high" />';
      sGenerado += '<param name="bgcolor" value="' + sColorFondo + '" />';
	  
	  if(sFlashVars) sGenerado += '<param name="flashVars" value="' + sFlashVars + '" />';
	  
      if (sParametros.indexOf(';')>-1) {
            var array_parametros = sParametros.split(';');
            for (var i=0; i<array_parametros.length-1; i++) {
                  sGenerado += '<param name="'+array_parametros[i].split("=")[0]+'" value="'+array_parametros[i].split("=")[1]+'" />';
            }
      }     

      sGenerado += '</object>';
	  
	  document.write(sGenerado);
}
