//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 = "";
var tipoZoom = ""; 

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), 10);

        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);

    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 = nodoHotel.getAttribute("precioMinimo").replace(",", ".");
    var descripcion = nodoHotel.getAttribute("descripcion");
    var codigo = nodoHotel.getAttribute("codigo");
    var videoYouTube = nodoHotel.getAttribute("videoYouTube");
    var imagenMiniatura = nodoHotel.getAttribute("imagen");
    var edadMaxBebe = nodoHotel.getAttribute("edadMaxBebe");
    if (descripcion.length > 130) {
        descripcion = descripcion.substring(0, 130) + "..."
    }

    if (imagenMiniatura == "") {
        imagenMiniatura = 0
    }


    var estrellas = generarEstrellas(categoria);

    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 = "El hotel no dispone de galer&iacute;a de im&aacute;genes"
    }

    var precioFormateado = 0;
    if (precioMinimo > 0) precioFormateado = parseFloat(precioMinimo).toFixed(2);

    var tabs;

    if (videoYouTube != "") {
        tabs = [
			new GInfoWindowTab("info Hotel", "<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\"/><p>Desde<br/><b>" + String(precioFormateado).replace(".", ",") + " &euro;</b></p></td><td><h5>" + nombre + "</h5>" + estrellas + "<br/><br/><b>" + direccion + "</b><br/>" + descripcion + "</td></tr><tr><td><a href=\"javascript:lanzarReserva('" + codigo + "'," + edadMaxBebe + ")\" class=\"botonReservar\">reservar</a></td><td><a href=\"javascript:verHotel('" + codigo + "')\" class=\"botonMasInfo\">m&aacute;s informaci&oacute;n</a><a class=\"zoomHotel\" href=\"javascript:mapa.setCenter(new GLatLng(" + lat + "," + lng + "), 17);\">Zoom Hotel</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 Hotel", "<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\"/><p>Desde<br/><b>" + String(precioFormateado).replace(".", ",") + " &euro;</b></p></td><td><h5>" + nombre + "</h5>" + estrellas + "<br/><br/><b>" + direccion + "</b><br/>" + descripcion + "</td></tr><tr><td><a href=\"javascript:lanzarReserva('" + codigo + "'," + edadMaxBebe + ")\" class=\"botonReservar\">reservar</a></td><td><a href=\"javascript:verHotel('" + codigo + "')\" class=\"botonMasInfo\">m&aacute;s informaci&oacute;n</a><a class=\"zoomHotel\" href=\"javascript:mapa.setCenter(new GLatLng(" + lat + "," + lng + "), 17);\">Zoom Hotel</a></td></tr></table></div>"),

			new GInfoWindowTab("fotos", "<div class=\"tabMapa\" style=\"overflow:auto\">" + galeriaImagenes + "</div>")];
    }

    var punto = new GMarker(new GLatLng(lat, lng), iconoMS);
    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);

    // Generamos la entrada en el vector de hoteles

    vectorHoteles.nuevoHotel(codigo, nombre, direccion, categoria, precioFormateado, punto, '', '');
}

function seleccionarHotelMapa(indexHotel) {

    //Disparamos el evento Click del punto en cuestión
    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() {
	alert(document.getElementById("selectPDI"));
	if(document.getElementById("selectPDI")) document.getElementById("selectPDI").selectedIndex = 0;
    hacerZoomAZona(document.getElementById('cmbZonasMapa').value);
    recargarConsulta();
}


function hacerZoomAZona(numeroZona) {
    tipoZoom = "";
    //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;
        case 'especifica':
            tipoZoom = "especifica";
            mapa.setCenter(new GLatLng(latAux, lngAux), 12);
            break;
        default:
            //Zoom por defecto en mapa general
            mapa.setCenter(new GLatLng(41.651367, -0.883026), 12);
    }
}

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.precioHotel = 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)
    var celdaPrecio = hotel.insertCell(2)

    celdaHoteles.innerHTML = "<h4><a href=\"javascript:verHotel('" + nuevoHotel.codigo + "');\">" + nuevoHotel.nombre + "</a></h4>" + nuevoHotel.direccion + " · <a href=\"javascript:seleccionarHotelMapa(" + indexHotel + ");\">Ver en Mapa</a>";
    //alert(celdaHoteles.innerHTML);
    
    var estrellas = generarEstrellas(nuevoHotel.categoria);

    celdaCategoria.innerHTML = estrellas;
    celdaPrecio.innerHTML = String(nuevoHotel.precioHotel).replace(".", ",") + " &euro;";

    celdaPrecio.className = "celdaPrecio"
}


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("precioA").src = "images/flechaArribaG.gif"
    document.getElementById("nombreD").src = "images/flechaAbajoG.gif"
    document.getElementById("categoriaD").src = "images/flechaAbajoG.gif"
    document.getElementById("precioD").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\\imgEstrella.gif\" class=\"estrella\"/>"
    }
    return estrellas;

}

function lanzarBusqueda() {

    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 += "&paramFecha=" + fecha.toLocaleString();
    //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("hotel");
            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 {
            var hoteles = new Array();
        }

        informarNumeroHotelesEncontrados(hoteles.length);

        if ((precioMinimo == 0) || (hoteles.length == 0)) {
            inicializarSlider(precioMinimoDefecto, precioMaximoDefecto);
        } else {
            precioMaximo = precioMaximo + (precioMaximo / 50);
            precioMinimo = precioMinimo - (precioMinimo / 50);
            //alert(precioMinimo + "\n" + precioMaximo);
            inicializarSlider(precioMinimo, precioMaximo);
            actualizarTablaHoteles(0);
        }

        if (tipoZoom == "") hacerZoomAZona(document.getElementById('cmbZonasMapa').value);
        var cboPDI = document.getElementById('selectPDI');
        if (cboPDI) {
            if (cboPDI.selectedIndex > 0) {
                latAux = cboPDI.options[cboPDI.selectedIndex].value.split(",")[0];
                lngAux = cboPDI.options[cboPDI.selectedIndex].value.split(",")[1];
                hacerZoomAZona("especifica");
            }
        }
    });
}

function pintarPuntoInteres(latLong) {

    punto = new GMarker(new GLatLng(latLong.split(",")[0], latLong.split(",")[1]), iconoAmarillo);
    mapa.addOverlay(punto);

}

function recargarConsulta() {


    var categoria;
    var servicios = "";
    var latLng = document.getElementById("selectPDI").value;

    var radioButtons = document.getElementsByName("categoria");
    for (var x = 0; x < radioButtons.length; x++) {
        if (radioButtons[x].checked) {
            categoria = radioButtons[x].value;
        }
    }

    var checkButtons = document.getElementsByName("servicios");
    for (var x = 0; x < checkButtons.length; x++) {
        if (checkButtons[x].checked) {
            servicios += checkButtons[x].value + ',';
        }
    }

    parametrosBusqueda = "";
    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_UBICACION=" + document.getElementById("cmbZonasMapa").value;

    parametrosBusqueda += "&PASO1_NOCHES=" + document.getElementById("PASO1_NOCHES").value;

    parametrosBusqueda += "&PASO1_TAG=" + document.getElementById("PASO1_TAG").value;

    if (servicios != "") {
        servicios = servicios.substring(0, servicios.length - 1);
        parametrosBusqueda += "&PASO1_SERVICIOS=" + servicios;
    }

    if (latLng != "0,0") {
        parametrosBusqueda += "&PASO1_GEOLATITUD=" + latLng.split(",")[0].replace(".", ",");
        parametrosBusqueda += "&PASO1_GEOLONGITUD=" + latLng.split(",")[1].replace(".", ",");
        parametrosBusqueda += "&PASO1_GEODISTANCIA=" + document.getElementById("distancia").value;
        parametrosBusqueda += "&PASO1_GEOFACTORDISTANCIA=0,011";

    }

    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>"
    }
}
