//Funciones del mapa del buscador de cercanía
var mapa;
var geoXmlLugaresInteres;
var geoXmlLineasMetro;
var iconoPDI;
var iconoRojo;
var iconoAzul;
var iconoVerde;
var iconoAmarillo;
var iconoPurple;
var iconoNaranja;
var iconoSkyBlue;
var iconoMS;
var vectorHoteles;
var vectorPDIs;
var elementosXPagina = 10;
var parametrosBusqueda = "";

function loadMapaGuiaMadrid() {

    if (GBrowserIsCompatible()) {

        mapa = new GMap2(document.getElementById("map"));

        mapa.enableScrollWheelZoom();
        mapa.setMapType(G_NORMAL_MAP);
        mapa.addControl(new GLargeMapControl());
        mapa.addControl(new GHierarchicalMapTypeControl());
        mapa.addMapType(G_PHYSICAL_MAP);
        mapa.addMapType(G_SATELLITE_3D_MAP);

        mapa.enableContinuousZoom();
        mapa.enableScrollWheelZoom();

        mapa.setCenter(new GLatLng(41.652425, -0.881267), 7);

        cargarPuntosGuia(true);

    }
}

function loadMapaBuscadorInteractivo() {

    addMapper();

    if (GBrowserIsCompatible()) {

        mapa = new GMap2(document.getElementById("mapaPuntosInteres"));
        mapa.addControl(new GSmallMapControl());

        mapa.enableScrollWheelZoom();
        mapa.setMapType(G_PHYSICAL_MAP);

        mapa.setCenter(new GLatLng(41.651367, -0.883026), 12);

        cargarPDIS(true);

    }
}

function cargarPDIS(accion) {

    iconoPDI = new GIcon();
    iconoPDI.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
    iconoPDI.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    iconoPDI.iconSize = new GSize(12, 20);
    iconoPDI.shadowSize = new GSize(22, 20);
    iconoPDI.iconAnchor = new GPoint(6, 20);
    iconoPDI.infoWindowAnchor = new GPoint(5, 1);


    GDownloadUrl("devolverPDI.aspx?idArea=10", function (doc) {

        var xmlDoc = GXml.parse(doc);
        var pdi = xmlDoc.documentElement.getElementsByTagName("REGISTRO");

        vectorPDIs = new Array();

        for (var i = 0; i < pdi.length; i++) {
            incluirPDI(pdi[i], accion);
        }
    });
}

function incluirPDI(nodoPDI, accion) {

    var lat = parseFloat(nodoPDI.getAttribute("LAT"));
    var lng = parseFloat(nodoPDI.getAttribute("LNG"));
    var nombre = nodoPDI.getAttribute("NOMBRE");

    var punto = new GMarker(new GLatLng(lat, lng), iconoPDI);
    var tooltip = new Tooltip(punto, nombre, -50);
    punto.tooltip = tooltip;

    if (accion) {
        GEvent.addListener(punto, "click", function () { window.location = 'mapaHoteles.aspx?PASO1_GEOLATITUD=' + lat + '&PASO1_GEOLONGITUD=' + lng + '&PASO1_GEODISTANCIA=2' });
    }
    GEvent.addListener(punto, "mouseover", function () { this.tooltip.show(); });
    GEvent.addListener(punto, "mouseout", function () { this.tooltip.hide(); });

    mapa.addOverlay(punto);
    mapa.addOverlay(tooltip);

    vectorPDIs[vectorPDIs.length] = punto;

}

function incluirPuntoGuia(nodoPDI, accion) {

    var lat = parseFloat(nodoPDI.getAttribute("LAT"));
    var lng = parseFloat(nodoPDI.getAttribute("LNG"));
    var nombre = nodoPDI.getAttribute("NOMBRE");
    var codigo = nodoPDI.getAttribute("CODIGO");
    var texto = nodoPDI.getAttribute("TEXTO");
    var direccion = nodoPDI.getAttribute("DIRECCION");
    var fecha = nodoPDI.getAttribute("FECHA");
    var categoria = nodoPDI.getAttribute("CATEGORIA");
    var archivo = nodoPDI.getAttribute("ARCHIVO");

    if (archivo == 0) {
        archivo = archivoImagenDefecto;
    }

    var punto;
    var fechaF;

    switch (fecha.substring(3, 5)) {
        case '01': fechaF = fecha.substring(0, 2) + ' de Enero'; break;
        case '02': fechaF = fecha.substring(0, 2) + ' de Febrero'; break;
        case '03': fechaF = fecha.substring(0, 2) + ' de Marzo'; break;
        case '04': fechaF = fecha.substring(0, 2) + ' de Abril'; break;
        case '05': fechaF = fecha.substring(0, 2) + ' de Mayo'; break;
        case '06': fechaF = fecha.substring(0, 2) + ' de Junio'; break;
        case '07': fechaF = fecha.substring(0, 2) + ' de Julio'; break;
        case '08': fechaF = fecha.substring(0, 2) + ' de Agosto'; break;
        case '09': fechaF = fecha.substring(0, 2) + ' de Septiembre'; break;
        case '10': fechaF = fecha.substring(0, 2) + ' de Octubre'; break;
        case '11': fechaF = fecha.substring(0, 2) + ' de Noviembre'; break;
        case '12': fechaF = fecha.substring(0, 2) + ' de Diciembre'; break;
    }

    if (categoria == 'Eventos') {
        punto = new GMarker(new GLatLng(lat, lng), iconoRojo);
        fechaF = fecha;
    } else {
        if (categoria == 'Ferias y Congresos') {
            punto = new GMarker(new GLatLng(lat, lng), iconoAzul);
            fechaF = fecha;
        } else {
            if (categoria == 'Fiestas y Tradiciones') {
                punto = new GMarker(new GLatLng(lat, lng), iconoVerde);
            } else {
                if (categoria == 'De Compras') {
                    punto = new GMarker(new GLatLng(lat, lng), iconoAmarillo);
                    fechaF = "";
                } else {
                    if (categoria == 'Museos') {
                        punto = new GMarker(new GLatLng(lat, lng), iconoPurple);
                        fechaF = "";
                    } else {
                        if (categoria == 'Conciertos') {
                            punto = new GMarker(new GLatLng(lat, lng), iconoNaranja);
                            fechaF = "";
                        } else {
                            punto = new GMarker(new GLatLng(lat, lng), iconoSkyBlue);
                            fechaF = "";

                        }
                    }
                }
            }
        }
    }

    var tooltip = new Tooltip(punto, nombre, -50);
    punto.tooltip = tooltip;

    var tabs = [
			new GInfoWindowTab("General", "<div class=\"tabGuia\" ><table><tr><td class=\"imagen\" valign=\"top\"><img src=\"image.aspx?FIL_ID=" + archivo + "&tImg=D&iW=71&iH=73\" class=\"miniaturaHotel\" /><br/><a class=\"botonReservar1\" href=\"javascript:mapa.setCenter(new GLatLng(" + lat + "," + lng + "), 17);\">Acercar</a><a class=\"botonReservar2\" style=\"margin-top: 5px\" href=\"mapaHoteles.aspx?PASO1_GEOLATITUD=" + lat + "&PASO1_GEOLONGITUD=" + lng + "&PASO1_GEODISTANCIA=2\">Buscar hotel cercano</a></td><td><h5>" + nombre + "</h5><i>" + fechaF + "</i><br/><br/>Lugar: <b>" + direccion + "</b><br/><br/></td></tr></table></div>"),
			new GInfoWindowTab("Detalles", "<div class=\"tabGuia\">" + texto + "</div>")
			];

    GEvent.addListener(punto, "click", function () { this.tooltip.hide(); punto.openInfoWindowTabsHtml(tabs); });
    GEvent.addListener(punto, "mouseover", function () { this.tooltip.show(); });
    GEvent.addListener(punto, "mouseout", function () { this.tooltip.hide(); });

    mapa.addOverlay(punto);
    mapa.addOverlay(tooltip);

    vectorPDIs[codigo] = punto;

}

function cargarPuntosGuia(accion) {

    iconoRojo = new GIcon();
    iconoRojo.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
    iconoRojo.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    iconoRojo.iconSize = new GSize(12, 20);
    iconoRojo.shadowSize = new GSize(22, 20);
    iconoRojo.iconAnchor = new GPoint(6, 20);
    iconoRojo.infoWindowAnchor = new GPoint(5, 1);

    iconoAzul = new GIcon();
    iconoAzul.image = "http://labs.google.com/ridefinder/images/mm_20_blue.png";
    iconoAzul.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    iconoAzul.iconSize = new GSize(12, 20);
    iconoAzul.shadowSize = new GSize(22, 20);
    iconoAzul.iconAnchor = new GPoint(6, 20);
    iconoAzul.infoWindowAnchor = new GPoint(5, 1);

    iconoVerde = new GIcon();
    iconoVerde.image = "http://labs.google.com/ridefinder/images/mm_20_green.png";
    iconoVerde.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    iconoVerde.iconSize = new GSize(12, 20);
    iconoVerde.shadowSize = new GSize(22, 20);
    iconoVerde.iconAnchor = new GPoint(6, 20);
    iconoVerde.infoWindowAnchor = new GPoint(5, 1);

    iconoAmarillo = new GIcon();
    iconoAmarillo.image = "http://labs.google.com/ridefinder/images/mm_20_yellow.png";
    iconoAmarillo.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    iconoAmarillo.iconSize = new GSize(12, 20);
    iconoAmarillo.shadowSize = new GSize(22, 20);
    iconoAmarillo.iconAnchor = new GPoint(6, 20);
    iconoAmarillo.infoWindowAnchor = new GPoint(5, 1);

    iconoPurple = new GIcon();
    iconoPurple.image = "http://labs.google.com/ridefinder/images/mm_20_purple.png";
    iconoPurple.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    iconoPurple.iconSize = new GSize(12, 20);
    iconoPurple.shadowSize = new GSize(22, 20);
    iconoPurple.iconAnchor = new GPoint(6, 20);
    iconoPurple.infoWindowAnchor = new GPoint(5, 1);

    iconoNaranja = new GIcon();
    iconoNaranja.image = "http://labs.google.com/ridefinder/images/mm_20_orange.png";
    iconoNaranja.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    iconoNaranja.iconSize = new GSize(12, 20);
    iconoNaranja.shadowSize = new GSize(22, 20);
    iconoNaranja.iconAnchor = new GPoint(6, 20);
    iconoNaranja.infoWindowAnchor = new GPoint(5, 1);

    iconoSkyBlue = new GIcon();
    iconoSkyBlue.image = "http://zaragozahoteles.desarrollando.net/images/mm_20_BlueSky.png";
    iconoSkyBlue.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    iconoSkyBlue.iconSize = new GSize(12, 20);
    iconoSkyBlue.shadowSize = new GSize(22, 20);
    iconoSkyBlue.iconAnchor = new GPoint(6, 20);
    iconoSkyBlue.infoWindowAnchor = new GPoint(5, 1);

    GDownloadUrl("devolverPuntosGuia.aspx", function (doc) {
        var xmlDoc = GXml.parse(doc);
        var pdi = xmlDoc.documentElement.getElementsByTagName("REGISTRO");

        vectorPDIs = new Array();

        for (var i = 0; i < pdi.length; i++) {
            incluirPuntoGuia(pdi[i], accion);
        }
    });
}

function inicializarMapa() {

    //Define los iconos y el tipo de mapa de arranque

    iconoMS = new GIcon();
    iconoMS.image = "http://zaragozahoteles.desarrollando.net/images/iconoZH.gif";
    iconoMS.shadow = "http://zaragozahoteles.desarrollando.net/images/iconoMSShadow.png";
    iconoMS.iconSize = new GSize(23.0, 27.0);
    iconoMS.shadowSize = new GSize(42.0, 24.0);
    iconoMS.iconAnchor = new GPoint(14.0, 12.0);
    iconoMS.infoWindowAnchor = new GPoint(14.0, 12.0);

    iconoHotel = new GIcon();
    iconoHotel.image = "images/hotel.png";
    iconoHotel.shadow = "images/shadowIconos.png";
    iconoHotel.iconSize = new GSize(32.0, 37.0);
    iconoHotel.shadowSize = new GSize(51.0, 37.0);
    iconoHotel.iconAnchor = new GPoint(16.0, 18.0);
    iconoHotel.infoWindowAnchor = new GPoint(16.0, 18.0);

    iconoHostal = new GIcon();
    iconoHostal.image = "images/hostal.png";
    iconoHostal.shadow = "images/shadowIconos.png";
    iconoHostal.iconSize = new GSize(32.0, 37.0);
    iconoHostal.shadowSize = new GSize(51.0, 37.0);
    iconoHostal.iconAnchor = new GPoint(16.0, 18.0);
    iconoHostal.infoWindowAnchor = new GPoint(16.0, 18.0);

    iconoHospederia = new GIcon();
    iconoHospederia.image = "images/iconoHostal.png";
    iconoHospederia.shadow = "images/shadowIconos.png";
    iconoHospederia.iconSize = new GSize(32.0, 37.0);
    iconoHospederia.shadowSize = new GSize(51.0, 37.0);
    iconoHospederia.iconAnchor = new GPoint(16.0, 18.0);
    iconoHospederia.infoWindowAnchor = new GPoint(16.0, 18.0);

    iconoCRH = new GIcon();
    iconoCRH.image = "images/casaRural.png";
    iconoCRH.shadow = "images/shadowIconos.png";
    iconoCRH.iconSize = new GSize(32.0, 37.0);
    iconoCRH.shadowSize = new GSize(51.0, 37.0);
    iconoCRH.iconAnchor = new GPoint(16.0, 18.0);
    iconoCRH.infoWindowAnchor = new GPoint(16.0, 18.0);

    iconoCRC = new GIcon();
    iconoCRC.image = "images/casaRural.png";
    iconoCRC.shadow = "images/shadowIconos.png";
    iconoCRC.iconSize = new GSize(32.0, 37.0);
    iconoCRC.shadowSize = new GSize(51.0, 37.0);
    iconoCRC.iconAnchor = new GPoint(16.0, 18.0);
    iconoCRC.infoWindowAnchor = new GPoint(16.0, 18.0);

    iconoAlbergue = new GIcon();
    iconoAlbergue.image = "images/albergue.png";
    iconoAlbergue.shadow = "images/shadowIconos.png";
    iconoAlbergue.iconSize = new GSize(32.0, 37.0);
    iconoAlbergue.shadowSize = new GSize(51.0, 37.0);
    iconoAlbergue.iconAnchor = new GPoint(16.0, 18.0);
    iconoAlbergue.infoWindowAnchor = new GPoint(16.0, 18.0);

    iconoApartamentoTuristico = new GIcon();
    iconoApartamentoTuristico.image = "images/apartamentoTuristico.png";
    iconoApartamentoTuristico.shadow = "images/shadowIconos.png";
    iconoApartamentoTuristico.iconSize = new GSize(32.0, 37.0);
    iconoApartamentoTuristico.shadowSize = new GSize(51.0, 37.0);
    iconoApartamentoTuristico.iconAnchor = new GPoint(16.0, 18.0);
    iconoApartamentoTuristico.infoWindowAnchor = new GPoint(16.0, 18.0);

    iconoBalneario = new GIcon();
    iconoBalneario.image = "images/balneario.png";
    iconoBalneario.shadow = "images/shadowIconos.png";
    iconoBalneario.iconSize = new GSize(32.0, 37.0);
    iconoBalneario.shadowSize = new GSize(51.0, 37.0);
    iconoBalneario.iconAnchor = new GPoint(16.0, 18.0);
    iconoBalneario.infoWindowAnchor = new GPoint(16.0, 18.0);

    iconoTurismoAventura = new GIcon();
    iconoTurismoAventura.image = "images/turismoAventura.png";
    iconoTurismoAventura.shadow = "images/shadowIconos.png";
    iconoTurismoAventura.iconSize = new GSize(32.0, 37.0);
    iconoTurismoAventura.shadowSize = new GSize(51.0, 37.0);
    iconoTurismoAventura.iconAnchor = new GPoint(16.0, 18.0);
    iconoTurismoAventura.infoWindowAnchor = new GPoint(16.0, 18.0);

    iconoRestaurante = new GIcon();
    iconoRestaurante.image = "images/restaurante.png";
    iconoRestaurante.shadow = "images/shadowIconos.png";
    iconoRestaurante.iconSize = new GSize(32.0, 37.0);
    iconoRestaurante.shadowSize = new GSize(51.0, 37.0);
    iconoRestaurante.iconAnchor = new GPoint(16.0, 18.0);
    iconoRestaurante.infoWindowAnchor = new GPoint(16.0, 18.0);

    mapa = new GMap2(document.getElementById("map"));
    mapa.addControl(new GLargeMapControl());
    mapa.addControl(new GHierarchicalMapTypeControl());
    mapa.addMapType(G_PHYSICAL_MAP);
    mapa.addMapType(G_SATELLITE_3D_MAP);

    mapa.enableContinuousZoom();
    mapa.enableScrollWheelZoom();

}

function incluirHotel(nodoHotel) {

    var lat = parseFloat(nodoHotel.getAttribute("LAT"));
    var lng = parseFloat(nodoHotel.getAttribute("LNG"));
    var nombre = nodoHotel.getAttribute("NOMBRE");
    var direccion = nodoHotel.getAttribute("DIRECCION");
    var categoria = parseInt(nodoHotel.getAttribute("CATEGORIA"));
    //Transpondemos la categoria para que aparezca un orden lógico
    if (categoria >= 10) {
        categoria = parseInt(categoria - 10); //Hostales se quedarán con 01 - 02 - 03 
    } else {
        categoria = parseInt(categoria + 10); //Hoteles tomarán 11 - 12 - 13 - 14 - 15
    }
    var precioMinimo = "0";
    if (nodoHotel.getAttribute("PRECIOMINIMO")) precioMinimo = nodoHotel.getAttribute("PRECIOMINIMO").replace(",", ".");
    if (nodoHotel.getAttribute("PRECIODESDEIVA")) precioMinimo = nodoHotel.getAttribute("PRECIODESDEIVA").replace(",", ".");
    var descripcion = nodoHotel.getAttribute("DESCRIPCION");
    var codigo = nodoHotel.getAttribute("CODIGO");
    var videoYouTube = nodoHotel.getAttribute("VIDEOYOUTUBE");
    var imagenMiniatura = "0";
    if (nodoHotel.getAttribute("IMAGEN")) imagenMiniatura = nodoHotel.getAttribute("IMAGEN");
    if (nodoHotel.getAttribute("FIL_ID")) imagenMiniatura = nodoHotel.getAttribute("FIL_ID");
    var edadMaxBebe = nodoHotel.getAttribute("EDADMAXBEBE");
    var tipoEstablecimiento = nodoHotel.getAttribute("TIPOESTABLECIMIENTO");

    if (descripcion.length > 130) {
        descripcion = descripcion.substring(0, 130) + "..."
    }

    if (imagenMiniatura == "") {
        imagenMiniatura = 0
    }

    var estrellas = generarEstrellas(categoria);
    if (estrellas != "") estrellas += "<br/>";

    var imagenes = nodoHotel.getElementsByTagName("imagen");
    var galeriaImagenes = "haga click sobre las miniaturas para ampliar";
    var limiteImagenes;
    if (imagenes.length <= 9) {
        limiteImagenes = imagenes.length;
    } else {
        limiteImagenes = 9;
    }
    for (var i = 0; i < limiteImagenes; i++) {
        var imagenActual = imagenes[i].getAttribute("url");

        galeriaImagenes += "<a href=\"http://reservas.siron.es/admin/File.aspx?FIL_ID=" + imagenActual + "\" class=\"highslide\" onclick=\"return hs.expand(this)\" ><img src=\"http://reservas.siron.es/admin/File.aspx?FIL_ID=" + imagenActual + "&tImg=D&iW=71&iH=53\" /></a>"
    }
    if (imagenes.length == 0) {
        galeriaImagenes = "Galer&iacute;a de im&aacute;genes no disponible"
    }

    var tabs;

    if (videoYouTube != "") {
        tabs = [
			new GInfoWindowTab("info", "<div class=\"tabMapa\"><table><tr><td class=\"imagen\"><img src=\"http://reservas.siron.es/admin/File.aspx?FIL_ID=" + imagenMiniatura + "&tImg=D&iW=71&iH=53\" class=\"miniaturaHotel\"/></td><td><h5>" + nombre + "</h5>" + estrellas + "<br/><b>" + direccion + "</b><br/>" + descripcion + "</td></tr><tr><td></td><td><a href='javascript:verRestaurante(\"" + codigo + "\")' class=\"botonMasInfo\">m&aacute;s informaci&oacute;n</a><a class=\"zoomHotel\" href=\"javascript:mapa.setCenter(new GLatLng(" + lat + "," + lng + "), 17);\">Zoom</a></td></tr></table></div>"),
			new GInfoWindowTab("fotos", "<div class=\"tabMapa\" style=\"overflow:auto\">" + galeriaImagenes + "</div>"),
			 new GInfoWindowTab("video", "<div class=\"tabMapa\"><object width=\"280\" height=\"180\"><param name=\"movie\" value=\"http://www.youtube.com/v/" + videoYouTube + "&hl=es&fs=1\"></param><param name=\"allowFullScreen\" value=\"true\"></param><embed src=\"http://www.youtube.com/v/" + videoYouTube + "&hl=es&fs=1\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" width=\"280\" height=\"180\"></embed></object></div>")
			];
    } else {
        tabs = [
			new GInfoWindowTab("info", "<div class=\"tabMapa\"><table><tr><td class=\"imagen\"><img src=\"http://reservas.siron.es/admin/File.aspx?FIL_ID=" + imagenMiniatura + "&tImg=D&iW=71&iH=53\" class=\"miniaturaHotel\"/></td><td><h5>" + nombre + "</h5>" + estrellas + "<br/><b>" + direccion + "</b><br/>" + descripcion + "</td></tr><tr><td></td><td><a href='javascript:verRestaurante(\"" + codigo + "\")' class=\"botonMasInfo\">m&aacute;s informaci&oacute;n</a><a class=\"zoomHotel\" href=\"javascript:mapa.setCenter(new GLatLng(" + lat + "," + lng + "), 17);\">Zoom</a></td></tr></table></div>"),
			new GInfoWindowTab("fotos", "<div class=\"tabMapa\" style=\"overflow:auto\">" + galeriaImagenes + "</div>")];
    }

    var punto
    if (tipoEstablecimiento == 1) {
        punto = new GMarker(new GLatLng(lat, lng), iconoHotel);
    }
    if (tipoEstablecimiento == 2) {
        punto = new GMarker(new GLatLng(lat, lng), iconoHostal);
    }
    if (tipoEstablecimiento == 3) {
        punto = new GMarker(new GLatLng(lat, lng), iconoHospederia);
    }
    if (tipoEstablecimiento == 4) {
        punto = new GMarker(new GLatLng(lat, lng), iconoCRH);
    }
    if (tipoEstablecimiento == 5) {
        punto = new GMarker(new GLatLng(lat, lng), iconoCRC);
    }
    if (tipoEstablecimiento == 6) {
        punto = new GMarker(new GLatLng(lat, lng), iconoAlbergue);
    }
    if (tipoEstablecimiento == 7) {
        punto = new GMarker(new GLatLng(lat, lng), iconoApartamentoTuristico);
    }
    if (tipoEstablecimiento == 8) {
        punto = new GMarker(new GLatLng(lat, lng), iconoBalneario);
    }
    if (tipoEstablecimiento == 9) {
        punto = new GMarker(new GLatLng(lat, lng), iconoTurismoAventura);
    }
    if (tipoEstablecimiento == 10) {
        punto = new GMarker(new GLatLng(lat, lng), iconoRestaurante);
    }


    punto.isInfoWindowOpen = false;
    var tooltip = new Tooltip(punto, nombre, -50);
    punto.tooltip = tooltip;


    GEvent.addListener(punto, "click", function () { this.tooltip.hide(); punto.openInfoWindowTabsHtml(tabs); });
    GEvent.addListener(punto, 'mouseover', function () { if (!punto.isInfoWindowOpen) { this.tooltip.show(); } });
    GEvent.addListener(punto, 'mouseout', function () { this.tooltip.hide(); });
    GEvent.addListener(punto, 'infowindowopen', function () { punto.isInfoWindowOpen = true; });
    GEvent.addListener(punto, 'infowindowclose', function () { punto.isInfoWindowOpen = false; });

    mapa.addOverlay(punto);
    mapa.addOverlay(tooltip);
    punto.hide();
    // Generamos la entrada en el vector de hoteles

    vectorHoteles.nuevoHotel(codigo, nombre, direccion, categoria, precioMinimo, punto, '', '');
}

//_____29/09/2010_____Miguel Maicas
//cuando seleccionemos ver en mapa, nos posicionara la pantalla en el mapa
//en el xslt deberemos crear un elemento con value="#verMapa"
//si queremos que sea dinamico, indicaremos el valor del elemento
//function posicionarVentana(elementoDondeQueremosPosicionarnos)
//oEnlace = elementoDondeQueremosPosicionarnos.value;
function posicionarVentana() {
    oEnlace = "#verMapa";
    window.location = oEnlace; 
//    window.location.href(oEnlace);         No Funciona en firefox
 
}
//_____29/09/2010_____

function seleccionarHotelMapa(indexHotel) {
    posicionarVentana();
    //Disparamos el evento Click del punto en cuestión
    vectorHoteles.hotel[indexHotel].marker.show();
    GEvent.trigger(vectorHoteles.hotel[indexHotel].marker, "click");
}

function limpiarHotelesActuales() {

    //Recorremos el vector de hoteles y eliminamos todos los puntos del mapa
    if (vectorHoteles != undefined)
        for (i = 0; i < vectorHoteles.hotel.length; i++) {
            mapa.removeOverlay(vectorHoteles.hotel[i].marker);
        }
}

function limpiarPDISActuales() {

    //Recorremos el vector de hoteles y eliminamos todos los puntos del mapa
    if (vectorPDIs != undefined)
        for (i = 0; i < vectorPDIs.length; i++) {
            mapa.removeOverlay(vectorPDIs[i]);

        }
}

function cambiarZonaMapa() {

    hacerZoomAZona(document.getElementById('cmbZonasMapa').value);
    recargarConsulta();

}


function hacerZoomAZona(numeroZona) {

    //Cambiamos la posición y el zoom del mapa a la zona concreta seleccionada
    switch (numeroZona) {
        case 'Aranda':
            mapa.setCenter(new GLatLng(41.573334, -1.792145), 10);
            break;
        case 'Bajo Aragón-Caspe':
            mapa.setCenter(new GLatLng(41.235478, -0.041199), 10);
            break;
        case 'Bajo Cinca':
            mapa.setCenter(new GLatLng(41.512691, 0.351563), 10);
            break;
        case 'Campo de Belchite':
            mapa.setCenter(new GLatLng(41.309986, -0.754023), 10);
            break;
        case 'Campo de Borja':
            mapa.setCenter(new GLatLng(41.808173, -1.51062), 10);
            break;
        case 'Campo de Cariñena':
            mapa.setCenter(new GLatLng(41.336349, -1.225319), 10);
            break;
        case 'Campo de Daroca':
            mapa.setCenter(new GLatLng(41.114021, -1.412086), 10);
            break;
        case 'Cinco Villas':
            mapa.setCenter(new GLatLng(42.115543, -1.149445), 10);
            break;
        case 'Comunidad de Calatayud':
            mapa.setCenter(new GLatLng(41.356196, -1.652756), 10);
            break;
        case 'Hoya de Huesca':
            mapa.setCenter(new GLatLng(42.309815, -0.55481), 10);
            break;
        case 'La Jacetania':
            mapa.setCenter(new GLatLng(42.730874, -0.758057), 10);
            break;
        case 'Los Monegros':
            mapa.setCenter(new GLatLng(41.750824, -0.148315), 10);
            break;
        case 'Ribera Alta del Ebro':
            mapa.setCenter(new GLatLng(41.983994, -0.834961), 10);
            break;
        case 'Ribera Baja del Ebro':
            mapa.setCenter(new GLatLng(41.512691, -0.527344), 10);
            break;
        case 'Tarazona y el Moncayo':
            mapa.setCenter(new GLatLng(41.8987, -1.722107), 10);
            break;
        case 'Valdejalón':
            mapa.setCenter(new GLatLng(41.611335, -1.257935), 10);
            break;
        case 'Zaragoza':
            mapa.setCenter(new GLatLng(41.651367, -0.883026), 12);
            break;
        default:
            //Zoom por defecto en mapa general
            mapa.setCenter(new GLatLng(41.651367, -0.883026), 7);
    }
}

function cambiarEstadoLineasMetro() {

    if (document.getElementById('chkLineasMetro').checked) {
        //Carga asíncronamente la capa KML con las líneas del metro 		
        geoXmlLineasMetro = new GGeoXml("http://zaragozahoteles.desarrollando.net/lineasMetro.kml");
        mapa.addOverlay(geoXmlLineasMetro);

    } else {
        //Borra la capa KML con las líneas del metro 		
        mapa.removeOverlay(geoXmlLineasMetro);
    }
}

function cambiarEstadoLugaresInteres() {

    if (document.getElementById('chkLugaresInteres').checked) {
        //Carga asíncronamente la capa KML con los lugares de interés		
        cargarPDIS(false);

    } else {
        //Borra la capa KML con las líneas del metro 		
        limpiarPDISActuales();
    }
}

/*Funciones del elemento ToolTip*/

function Tooltip(marker, text, padding) {
    this.marker_ = marker;
    this.text_ = text;
    this.padding_ = padding;
}

Tooltip.prototype = new GOverlay();

Tooltip.prototype.initialize = function (map) {
    var div = document.createElement("div");
    div.appendChild(document.createTextNode(this.text_));
    div.className = 'tooltip';
    div.style.position = 'absolute';
    div.style.visibility = 'hidden';
    map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
    this.map_ = map;
    this.div_ = div;
}

Tooltip.prototype.remove = function () {
    this.div_.parentNode.removeChild(this.div_);
}

Tooltip.prototype.copy = function () {
    return new Tooltip(this.marker_, this.text_, this.padding_);
}

Tooltip.prototype.redraw = function (force) {
    if (!force) return;
    var markerPos = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());
    var iconAnchor = this.marker_.getIcon().iconAnchor;
    var xPos = Math.round(markerPos.x - this.div_.clientWidth / 2);
    var yPos = markerPos.y - iconAnchor.y - this.div_.clientHeight - this.padding_;
    this.div_.style.top = yPos + 'px';
    this.div_.style.left = xPos + 'px';
}

Tooltip.prototype.show = function () {
    this.div_.style.visibility = 'visible';
}

Tooltip.prototype.hide = function () {
    this.div_.style.visibility = 'hidden';
}

/* Funciones del vector de hoteles */

function objetoHoteles() {
    this.hotel = new Array();
}

function hotel(codigo, nombre, direccion, categoria, precio, marker, descripcion, imagen) {
    this.codigo = codigo;
    this.nombre = nombre;
    this.direccion = direccion;
    this.categoria = categoria;
    this.precio = parseFloat(precio);
    this.marker = marker;
    this.descripcion = descripcion;
    this.imagen = imagen; ;
}

objetoHoteles.prototype.nuevoHotel = function (codigo, nombre, direccion, categoria, precio, marker, descripcion, imagen) {
    this.hotel[this.hotel.length] = new hotel(codigo, nombre, direccion, categoria, precio, marker, descripcion, imagen);
}

objetoHoteles.prototype.ordenar = function () {
    var param = "return ", dato, orden;
    for (var i = 0; i < arguments.length; i += 2) {
        dato = arguments[i];
        orden = (arguments[i + 1] == "D") ? 1 : -1;

        param += "(x." + dato + " < y." + dato + ")?" + orden + ":";
        param += "(x." + dato + " > y." + dato + ")?" + (0 - orden) + ":";
    }

    param += "0;";

    this.hotel.sort(new Function("x", "y", param));
}

/* Funciones de manejo de la tabla de hoteles bajo el mapa */

function actualizarTablaHoteles(paginaActual) {

    //Limpiamos la tabla actual de hoteles
    var tablaHoteles = document.getElementById('tablaHoteles');

    if (vectorHoteles.hotel.length > 0) {

        limpiarFilas(tablaHoteles);

        //Ahora recorremos el vector de hoteles y hacemos la llamada a la funcion que pinta cada fila
        var posicionInicial = paginaActual * elementosXPagina;
        var posicionFinal = posicionInicial + elementosXPagina;

        if (posicionFinal > vectorHoteles.hotel.length)
            posicionFinal = vectorHoteles.hotel.length;
        //Pintamos los elementos en la tabla

        for (i = posicionInicial; i < posicionFinal; i++) {

            nuevaFila(tablaHoteles, vectorHoteles.hotel[i], i);
        }

        //Obtenemos el número de páginas total y pintamos el paginador
        if ((vectorHoteles.hotel.length % elementosXPagina) == 0) {
            numeroTotalPaginas = (vectorHoteles.hotel.length / elementosXPagina);
        } else {
            numeroTotalPaginas = ((vectorHoteles.hotel.length - (vectorHoteles.hotel.length % elementosXPagina)) / elementosXPagina) + 1;
        }

        incluirFilaPaginacion(tablaHoteles, numeroTotalPaginas, paginaActual);

    }
}

function limpiarFilas(tabla) {

    while (tabla.rows.length > 1)
        tabla.deleteRow(tabla.rows.length - 1);
}

function nuevaFila(tabla, nuevoHotel, indexHotel) {
    var hotel = tabla.insertRow(-1);

    var celdaHoteles = hotel.insertCell(0)
    var celdaCategoria = hotel.insertCell(1)

    celdaHoteles.innerHTML = "<h4><a href='javascript:verRestaurante(\"" + nuevoHotel.codigo + "\")'>" + nuevoHotel.nombre + "</a></h4>" + nuevoHotel.direccion + " · <a href='javascript:seleccionarHotelMapa(" + indexHotel + ")'>" + verEnMapa  + "</a>";

    var estrellas = generarEstrellas(nuevoHotel.categoria);
    if (estrellas == "") estrellas = "&nbsp;";

    celdaCategoria.innerHTML = estrellas;
}


function incluirFilaPaginacion(tabla, numeroPaginas, paginaActiva) {

    var paginador = tabla.insertRow(-1);
    var celdaPaginacion = paginador.insertCell(0)
    celdaPaginacion.colSpan = 3;
    celdaPaginacion.className = "celdaPaginacion"

    for (i = 0; i < numeroPaginas; i++) {
        if (i != paginaActiva) {
            celdaPaginacion.innerHTML += "<a href='javascript:actualizarTablaHoteles(" + i + ")'>" + (i + 1) + "</a> "
        } else {
            celdaPaginacion.innerHTML += "<span class='numeroActual'>" + (i + 1) + "</span> "
        }

    }

}

function restablecerFlechas() {
    document.getElementById("nombreA").src = "images/flechaArribaG.gif"
    document.getElementById("categoriaA").src = "images/flechaArribaG.gif"
    document.getElementById("nombreD").src = "images/flechaAbajoG.gif"
    document.getElementById("categoriaD").src = "images/flechaAbajoG.gif"
}

function reordenarTabla(campo, tipo) {

    restablecerFlechas();

    if (tipo == 'A') {
        document.getElementById(campo + tipo).src = "images/flechaArriba.gif"
    } else {
        document.getElementById(campo + tipo).src = "images/flechaAbajo.gif"
    }

    vectorHoteles.ordenar(campo, tipo);
    actualizarTablaHoteles(0);

}

function reordenarLista(campo, tipo) {

    vectorHoteles.ordenar(campo, tipo);
    actualizarListadoHoteles(0);

}

function generarEstrellas(categoria) {
    var estrellas = "";
    var numeroEstrellas = categoria % 10;
    for (var i = 0; i < numeroEstrellas; i++) {
        estrellas += "<img src=\"images\/imgTenedor.gif\" class=\"estrella\"/>"
    }
    return estrellas;
}

function lanzarBusqueda() {
    //alert("parametrosBusqueda lanzarBusqueda(): " + parametrosBusqueda);
    informarNumeroHotelesEncontrados(-1);

    //Limpiamos primero los posibles puntos que haya en el mapa
    limpiarHotelesActuales();
    restablecerFlechas();

    //limpiarDivPaginacion(document.getElementById('paginador'))

    //Aqui lanzaríamos la búsqueda con los parámetros necesarios	
    var URLAjax = "ajaxHoteles.aspx"
    if (parametrosBusqueda != "") {
        URLAjax += "?" + parametrosBusqueda;
    }

    var fecha = new Date();
    URLAjax += "&paramD=" + fecha.getTime();

    //prompt("",URLAjax);

    GDownloadUrl(URLAjax, function (doc) {

        var precioMinimo = 50000;
        var precioMaximo = 0;

        var xmlDoc = GXml.parse(doc);
        if (xmlDoc.documentElement) {
            var hoteles = xmlDoc.documentElement.getElementsByTagName("RESTAURANTE");
            vectorHoteles = new objetoHoteles();
            for (var i = 0; i < hoteles.length; i++) {
                incluirHotel(hoteles[i]);
                var precioHotel = parseFloat(hoteles[i].getAttribute("PRECIOMINIMO"));
                if (precioHotel < precioMinimo)
                { precioMinimo = precioHotel }
                if (precioHotel > precioMaximo)
                { precioMaximo = precioHotel }
            }

            //En este punto debemos pintar el punto de interés seleccionado, si es que lo hay
            var comboPuntos = document.getElementById('selectPDI');
            if (comboPuntos.value != '0,0') {
                pintarPuntoInteres(comboPuntos.value) //Crear esta funcion
            }
        } else {
            hoteles = new Array();
        }

        informarNumeroHotelesEncontrados(hoteles.length);

        if ((precioMinimo == 0) || (hoteles.length == 0)) {
            //inicializarSlider(precioMinimoDefecto,precioMaximoDefecto);
        } else {
            precioMaximo = precioMaximo + (precioMaximo / 50);
            precioMinimo = precioMinimo - (precioMinimo / 50);
            actualizarListadoHoteles(0);
        }
        actualizarTablaHoteles(0);

        hacerZoomAZona(0);
    });
}
//MIGUEL
function lanzarBusquedaRestaurantes(poblacion, provincia, tags) {

    inicializarMapa();
    mapa.setMapType(G_NORMAL_MAP);
    hacerZoomAZona(0);
    informarNumeroHotelesEncontrados(-1);

    //Limpiamos primero los posibles puntos que haya en el mapa
    limpiarHotelesActuales();
    restablecerFlechas();

    //limpiarDivPaginacion(document.getElementById('paginador'))

    //Aqui lanzaríamos la búsqueda con los parámetros necesarios	
    var URLAjax = "ajaxHoteles.aspx"
//    parametrosBusqueda += "PASO1_CATEGORIA=" + categoria;
//    parametrosBusqueda += "&PASO1_PRECIOMINIMO=" + document.getElementById("precioMinimo").value;
//    parametrosBusqueda += "&PASO1_PRECIOMAXIMO=" + document.getElementById("precioMaximo").value;
//    parametrosBusqueda += "&PASO1_FECHADESDE=" + document.getElementById("PASO1_FECHADESDE").value;
//    parametrosBusqueda += "&PASO1_FECHAHASTA=" + document.getElementById("PASO1_FECHAHASTA").value;
//    parametrosBusqueda += "&PASO1_NUMHABITACIONES=" + document.getElementById("PASO1_NUMHABITACIONES").value;
//    parametrosBusqueda += "&PASO1_numAdultos_1=" + document.getElementById("PASO1_numAdultos_1").value;
//    parametrosBusqueda += "&PASO1_numAdultos_2=" + document.getElementById("PASO1_numAdultos_2").value;
//    parametrosBusqueda += "&PASO1_numAdultos_3=" + document.getElementById("PASO1_numAdultos_3").value;
//    parametrosBusqueda += "&PASO1_numAdultos_4=" + document.getElementById("PASO1_numAdultos_4").value;
//    parametrosBusqueda += "&PASO1_numAdultos_5=" + document.getElementById("PASO1_numAdultos_5").value;
//    parametrosBusqueda += "&PASO1_numNinos_1=" + document.getElementById("PASO1_numNinos_1").value;
//    parametrosBusqueda += "&PASO1_numNinos_2=" + document.getElementById("PASO1_numNinos_2").value;
//    parametrosBusqueda += "&PASO1_numNinos_3=" + document.getElementById("PASO1_numNinos_3").value;
//    parametrosBusqueda += "&PASO1_numNinos_4=" + document.getElementById("PASO1_numNinos_4").value;
//    parametrosBusqueda += "&PASO1_numNinos_5=" + document.getElementById("PASO1_numNinos_5").value;
//    parametrosBusqueda += "&PASO1_NOCHES=" + document.getElementById("PASO1_NOCHES").value;
//    parametrosBusqueda += "&PASO1_TAG=" + document.getElementById("PASO1_TAG").value;
    parametrosBusqueda += "&TIPOBUSQUEDA=RESTAURANTES"
    parametrosBusqueda += "&laPoblacion=" + poblacion
    parametrosBusqueda += "&laProvincia=" + provincia
    parametrosBusqueda += "&losTags=" + tags

    if (parametrosBusqueda != "") {
        URLAjax += "?" + parametrosBusqueda;
    }
    var fecha = new Date();
    URLAjax += "&paramD=" + fecha.getTime();
    parametrosBusqueda = "";
    //prompt("",URLAjax);
    //prompt("",  URLAjax);
    GDownloadUrl(URLAjax, function (doc) {
        var xmlDoc = GXml.parse(doc);
        if (xmlDoc.documentElement) {
            var hoteles = xmlDoc.documentElement.getElementsByTagName("RESTAURANTE");
            vectorHoteles = new objetoHoteles();
            for (var i = 0; i < hoteles.length; i++) {
                incluirHotel(hoteles[i]);
            }
        } else {
            hoteles = new Array();
        }

        informarNumeroHotelesEncontrados(hoteles.length);
        actualizarTablaHoteles(0);

        hacerZoomAZona(0);
    });
}


function pintarPuntoInteres(latLong) {

    punto = new GMarker(new GLatLng(latLong.split(",")[0], latLong.split(",")[1]), iconoAmarillo);
    mapa.addOverlay(punto);

}

function recargarConsulta() {

    //alert("entramos en recargarConsulta() ");
    var categoria = 0;

    var radioButtons = document.getElementsByName("categoria");
    for (var x = 0; x < radioButtons.length; x++) {
        if (radioButtons[x].checked) {
            categoria = radioButtons[x].value;
        }
    }

    parametrosBusqueda = "";
    parametrosBusqueda += "PASO1_CATEGORIA=" + categoria;

    parametrosBusqueda += "&PASO1_TAG=" + document.getElementById("PASO1_TAG").value;

    parametrosBusqueda += "&TIPOBUSQUEDA=" + document.getElementById("tipoBusqueda").value;

    lanzarBusqueda();
}

function incluirHotelAVector(nodoHotel) {

    var lat = parseFloat(nodoHotel.getAttribute("LAT"));
    var lng = parseFloat(nodoHotel.getAttribute("LNG"));
    var nombre = nodoHotel.getAttribute("NOMBRE");
    var direccion = nodoHotel.getAttribute("DIRECCION");
    var categoria = parseInt(nodoHotel.getAttribute("CATEGORIA"));
    var precioMinimo = nodoHotel.getAttribute("PRECIOMINIMO");
    var descripcion = nodoHotel.getAttribute("DESCRIPCION");
    var codigo = nodoHotel.getAttribute("CODIGO");
    var videoYouTube = nodoHotel.getAttribute("VIDEOYOUTUBE");
    var imagenMiniatura = nodoHotel.getAttribute("IMAGEN");

    vectorHoteles.nuevoHotel(codigo, nombre, direccion, categoria, precioMinimo, '', descripcion, imagenMiniatura);

}

function informarNumeroHotelesEncontrados(numero) {
    var numeroHoteles = document.getElementById("numeroHotelesEncontrados");
    var capaHoteles = document.getElementById('capaSinResultados');
    var tablaHoteles = document.getElementById('tablaHoteles');

    if (numero > 0) {
        numeroHoteles.innerHTML = numero + ' ' + textoEncontrado;
        capaHoteles.style.display = "none";
        tablaHoteles.style.display = "";
    } else
        if (numero == -1) {
            numeroHoteles.innerHTML = textoBuscando;
            capaHoteles.style.display = "";
            tablaHoteles.style.display = "none";
            capaHoteles.innerHTML = "<br/><br/><br/><br/><div align='center'><img src='images/loading.gif'/><p>&nbsp;</p><p>" + textoBusquedaAJAX + "</p></div>"
        } else {
            numeroHoteles.innerHTML = textoNoEncontrado;
            capaHoteles.style.display = "";
            tablaHoteles.style.display = "none";
            capaHoteles.innerHTML = "<br/><br/><br/><br/><br/><br/><br/><div align='center'>" + textoNoEncontrado + "</div>"
        }
}
