//Funciones del mapa del buscador de cercanía
var mapa;
var geoXmlLugaresInteres;
var geoXmlLineasMetro;
var iconoPDI;
var iconoMS;
var vectorHoteles;
var vectorPDIs;
var elementosXPagina = 10;
var parametrosBusqueda = "";
var zone;
var idioma;
var browser;

if (navigator.userAgent.indexOf("MSIE") >= 0) {
    browser = "IE";
} else {
    browser = "FF";
}

function limpiarHotelesActuales() {
    mapa.clearOverlays();
    //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);
    }*/
}

/* Funciones del vector de hoteles */

function objetoHoteles() {
    this.hotel = new Array();
}

function hotel(codigo, nombre, direccion, categoria, precio, marker, descripcion, imagen, edadMaxBebe) {
    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;
    this.edadMaxBebe = edadMaxBebe;
}

objetoHoteles.prototype.nuevoHotel = function(codigo, nombre, direccion, categoria, precio, marker, descripcion, imagen, edadMaxBebe) {
    this.hotel[this.hotel.length] = new hotel(codigo, nombre, direccion, categoria, precio, marker, descripcion, imagen, edadMaxBebe);
}

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 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 reordenarLista(campo, tipo) {

    restablecerFlechas();

    if (tipo == 'A') {
        document.getElementById(campo + tipo).src = "/images/flechaArribaN.gif"
    } else {
        document.getElementById(campo + tipo).src = "/images/flechaAbajoN.gif"
    }

    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 lanzarBusquedaListado() {
    informarNumeroHotelesEncontrados(-1);
    limpiarDivPaginacion(document.getElementById('paginador'));
    restablecerFlechas();

    /*//Generamos la dirección de la petición del XML
    var URLAjax = reemplazaTodo(raizWeb, "%3A", ":") + "ajaxHoteles.aspx"
    if (parametrosBusqueda != "") {
    URLAjax += "?" + parametrosBusqueda;
    }
    //prompt("",URLAjax);
    
    //Realizamos la petición
    if (window.XMLHttpRequest) {
    xhttp = new XMLHttpRequest()
    } else {
    xhttp = new ActiveXObject("Msxml2.XMLHTTP.3.0")
    }

    xhttp.open("GET", URLAjax, false);
    xhttp.send(null);

    var xmlHoteles;
    if (window.ActiveXObject) {
    var xmlDoc = new ActiveXObject("Msxml2.DOMDocument.4.0");
    xmlDoc.loadXML(xhttp.responseText);
    xmlHoteles = xmlDoc.childNodes[1];
    } else {
    var objDoc = new DOMParser().parseFromString(xhttp.responseText, "text/xml");
    var xmlDoc = document.implementation.createDocument("", "", null);
    xmlDoc = objDoc;
    xmlHoteles = xmlDoc.documentElement;
    }

    var precioMinimo = 50000;
    var precioMaximo = 0;

    vectorHoteles = new objetoHoteles();

    for (var i = 0; i < xmlHoteles.childNodes.length; i++) {
    incluirHotelAVector(xmlHoteles.childNodes[i]);

        var precioHotel = parseFloat(xmlHoteles.childNodes[i].getAttribute("precioMinimo"));
    if (precioHotel < precioMinimo)
    { precioMinimo = precioHotel }
    if (precioHotel > precioMaximo)
    { precioMaximo = precioHotel }
    }

    informarNumeroHotelesEncontrados(xmlHoteles.childNodes.length);

    if ((precioMinimo == 0) || (xmlHoteles.childNodes.length == 0)) {
    inicializarSlider(precioMinimoDefecto, precioMaximoDefecto);
    } else {
    precioMaximo = precioMaximo + (precioMaximo / 50);
    precioMinimo = precioMinimo - (precioMinimo / 50);
    inicializarSlider(precioMinimo, precioMaximo);
    }

    actualizarListadoHoteles(0);*/


    //Generamos la dirección de la petición del XML
    var URLAjax = reemplazaTodo(raizWeb, "%3A", ":") + "ajaxHoteles.aspx"
    if (parametrosBusqueda != "") {
        URLAjax += "?" + parametrosBusqueda;
    }
    //Realizamos la petición
    //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++) {
                incluirHotelAVector(hoteles[i]);

                var precioHotel = 0;

                if (hoteles[i].getAttribute("PRECIOMINIMO") != null) {
                    precioHotel = parseFloat(hoteles[i].getAttribute("PRECIOMINIMO").replace(",", "."));
                }
                if (hoteles[i].getAttribute("PRECIODESDEIVA") != null) {
                    precioHotel = parseFloat(hoteles[i].getAttribute("PRECIODESDEIVA").replace(",", "."));
                }
                
				if (precioHotel == 0) { 
					precioHotel = parseFloat(hoteles[i].getAttribute("precioMinimo"));
				}
                
                if (precioHotel != 0) {
                    if (precioHotel < precioMinimo) precioMinimo = precioHotel;
                    if (precioHotel > precioMaximo) precioMaximo = precioHotel;
                }
            }
        } 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);
            inicializarSlider(precioMinimo, precioMaximo);
            actualizarListadoHoteles(0);
        }
    });
}

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"));
    //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");

    //Acortamos la descripción si es demasiado extensa

    if (descripcion.length > 170) {
        descripcion = descripcion.substring(0, 170) + "..."
    }

    if (imagenMiniatura == "") {
        imagenMiniatura = 0
    }

    var precioFormateado = 0;
    if(precioMinimo > 0) precioFormateado = parseFloat(precioMinimo).toFixed(2);

    vectorHoteles.nuevoHotel(codigo, nombre, direccion, categoria, precioFormateado, '', descripcion, imagenMiniatura, edadMaxBebe);
}

function actualizarListadoHoteles(paginaActual) {

    //Limpiamos la tabla actual de hoteles
    var capaHoteles = document.getElementById('capaHoteles');
    if (vectorHoteles.hotel.length > 0) {

        //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;

        //Limpiamos la capa de los hoteles
        capaHoteles.innerHTML = '';

        //Pintamos los elementos en la tabla
        for (i = posicionInicial; i < posicionFinal; i++) {
            nuevoHotelCapa(capaHoteles, 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;
        }

        incluirDivPaginacion(document.getElementById('paginador'), numeroTotalPaginas, paginaActual);
        document.location = '#arriba';

    }
}

function nuevoHotelCapa(capa, nuevoHotel, indexHotel) {

    var HTMLHotel;

    if (nuevoHotel.precio == 0) {
        //Caso en el que no hacemos consulta de disponibilidad. Eliminamos el "Precio Desde"
        //HTMLHotel = "<div class=\"cuadroHotel\"><div class=\"precioReserva\">" + precioNulo + "<br/><a href=\"javascript:lanzarReserva('" + nuevoHotel.codigo + "')\" title=\"" + reservar + "\">" + reservar + "</a></div><a onclick=\"return hs.expand(this)\" href=\"http://reservas.siron.es/admin/File.aspx?FIL_ID=" + nuevoHotel.imagen + "\" title=\"" + nuevoHotel.nombre + "\" target=\"_blank\"><img class=\"miniaturaListado\" src=\"http://reservas.siron.es/admin/File.aspx?FIL_ID=" + nuevoHotel.imagen + "&tImg=D&iW=71&iH=53\" alt=\"" + nuevoHotel.nombre + "\" /></a><h3><a href=\"javascript:verHotel(" + nuevoHotel.codigo + ")\">" + nuevoHotel.nombre + "</a>&#160;" + generarEstrellas(nuevoHotel.categoria) + "</h3><div class=\"direccion\">" + nuevoHotel.direccion + " · <a href=\"hotel.aspx?CODIGOHOTEL=" + nuevoHotel.codigo + "&amp;mapa=1\" title=\"" + verEnMapa + "\">" + verEnMapa + "</a></div><div class=\"descripcion\">" + nuevoHotel.descripcion + "</div></div>";				
        HTMLHotel = "<div class=\"cuadroHotel\"><div class=\"precioReserva\">" + precioNulo + "<br/><a href=\"javascript:lanzarReserva('" + nuevoHotel.codigo + "'," + nuevoHotel.edadMaxBebe + ")\" title=\"" + reservar + "\">" + reservar + "</a></div><a onclick=\"return hs.expand(this)\" href=\"http://reservas.siron.es/admin/File.aspx?FIL_ID=" + nuevoHotel.imagen + "\" title=\"" + nuevoHotel.nombre + "\" target=\"_blank\"><img class=\"miniaturaListado\" src=\"http://reservas.siron.es/admin/File.aspx?FIL_ID=" + nuevoHotel.imagen + "&tImg=D&iW=71&iH=53\" alt=\"" + nuevoHotel.nombre + "\" /></a><h3><a href=\"javascript:verHotel('" + nuevoHotel.codigo + "')\">" + nuevoHotel.nombre + "</a>&#160;" + generarEstrellas(nuevoHotel.categoria) + "</h3><div class=\"direccion\">" + nuevoHotel.direccion + " · <a href=\"/hotel.aspx?CODIGOHOTEL=" + nuevoHotel.codigo + "&amp;mapa=1\" title=\"" + verEnMapa + "\">" + verEnMapa + "</a></div><div class=\"descripcion\">" + nuevoHotel.descripcion + "</div></div>";
    } else {
        //HTMLHotel = "<div class=\"cuadroHotel\"><div class=\"precioReserva\">" + precioDesde + "<br/><b>" + String(nuevoHotel.precio).replace(".",",") + "€</b><a href=\"javascript:lanzarReserva('" + nuevoHotel.codigo + "')\" title=\"" + reservar + "\">" + reservar + "</a></div><a onclick=\"return hs.expand(this)\" href=\"http://reservas.siron.es/admin/File.aspx?FIL_ID=" + nuevoHotel.imagen + "\" title=\"" + nuevoHotel.nombre + "\" target=\"_blank\"><img class=\"miniaturaListado\" src=\"http://reservas.siron.es/admin/File.aspx?FIL_ID=" + nuevoHotel.imagen + "&tImg=D&iW=71&iH=53\" alt=\"" + nuevoHotel.nombre + "\" /></a><h3><a href=\"javascript:verHotel(" + nuevoHotel.codigo + ")\">" + nuevoHotel.nombre + "</a>&#160;" + generarEstrellas(nuevoHotel.categoria) + "</h3><div class=\"direccion\">" + nuevoHotel.direccion + " · <a href=\"hotel.aspx?CODIGOHOTEL=" + nuevoHotel.codigo + "&amp;mapa=1\" title=\"" + verEnMapa + "\">" + verEnMapa + "</a></div><div class=\"descripcion\">" + nuevoHotel.descripcion + "</div></div>";				
        HTMLHotel = "<div class=\"cuadroHotel\"><div class=\"precioReserva\">" + precioDesde + "<br/><b>" + String(nuevoHotel.precioHotel).replace(".", ",") + " &euro;</b><a href=\"javascript:lanzarReserva('" + nuevoHotel.codigo + "'," + nuevoHotel.edadMaxBebe + ")\" title=\"" + reservar + "\">" + reservar + "</a></div><a onclick=\"return hs.expand(this)\" href=\"http://reservas.siron.es/admin/File.aspx?FIL_ID=" + nuevoHotel.imagen + "\" title=\"" + nuevoHotel.nombre + "\" target=\"_blank\"><img class=\"miniaturaListado\" src=\"http://reservas.siron.es/admin/File.aspx?FIL_ID=" + nuevoHotel.imagen + "&tImg=D&iW=71&iH=53\" alt=\"" + nuevoHotel.nombre + "\" /></a><h3><a href=\"javascript:verHotel('" + nuevoHotel.codigo + "')\">" + nuevoHotel.nombre + "</a>&#160;" + generarEstrellas(nuevoHotel.categoria) + "</h3><div class=\"direccion\">" + nuevoHotel.direccion + " · <a href=\"/hotel.aspx?CODIGOHOTEL=" + nuevoHotel.codigo + "&amp;mapa=1\" title=\"" + verEnMapa + "\">" + verEnMapa + "</a></div><div class=\"descripcion\">" + nuevoHotel.descripcion + "</div></div>";
    }

    capa.innerHTML += HTMLHotel;

}

function quitarEspacios(nombre) {
    return nombre.replace(" ", "-");
}

function incluirDivPaginacion(capa, numeroPaginas, paginaActiva) {

    capa.innerHTML = "";

    for (i = 0; i < numeroPaginas; i++) {
        if (i != paginaActiva) {
            capa.innerHTML += "<a href='javascript:actualizarListadoHoteles(" + i + ")'>" + (i + 1) + "</a> "
        } else {
            capa.innerHTML += "<span class='numeroActual'>" + (i + 1) + "</span> "
        }

    }

}

function limpiarDivPaginacion(capa) {

    capa.innerHTML = "";

}

function recargarConsulta() {
    var divHot = document.getElementById("capaHoteles");
    divHot.innerHTML = "<br/><br/><div align='center'><img src='/images/loading.gif'/><p>&nbsp;</p><p style='font-size: 14px; font-weight: bold;'>" + textoBusquedaAJAX + "</p></div>";
    divHot.style.display = "block";

    document.getElementById("ordenarNombrePrecio").style.display = "";

    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_NOCHES=" + document.getElementById("PASO1_NOCHES").value;

    parametrosBusqueda += "&PASO1_TAG=" + document.getElementById("PASO1_TAG").value;

    parametrosBusqueda += "&TIPO=" + document.getElementById("tipo").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";

    }

    parametrosBusqueda += "&lang=" + idioma + "";

    lanzarBusquedaListado();
    limpiarRadioButtonsOrden();
    //alert(parametrosBusqueda);
    //return;
}


function informarNumeroHotelesEncontrados(numero) {
    var numeroHoteles = document.getElementById("numeroHotelesEncontrados");
    var capaHoteles = document.getElementById('capaHoteles');
    if (numero > 0) {
        numeroHoteles.innerHTML = numero + ' ' + textoEncontrado;
    } else
        if (numero == -1) {
        numeroHoteles.innerHTML = textoBuscando;
        capaHoteles.innerHTML = "<br/><br/><div align='center'><img src='/images/loading.gif'/><p>&nbsp;</p><p style='font-size: 14px; font-weight: bold;'>" + textoBusquedaAJAX + "</p></div>"
    } else {
        numeroHoteles.innerHTML = textoNoEncontrado;
        capaHoteles.innerHTML = "<br/><br/><br/><br/><br/><br/><br/><div align='center'>" + textoNoEncontrado + "</div>"
    }
}
function limpiarRadioButtonsOrden() {

    var radioButtons = document.getElementsByName("id");
    for (var x = 0; x < radioButtons.length; x++) {
        radioButtons[x].checked = "";
    }
}

function buscarZonas(nombreZona) {

    var categoria;
    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_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_UBICACION=" + nombreZona;

    parametrosBusqueda += "&lang=" + idioma + "";

    window.location = "/mapaHoteles.aspx?" + parametrosBusqueda;

}
