var ie = document.all ? 1 : 0;			// ie = Internet Explorer
var ns = document.layers ? 1 : 0;		// ns = NetScape
//·································································································
function abre_generica(cual, nombre_pop, alto, ancho, donde_x, donde_y, ajustable, barras_de_scroll) {
// Abrir popup
	if (ie) {
		window.open(cual, nombre_pop, 'toolbar=no, location=no, directories=no, status, menubar=no, scrollbars='+barras_de_scroll+', resizable='+ajustable+', copyhistory=no, width='+ancho+', height='+alto+', top='+donde_y+', left='+donde_x+'');
	} else if (ns) {
		window.open(cual, nombre_pop,'left='+donde_x+',top='+donde_y+',width=740,height=500,location=no,toolbar=no,directories=no,menubar=no,resizable='+ajustable+',scrollbars=yes,status=no');		
	} else {
		window.open(cual, nombre_pop, 'left=0,top=0,width='+ancho+',height='+(alto+5)+',location=no,toolbar=no,directories=no,menubar=no,resizable='+ajustable+',scrollbars='+barras_de_scroll+',status=no');		
	}
}
//·································································································
function imprimir(){
// Función que redimensiona una ventana para imprimir
	self.resizeTo(600,400);
	self.print();
}
//·································································································
function busca_palabra(destino){
	if(document.getElementById("palabra_aux").value!=""){
		document.buscador1.action=document.buscador1.action+"&palabra="+escape(document.getElementById("palabra_aux").value);
	}
}
//·································································································
function busca_guia(){
	var destino;

	destino="";

	if(document.getElementById("id_comarca")){
		if((document.getElementById("id_comarca").value!=0)&&(document.getElementById("id_concello").value==0)){
			destino=destino+"&id_comarca="+document.getElementById("id_comarca").value;
		}
	}
	if(document.getElementById("id_concello")){
		if(document.getElementById("id_concello").value!=0){
			destino=destino+"&id_concello="+document.getElementById("id_concello").value;
		}
	}
	if(document.getElementById("id_menu_guia")){
		if(document.getElementById("id_menu_guia").value!=0){
			destino=destino+"&id_menu_guia="+document.getElementById("id_menu_guia").value;
		}
	}
	if(document.getElementById("id_categoria")){
		if(document.getElementById("id_categoria").value!=0){
			destino=destino+"&id_categoria="+document.getElementById("id_categoria").value;
		}
	}
	if(document.getElementById("palabra").value!=""){
		destino=destino+"&palabra="+escape(document.getElementById("palabra").value);
	}
	document.buscador2.action+=destino;
}
//·································································································
function recarga_bsq_guia(){
	if(document.frm_bsq_guia.palabra.value!=""){
		document.frm_bsq_guia.action+="&palabra="+document.frm_bsq_guia.palabra.value;
	}
	if(document.frm_bsq_guia.id_categoria.value!="0"){
		document.frm_bsq_guia.action+="&id_categoria="+document.frm_bsq_guia.id_categoria.value;
	}
}
//·································································································
function busca_municipios(){
	var destino;
	destino="";
	if((document.getElementById("id_comarca").value!=0)&&(document.getElementById("id_concello").value==0)){
		destino=destino+"&id_comarca="+document.getElementById("id_comarca").value;
	}
	if(document.getElementById("id_concello").value!=0){
		destino=destino+"&id_concello="+document.getElementById("id_concello").value;
	}
	if(document.getElementById("palabra").value!=""){
		destino=destino+"&palabra="+document.getElementById("palabra").value;
	}
	if(document.getElementById("contenido").value =="1"){
		destino=destino+"&contenido="+document.getElementById("contenido").value;
	}
	document.frm_bsq_mnc.action=document.frm_bsq_mnc.action+destino;
}


// ·······························································································
function chekeaBsqAgenda(idioma){
	var fechaCorrecta;
	
	var fecha_inicial = document.frm_buscador_agenda.fecha_inicial.value;
	var fecha_final = document.frm_buscador_agenda.fecha_final.value;
	
	fechaCorrecta = es_fecha(fecha_inicial, idioma);
	
    if (fechaCorrecta != "true"){
       alert(fechaCorrecta);
	   return false;
    }else{
		fechaCorrecta = es_fecha(fecha_final, idioma);
        if (fechaCorrecta != "true"){
           alert(fechaCorrecta);
		   return false;
        }else{
			return true;
		}
	}
}


//·································································································
function bloquea_combos(pulsado){
	if(pulsado=="2"){
		document.getElementById("id_comarca").selectedIndex=0;
		document.getElementById("id_concello").selectedIndex=0;
		document.getElementById("id_comarca").disabled=true;
		document.getElementById("id_concello").disabled=true;
	}else{
		document.getElementById("id_comarca").disabled=false;
		document.getElementById("id_concello").disabled=false;
	}
}

//·································································································

function cadena_busqueda(comarca, concello, menu_guia, categoria){
/* Esta función muestra las carácterísticas de búsqueda que has realizado por combos. Mostrará una información del
   tipo:  O Baixo Miño · A Guarda · Imágenes     (Siempre que seleccionásemos esas opciones en combos) */
	var indice, texto;
	
	texto="";
	if(comarca!=0){
		indice=document.getElementById("id_comarca").selectedIndex;
		texto=document.getElementById("id_comarca").options[indice].text;
	}
	if(concello!=0){
		indice=document.getElementById("id_concello").selectedIndex;
		if(texto!="") texto=texto+" · ";
		texto=texto+document.getElementById("id_concello").options[indice].text;
	}
	if(menu_guia!=0){
		indice=document.getElementById("id_menu_guia").selectedIndex;
		if(texto!="") texto=texto+" · ";
		texto=texto+document.getElementById("id_menu_guia").options[indice].text;
	}
	if(categoria!=""){
		indice=document.getElementById("id_categoria").selectedIndex;
		if(texto!="") texto=texto+" · ";
		texto=texto+document.getElementById("id_categoria").options[indice].text;
	}
	if(document.getElementById("palabra").value!=""){
		if(texto!="") texto=texto+" · ";
		texto=texto+document.getElementById("palabra").value;
	}

	document.getElementById("cadena_busqueda").innerHTML=texto;
}

//··················································································
//						Funciones para Gastronomía.
//··················································································

function envia_frm_gst(mensaje){
// Para Gastronomía: Envía el formulario con la búsqueda de los campos seleccionados.
	var aux, platos;
	aux=false;
	if(document.frm_bsq_gst.palabra.value!=""){
		document.frm_bsq_gst.action+="&palabra="+document.frm_bsq_gst.palabra.value;
	}
	platos="";			
	for(i=0;i<document.frm_bsq_gst.elements.length;i++){
		if(document.frm_bsq_gst.elements[i].name.substring(0,6)=="platos"){
			if(document.frm_bsq_gst.elements[i].checked==true){
				platos=document.frm_bsq_gst.elements[i].value+","+platos;
				aux=true;
			}
		}
	}
	if(aux==true){
		platos=platos.substring(0,platos.length-1);      // Eliminamos la ,
		document.frm_bsq_gst.action+="&platos="+platos;
	}else{
		alert(mensaje);
	}
	return aux;
}

//....................................................................................
// Selecciona todos los ckeckbox de un formulario
function sel_chk_frm(obj){
	for(i=0;i<obj.elements.length;i++){
		if(obj.elements[i].name.substring(0,6)=="platos"){
			obj.elements[i].checked=obj.chkSel.checked;
		}
	}
}

//·································································································

/* Tool Tip **************************************************************************************/

if(ns){doc = "document."; sty = ""}
if(ie){doc = "document.all."; sty = ".style"}

var initialize = 0;
var Ex, Ey, topColor, subColor, ContentInfo;

if (ie) {
	Ex = "event.x";
	Ey = "event.y";
	topColor = "#21D220";
	subColor = "#FFFFFF";
}
if (ns) {
	Ex = "e.pageX";
	Ey = "e.pageY";
	window.captureEvents(Event.MOUSEMOVE);
	window.onmousemove=overhere;
	topColor = "#21D220";
	subColor = "#FFFFFF";
}

function MoveToolTip (layerName, FromTop, FromLeft, e){
	if(ie){eval(doc + layerName + sty + ".top = "  + (eval(FromTop) + document.body.scrollTop + 10))}
	if(ns){eval(doc + layerName + sty + ".top = "  +  eval(FromTop))}
	eval(doc + layerName + sty + ".left = " + (eval(FromLeft) + 15));
}
function ReplaceContent (layerName) {
	if(ie){document.all[layerName].innerHTML = ContentInfo}
	if(ns){
		with(document.layers[layerName].document) {
			open(); 
			write(ContentInfo); 
			close(); 
		}
	}
}
function Activate(){initialize=1;}
function deActivate(){initialize=0;}
function overhere(e){
	if(initialize){
		tamX=document.getElementById("ToolTip").offsetWidth; 		// ancho del contenido
		tamY=document.getElementById("ToolTip").offsetHeight;		// alto del contenido
		MoveToolTip("ToolTip", eval(Ey), 740, e);
		eval(doc + "ToolTip" + sty + ".visibility = 'visible'");
	}else{
		MoveToolTip("ToolTip", 0, 0);
		eval(doc + "ToolTip" + sty + ".visibility = 'hidden'");
	}
}
function EnterContent(layerName, TTitle, TContent){
	ContentInfo = '<table class="tbl0 brd1" width="230"><tr><td class="pad1" align="right"><img alt="" src="img/btn_cerrar_info.gif" class="mano" onclick="oculta();" width="10" height="10" border="0" align=""></td></tr><tr><td class="padR2 padL2 padB2">'+TTitle+'<br>'+TContent+'</td></tr></table>';
	ReplaceContent(layerName);
}

function oculta(tipo){
	document.getElementById("ToolTip").style.visibility="hidden";
}
/* Fin de Tool Tip *******************************************************************************/
//·································································································
function recarga(destino){
//	window.location.href='index.php'+destino+'&mes='+document.frm_calendario.mes.value+'&ano='+document.frm_calendario.ano.value;
	mes=document.frm_calendario.mes.value;
	ano=document.frm_calendario.ano.value;
	ultimo_dia=30;	
	window.location.href='index.php'+destino+'&fecha_inicial=01/'+mes+'/'+ano+'&fecha_final='+ultimo_dia+'/'+mes+'/'+ano;
}
//·································································································
function recarga_buscador(destino){

	if(document.bnn_buscador.palabra.value!=""){
		destino+="&palabra="+document.bnn_buscador.palabra.value;
	}

	if(document.bnn_buscador.id_comarca){
		if(document.bnn_buscador.id_comarca.value!="0"){
			destino+="&id_comarca="+document.bnn_buscador.id_comarca.value;
		}
	}

	if(document.getElementById("id_concello")){
		if(document.getElementById("id_concello").value!="0"){
			destino+="&id_concello="+document.getElementById("id_concello").value;
		}
	}

	if(document.bnn_buscador.id_categoria){
		if(document.bnn_buscador.id_categoria.value!="0" && document.bnn_buscador.id_categoria.value!=""){
			destino+="&id_categoria="+document.bnn_buscador.id_categoria.value;
		}
	}
	
	document.bnn_buscador.action="index.php"+destino;

	document.bnn_buscador.submit();
}
//·································································································
/* escribe lo que hay seleccionado en un combo */
function txt_categoria(){
	if(document.buscador2.id_categoria){
		if(document.buscador2.id_categoria.value!=0){
			indice=document.buscador2.id_categoria.selectedIndex;
			document.write(" | "+document.buscador2.id_categoria.options[indice].text);
		}
	}
}
//·································································································
function chekea(cual){
/* función utilizada para la aplicación de mensajes c_visitas.php */
	var i, campo, valor, seguir;
	
	seguir=true;
	for (i=0; i<cual.elements.length; i++) {
		campo=cual.elements[i].name.split("|");
		valor=cual.elements[i].value;
		if(campo[0]=="chk") {
			switch (campo[1]) {
			case "str":     // Comprueba campo nombre (texto)
				if (campo[2]=="true" && valor=="" && seguir==true){
					alert("El campo '"+campo[3]+"' no puede estar vacio");
					cual.elements[i].focus();
					seguir=false;
				}
				break;
			case "date":
				if (((campo[2]=="false" && valor!="" && esfecha(valor)!="true") || (campo[2]=="true" && (valor=="" || esfecha(valor)!="true")))&& seguir==true) {
					alert("El campo '"+campo[3]+"' debe ser de tipo fecha: DD/MM/AAAA");
					cual.elements[i].focus();
					seguir=false;
				}
				break;

			case "eml":     // Comprueba email.
				if (campo[2]=="true" && valor=="" && seguir==true){
					alert("El campo '"+campo[3]+"' no puede estar vacio");
					cual.elements[i].focus();
					seguir=false;
				}
				if(((valor.indexOf("@")==-1 && valor!="") || (valor.indexOf(".")==-1 && valor!="") || (campo[2]=="true" && valor=="")) && seguir==true){
					alert("El campo '"+campo[3]+"' no es correcto");
					cual.elements[i].focus();
					seguir=false;
				}
				break;
			case "int":
				if(((isNaN(valor)==true && valor!="") || (campo[2]=="true" && valor=="")) && seguir==true){
					alert("El campo '"+campo[3]+"' no puede estar vacio y debe ser un número");
					seguir=false;
				}
				break;
			}
		}
	}
	return seguir;
}



function crea_fecha_normalizada(fecha) {
	var fecha_split;	
	var tdia, tmes, tano;
	fecha_split = fecha.split('/');
	tdia = parseInt(fecha_split[0],10);
	tmes = parseInt(fecha_split[1],10);
	tano = parseInt(fecha_split[2],10);
	return date = new Date(tano,tmes-1,tdia);
}

function es_fecha(dato,idioma) {
	var fecha_split;
	var i;
	var aux;    
    
    
    /* la variable idioma, tomada como un entero, se interpreta del siguinete modo:
         1 = español;
         2 = galego;
         3 = english;
     */
    
	aux="true";
    
    if (dato == "")
        return aux;
    
	fecha_split = dato.split('/');  
        
    var mensajes_espanhol = new Array("Fechas no válidas: ",
                                  "Deben ser DD/MM/AAAA",
                                  "No existe la fecha 0",
                                  "El año debe tener 4 dígitos: AAAA",                              
                                  "El día no es correcto",
                                  "El mes no es correcto",
                                  "El año no es correcto");
    var mensajes_galego = new Array("Datas non válidas: ",
                                  "Tén que ser DD/MM/AAAA",
                                  "Non existe a data 0",
                                  "O ano tén que ter 4 díxitos: AAAA",                              
                                  "O día non é correcto",
                                  "O mes non é correcto",
                                  "O ano non é correcto");
     var mensajes_english = new Array("Dates not valid: ",
                                  "It must be DD/MM/YYYY",
                                  "0 date does not exist",
                                  "The year must have 4 digits: AAAA",                              
                                  "Wrong day",
                                  "Wrong month",
                                  "Wrong year");
    var mensajes = new Array(3);
    mensajes[0] = mensajes_espanhol;
    mensajes[1] = mensajes_galego;
    mensajes[2] = mensajes_english;
    

      
	// Comprobamos que sean 3 elementos
	if(fecha_split.length != 3)
		//aux="Debe tener DD/MM/AAAA";
        aux = mensajes[idioma - 1][0] + mensajes[idioma - 1][1];
    else
    {
		// Comprobamos que no sean ceros
		for (i = 0; i < 3; i++)
    		if (parseInt(fecha_split[i],10) == 0) 
            {
                //aux="No existe la fecha: 0";
                aux = mensajes[idioma - 1][0] + mensajes[idioma - 1][2];
                return(aux);
            }                
		// Comprobamos que el AÑO tenga 4 dígitos
		if(fecha_split[2].length != 4) 
        {
            //aux="El año debe tener 4 dígitos: AAAA";
            aux = mensajes[idioma - 1][0] + mensajes[idioma - 1][3];
            return aux;
        }            
		// Comprobamos que sea de la forma dia/mes/año: 28/02/1997
    	var tdia, tmes, tano;
    	tdia = parseInt(fecha_split[0],10);
    	tmes = parseInt(fecha_split[1],10);
    	tano = parseInt(fecha_split[2],10);       
		var f = crea_fecha_normalizada(dato);
		if(f.getDate() != tdia)         
            //aux="El día no es correcto";
            aux = mensajes[idioma - 1][0] + mensajes[idioma - 1][4];
        else if(f.getMonth() != (tmes - 1)) 
            //aux="El mes no es correcto";
            aux = mensajes[idioma - 1][0] + mensajes[idioma - 1][5];
		else if(f.getFullYear() != tano) 
            //aux="El año no es correcto";
            aux = mensajes[idioma - 1][0] + mensajes[idioma - 1][6];
	}
	return aux;
    
    
}


// CREA un objeto para AJAX según disponibilidad del navegador
// -------------------------------------------------------------------------------------------
function GetXmlHttpObject() {
	var objXMLHttp = null;
	if (window.XMLHttpRequest) {
		objXMLHttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return objXMLHttp;
}
//
// -------------------------------------------------------------------------------------------
var devuelveAjax;
//Recarga un combo con AJAX
function recargaContenidoAjax(ruta, idioma, contenido, contenedor) {
	var devolver;
	devolver = "";
	var xmlHttp = GetXmlHttpObject();
	if (xmlHttp==null) {
		alert ("Browser does not support HTTP Request");
		//return;
	}
	xmlHttp.onreadystatechange = function(){
			if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
				if (xmlHttp.responseText == -1000){ // id incorrecto
					devolver = "";
				}else{	// id correcto
					devolver = xmlHttp.responseText;
				}
				devuelveAjax =  devolver;
				document.getElementById(contenedor).innerHTML = devolver;
			}

		};
		xmlHttp.open("GET", "recargaContenidoAjax.php?id_idioma="+ idioma +"&contenido="+ contenido+"&rutaVolver="+ruta , true);
		xmlHttp.send(null);
}

// MAXIMIZA y MINIZA capas
// ** necesitamos incluir el fichero jquery.js
// -----------------------------------------------------------------------------------------------
function muestra_oculta_capa(capa){
	if(document.getElementById(capa)){
		$("#"+ capa).slideToggle();
	}
	if(document.getElementById("ico_"+ capa)){
		if(document.getElementById("ico_"+ capa).innerHTML == "+"){
			document.getElementById("ico_"+ capa).innerHTML = "-";
		}else{
			document.getElementById("ico_"+ capa).innerHTML = "+";
		}
	}
}