//---------------- 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] = "Imagen ##INICIAL## de ##FINAL##";
aArrayAlertasIngles[3] = "Image ##INICIAL## of ##FINAL##";

aArrayAlertasCastellano[4] = "Cerrar alerta";
aArrayAlertasIngles[4] = "Cerrar alerta";

var aArrayAlertas = new Array();
aArrayAlertas[1] = aArrayAlertasCastellano;
aArrayAlertas[2] = aArrayAlertasIngles;

//-------------------- FUNCIÓN QUE SE CARGA EN EL ONLOAD DEL BODY ---------------------------
function inicio(iIdidioma){
//	resolucion(iResolucion);
	imgAdjuntas(iIdidioma);
	externalLinks();
	cargarUtilidades();
}

// 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();"
	}
	
	oServicioImprimir = document.getElementById("servicioImprimir");
	if(oServicioImprimir){
		oServicioImprimir.style.display = "inline";
		oEnlace = oServicioImprimir.getElementsByTagName("A");
		oEnlace[0].href="javascript:Imprimir();"
	}

}
//--------------------------------------------------------------
// 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");

}

//--------------------------------------------------------------
// 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
// Modificación: Ahora se pasan también los hidden (Corsino - 02/06/2008)
function validarFormulario(oFormulario){

	var sParametros, sTipo, sNombre, sValor, bOk, nombrefichero, oCapa;

	bOk = true;
	nombrefichero = oFormulario.nombrefichero.value
	sParametros = ""
	oCapa = document.getElementById('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" || sTipo=="hidden") {

			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 +="&";
			}

		}
	}

//	sParametros += "nombrefichero=" + nombrefichero;

	ajax("/recursos/formularios/validar.asp",sParametros,"a_alerta",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) {
		if(!oForm){
	  		peticion.open("GET", sFichero+sParametros, bAsincrono);
	  	}else{
	  		peticion.open("POST", sFichero);
	  		peticion.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		}
	  	if (sDiv!=""){devolverResultado(peticion, sDiv, oForm);}
		if(!oForm){
			peticion.send(null);
		}else{
			peticion.send(sParametros); 
		}
	}
}

//---------------------------------------------------------------------
// 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.submit();
				else {
					
					if(sDiv == "a_alerta") {
						// Mensaje de alerta
						alerta(peticion.responseText);
					}
					else {
						// Funcionamiento normal
						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';
							if(oFormulario) location.hash = "a_alerta";
						}
					}
					
				}
			}
		}
	}
}

//---------------------------------------------------------------------
// Función volver al contenido anterior.
// Se utiliza en el botón volver de los atajos.
//---------------------------------------------------------------------
function volver() {
 history.back(-1);
}

function Imprimir() {
	window.print();
}

//---------------------------------------------------------------------
// 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);
}

function abrirExterno(fichero, caracteristicas){
	
	if (caracteristicas==""){
		caracteristicas = "width=500,height=400,top=50,left=100,scrollbars=yes,status=yes"
	}
	windowa=window.open(fichero,"externo",caracteristicas);
}

// Recargar los hoteles en función del destino / categoría seleccionados
function cambiaHotel(oElem) {
	
	var oForm = oElem.form;
	var sUrl = "?1=1";
	
	if(oForm.destino) sUrl += "&idDestino=" + oForm.destino.value;
	if(oForm.categoria) sUrl += "&idCategoria=" + oForm.categoria.value;
	
	ajax("/inc/aplicacionesPerso/hoteles/cargarCombo.asp",sUrl,"select_hotel");	
}

// Capa de las alertas
var oCapa, oFondo;

// Crea la capa de alertas
function alerta() {

	var sTexto	= arguments[0];
	var sAncho	= arguments[1] ? arguments[1] + "px" : "700px";

	if(oCapa)  {

		// Ocultar alertas anteriores
		borrarAlerta();
	}
	else {

		// Crear capas
		oCapa = document.createElement("div");
		oFondo = document.createElement("iframe");
		
		var objBody = document.getElementById("recurso");
	
		// Añadir capa con los errores de validación
		objBody.appendChild(oFondo);
		objBody.appendChild(oCapa);
	
	}
	
	oFondo.style.position = "absolute";
	oFondo.style.left = 0;
	oFondo.style.top = 0;
	oFondo.scrolling="no";
	oFondo.frameborder="0";
	oFondo.style.visibility = "hidden";
	
	oCapa.style.position = "absolute";
	oCapa.style.left = 0;
	oCapa.style.top = 0;
	oCapa.style.backgroundColor = "white";
	oCapa.style.border = "solid 2px #ccc";
	oCapa.style.width = sAncho;
	oCapa.style.visibility = "hidden";
	oCapa.id = "popup";
	oCapa.innerHTML = sTexto;
	
	// Icono cerrar
	var oIcono = document.createElement("a");
	
	oIcono.style.position = "absolute";
	oIcono.style.clear = "both";
	oIcono.style.right = "0px";
	oIcono.style.top = "0px";
	oIcono.href="javascript:void(null);"
	oIcono.onclick = function() {borrarAlerta();};
	oIcono.innerHTML = '<img src="/img/cerrar.gif" alt="' + aArrayAlertas[iIdioma][4] + '" />';
	
	oCapa.appendChild(oIcono);
	
	// Centrar la capa
	centrarCapa();
	
}

// Oculta la capa de alertas
function borrarAlerta() {

	oFondo.style.visibility = "hidden";
	oCapa.style.visibility = "hidden";
	
}

// Centrar una capa horizontal y verticalmente
function centrarCapa (){
    var correctorPercent = 1;//En caso de definir las dimensiones en porcentajes.

	var iAncho = document.documentElement.clientWidth;
	var iAlto = document.documentElement.clientHeight;

    if (iAncho > oCapa.offsetWidth - correctorPercent){
        oCapa.style.left = '50%';
        oCapa.style.marginLeft = (-1) * oCapa.offsetWidth / 2 + 'px';
    }
    if (iAlto > oCapa.offsetHeight - correctorPercent){
		oCapa.style.top = parseInt(document.documentElement.scrollTop + (iAlto/2) - (oCapa.offsetHeight/2),10) + "px";
//        oCapa.style.top = '50%';
//        oCapa.style.marginTop = (-1) * oCapa.offsetHeight / 2 + 'px';
    }
	
	oFondo.style.top = oCapa.style.top;
	oFondo.style.marginTop = oCapa.style.marginTop;
	oFondo.style.left = oCapa.style.left;
	oFondo.style.marginLeft = oCapa.style.marginLeft;
	oFondo.style.width = oCapa.style.width;
	oFondo.style.height = oCapa.offsetHeight;

	oFondo.style.visibility = "visible";
	oCapa.style.visibility = "visible";
	
}