﻿//function filtroHoteles() {
//    this.Cronometro = 0;
//    this.resultadosPorPagina = 10;
//    this.TiempoMaximoBusqueda = 3000;
//    this.parametrosXSL = new Array();
//    this.sliderPrecio;
//}
//      

var Cronometro;
var Estadisticas = new Array();
var categorias = new Array();
var PrecioMax = 0;
var PrecioMin = 0;
var NumResDevueltos = 0;
var NumResTotales = 0;
var GoogleDisponible = true;
var InicioBusqueda = (new Date()).getTime();
var xmlDocText;
var xmlDocXSL = new XMLRemoteRequest("xmlDocXSL");
xmlDocXSL.getRemoteDocument("/hotels/include/xsl/buscAlo.aspx");
var BusquedaTerminada = false;
var semaforoResultados = true;
var semaforoFin = false;
var totalPags = 0;

function marcarFin() {
    semaforoFin = true;
    semaforoResultados = true;
}

/* Inicializacion de elementos */
function initElements() {
    document.getElementById("FiltroListado").style.display = "";
    //document.getElementById("BuscandoAlojamientos").style.display = "";
}


/* Comprobamos los resultados periodicamente sin filtrar */

function ComprobarResultados() {
    crearxmlDocText();
    xmlDocText = new XMLRemoteRequest("xmlDocText");
    xmlDocText.async = true;
    xmlDocText.onreadystatechange = new Function("ProcesarResultadosBusqueda();");
    Cronometro = (new Date()).getTime();
    var orden = '&Orden=' + document.getElementById("lAloja_orden")[document.getElementById("lAloja_orden").selectedIndex].value;
    var Cat = '&cat=';
    var CatStr = '-1';
    var LCat = document.getElementsByName("LCategorias");
    var LCatTodas = document.getElementById("LCategorias_Todas");
    for (var x = 0; x < LCat.length; x++) {
        if ((LCat[x].checked || LCatTodas.checked) && !LCat[x].disabled)
            CatStr += ',' + LCat[x].id.replace('LCategorias_', '');
    }
    Cat += CatStr;
    xmlDocText.getRemoteDocument("/hotels/include/ResultadosHotel.aspx?f=" + Cronometro + "&Buscar=1&Pagina=1&MaxPaginas=" + nHoteles + orden + Cat);
}

/* Procesamos los resultados de la búsqueda, independientemente de si hemos buscado resultados en BBDD o filtrado los que tenemos*/

function ProcesarResultados() {
    var TiempoPeticion = (new Date()).getTime() - Cronometro;
    Estadisticas.push("Peticion Ajax: " + TiempoPeticion + " ms");
    NumResDevueltos = 0;
    if (xmlDocText.selectNodes("alojamientos/resultados").length > 0) {
        NumResDevueltos = xmlDocText.selectNodes("alojamientos/resultados")[0].getAttribute("filtrados");
    }
    NumResTotales = xmlDocText.selectNodes("alojamientos")[0].getAttribute("Totales");
    var TiempoServer = xmlDocText.selectNodes("alojamientos")[0].getAttribute("tiempoServer");
    PrecioMin = 1 * xmlDocText.selectNodes("alojamientos")[0].getAttribute("PrecioMin");
    PrecioMax = 1 * xmlDocText.selectNodes("alojamientos")[0].getAttribute("PrecioMax");
    if (NumResTotales > 0) {
        document.getElementById("ResMostrados").innerHTML = NumResTotales;
        document.getElementById("ResMostradosFiltro").innerHTML = NumResDevueltos;
    }
    
    Estadisticas.push("Procesamiento Server [" + NumResDevueltos + "/" + NumResTotales + "]: " + TiempoServer + "ms");
    Cronometro = (new Date()).getTime();
    var Resultado = xsltTransform(xmlDocText.XMLDOMComponent, xmlDocXSL.XMLDOMComponent, parametrosXSL);
    TiempoPeticion = (new Date()).getTime() - Cronometro;
    Estadisticas.push("Procesamiento XSL [" + NumResDevueltos + "/" + NumResTotales + "]: " + TiempoPeticion + "ms");
    
    if (1 * NumResDevueltos > 0) // && Resultado != document.getElementById("ListadoAlojamientos").innerHTML) 
    {
        document.getElementById("ListadoAlojamientos").style.display = "block";
        document.getElementById("BuscandoAlojamientos").style.display = "none";
        document.getElementById("ListadoAlojamientos").innerHTML = Resultado;
        document.getElementById("MensajeSinResultados").style.display = "none";  
    }
    else 
    {
        if (1 * NumResDevueltos == 0 )
        {
            document.getElementById("ListadoAlojamientos").style.display = "none";  
           // document.getElementById("MensajeSinResultados").style.display = "block";  
        }
    }

    /* Reiniciamos la hashtable con los mapas cargados*/
    document.getElementById("map2Global").style.display = 'none';
    try {
        if (GBrowserIsCompatible()) {
            htMapas = new Array();
            htMapasGlobal = new Array();
            bounds = new GLatLngBounds();
            for (var i = 0; i < xmlDocText.selectNodes("alojamientos/aloja").length;i++) {
                var nodo = xmlDocText.selectNodes("alojamientos/aloja")[i];
                var link = "/fichaProducto/fichaProducto.aspx?tipo=A&prov=" + nodo.getAttribute("Proveedor") + "&CodMant=" + nodo.getAttribute("Codigo") + "&CodZon=" + nodo.getAttribute("IdZon");
                htMapasGlobal[htMapasGlobal.length] = new hotelMarker(nodo.getAttribute("IdCbu"), nodo.getAttribute("Latitud"), nodo.getAttribute("Longitud"), nodo.getAttribute("Zona"), nodo.getAttribute("Nombre"), "", "", "0", nodo.getAttribute("Thumb"), link);
                if (htMapasGlobal[htMapasGlobal.length-1].lat != 0) {
                    bounds.extend(htMapasGlobal[htMapasGlobal.length-1].LatLng);
                }
            }
        }
        else {
            GoogleDisponible = false;
        }
    }
    catch (e) {
        GoogleDisponible = false;
    }

    if (document.getElementById("subzonas")) {
        var s = document.getElementById("subzonas");
        if (s.options.length <= 1) {

            var zonas = xmlDocText.selectNodes("alojamientos/zonas/zona");
            if (zonas.length == 1) {
                s.options[0] = new Option("- - - - - - - - -", "undefined");
            }

            if (navigator.userAgent.toLowerCase().indexOf('msie') < 0) //en firefox leemos el contenido del nodo con .textContent y en explorer con .text
            {
                for (var i = 0; i < zonas.length; i++) {
                    if (zonas[i].textContent != null && zonas[i].textContent != '' && zonas[i].textContent != ' ') {
                        s.options[i] = new Option(zonas[i].textContent, zonas[i].getAttribute("id"));
                    }
                }
            } else {
                for (var i = 0; i < zonas.length; i++) {
                    if (zonas[i].text != null && zonas[i].text != '' && zonas[i].text != ' ') {
                        s.options[i] = new Option(zonas[i].text, zonas[i].getAttribute("id"));
                    }
                }
            }
        }
    }
    go_decoding();
    go_decoding();
} /*Fin procesar resultados*/


/* Dejamos de buscar */
function CancelarBusqueda() {
    initSlider();
    RestartPaginacion();
    MostrarListadoOMensajeResultados()
    BusquedaTerminada = true;
}

/* Buscamos en BBDD si hay resultados (Primera Búsqueda)*/
function ProcesarResultadosBusqueda() {
    try {
        ProcesarResultados();
    }
    catch (e) {
        alert(e);
    }
    var HemosTerminado = "0"
    try {
        HemosTerminado = xmlDocText.selectNodes("alojamientos")[0].getAttribute("busquedaFinalizada");
    }
    catch (e) {
    }
    if (HemosTerminado == "1" || TimeOutBusqueda()) {
        CancelarBusqueda();
    }
    else {
        setTimeout(ComprobarResultados, tBusquedas);
    }
}

/* Devuelve true si ha habido un TimeOut en la búsqueda*/

function TimeOutBusqueda() {
    return (InicioBusqueda + TiempoMaximoBusqueda < (new Date()).getTime());
}

/* Filtramos los resultados ya obtenidos */
function ProcesarResultadosFiltrados() {
    if (semaforoFin) {
        try {
            ProcesarResultados();
            MostrarListadoOMensajeResultados();
        }
        catch (e) {
            alert(e);
        }
    }
    else {
        setTimeout(ProcesarResultadosFiltrados, 1000);
    }
}


var RestartPag = false;

/* Cargamos los alojamientos según los filtros, sin buscar en BBDD */
function cargarAlojamientos(RestartPaginacion) {
    if (semaforoResultados) {
        semaforoResultados = false;
        mostrarMensajeFiltrando(true);
        RestartPag = RestartPaginacion;
        setTimeout(cargarAlojamientos2, 100);
    }
}

function cargarAlojamientos2() {
    if (BusquedaTerminada) {
        crearxmlDocText();
        xmlDocText = new XMLRemoteRequest("xmlDocText");
        xmlDocText.async = false;
        
        var str = '';
        str += '&PreMin=' + eval(funcSliderPrecioMin);
        str += '&PreMax=' + eval(funcSliderPrecioMax);
        str += '&Nombre=' + encodeURIComponent(document.getElementById("txtNombreHotel").value);
        if (!RestartPag) {
            str += '&Pagina=' + objPaginacion.paginaSeleccionada;
        }
        str += '&Orden=' + document.getElementById("lAloja_orden")[document.getElementById("lAloja_orden").selectedIndex].value;
        
        if (document.getElementById("subzonas") && document.getElementById("subzonas").selectedIndex > 0)
        {
            str += '&subzona=' + document.getElementById("subzonas")[document.getElementById("subzonas").selectedIndex].value;
        }
        str += '&Cat=';
        var CatStr = '-1';
        var LCat = document.getElementsByName("LCategorias");
        var LCatTodas = document.getElementById("LCategorias_Todas");
        for (var x = 0; x < LCat.length; x++) {
            if ((LCat[x].checked || LCatTodas.checked) && !LCat[x].disabled)
                CatStr += ',' + LCat[x].id.replace('LCategorias_', '');
        }
        Cronometro = (new Date()).getTime();
        semaforoFin = false;
        xmlDocText.getRemoteDocument("/hotels/include/ResultadosHotel.aspx?f=" + Cronometro + "&Buscar=0&MaxPaginas=" + nHoteles + str + CatStr);
        marcarFin();
        ProcesarResultadosFiltrados();
        if (RestartPag) {
            RestartPaginacion();
        }
    }
    mostrarMensajeFiltrando(false);
}

/*  Prepara el objeto xmlDocText para una nueva petición AJAX */
function crearxmlDocText() {
    if (xmlDocText) {
        xmlDocText = null;
    }
}


/* mostramos u ocultamos y mensajes dependiendo de los resultados encontrados  */
function MostrarListadoOMensajeResultados() {
    document.getElementById("TextoBuscandoIzq").style.display = 'none';
    document.getElementById("foundResults").style.display = '';
    if (NumResTotales <= 0) {
        // Sin Resultados Totales
        document.getElementById("FiltroHotelesIzq").style.display = "none";
        document.getElementById("FiltroHotelesSup").style.display = "none";
        document.getElementById("FiltroHotelesInf").style.display = "none";
        document.getElementById("ResMostrados").innerHTML = NumResTotales;
        document.getElementById("ResMostradosFiltro").innerHTML = NumResDevueltos;
    }
    else {
        // Con Resultados Totales
        document.getElementById("FiltroHotelesIzq").style.display = '';
        document.getElementById("FiltroHotelesSup").style.display = '';
        document.getElementById("FiltroHotelesInf").style.display = '';
    }
    
    if (NumResDevueltos*1 == 0) {
        /* Sin Resultados  aplicando Filtro*/
        document.getElementById("MensajeSinResultados").style.display = 'block';
        document.getElementById("BuscandoAlojamientos").style.display = 'none';
    }
    else {
        /* Con Resultados aplicando Filtro*/
        document.getElementById("MensajeSinResultados").style.display = 'none';
        document.getElementById("BuscandoAlojamientos").style.display = 'none';
    }
    ComprobarCategorias();
}


/* Mensajes de Filtrando */
function mostrarMensajeFiltrando(mostrar) {
    if (mostrar) document.getElementById("MsjFiltrando").style.display = ''; else document.getElementById("MsjFiltrando").style.display = 'none';
}


/* Inicializacion de los Slider*/
function initSlider() {
    eval(idSliderPrecioObj).init(PrecioMin,PrecioMax);
}

/* Paginación */
function RestartPaginacion() {
    if ((NumResDevueltos % nHoteles) != 0) {
        numPags = 1 + ((NumResDevueltos  - (NumResDevueltos % nHoteles)) /  nHoteles);
    }
    else {
        numPags = NumResDevueltos / nHoteles;
    }
    objPaginacion.inicializarSelectPaginas(numPags);
}


/*Categorias*/
function ComprobarCategorias() {
    cargaCategorias(xmlDocText);
    var ListBoxs = document.getElementsByName("LCategorias");
    for (i = 0; i < ListBoxs.length;i++) {
        var categoria = ListBoxs[i].id.substring(ListBoxs[i].id.indexOf("_") + 1);
        if (!categorias[categoria]) {
            ListBoxs[i].style.display = 'none';
            document.getElementById(ListBoxs[i].id + "Label").style.display = 'none';
        }
    }
}

function cargaCategorias(xmlDocText) {
    var Cat = xmlDocText.selectNodes("alojamientos")[0].getAttribute("Categorias").split(",");
    for (var i = 0; i < Cat.length; i++) {
        categorias[Cat[i]] = true;
    }
}

function CheckCategorias(todas,checked) {    
    var ListBoxs = document.getElementsByName("LCategorias");
    if (todas == true)
    {
        if (checked == false) return;
        for (i = 0; i < ListBoxs.length;i++) 
        {
            var categoria = ListBoxs[i];
            if (categoria.style.display != 'none') categoria.checked = false;
        }
    }
    else
    {
       document.getElementById("LCategorias_Todas").checked = false;
    }
 
}



/* Estádisticas */
function MostrarEstadisticas() {
    var Mensaje = '';
    var contador;
    for (contador in Estadisticas) {
        Mensaje += Estadisticas[contador] + '\n';
    }
    alert(Mensaje);
}


/*mostrarCombinaciones*/

function showOtherCombi(id, countCombis, idDisplay, msj1, msj2) {
    for (i = 2; i <= countCombis; i++) {
        var dv = document.getElementById(id + "_" + i);
        if (dv && dv.style.display == 'none') {
            dv.style.display = '';
        } else {
            if (dv && dv.style.display != 'none') dv.style.display = 'none';
        }

    }
    if (document.getElementById(id + '_' + countCombis).style.display == 'none') {
        document.getElementById(idDisplay).innerHTML = msj1;
        document.getElementById(idDisplay).className = 'otherCombi';
    } else {
        document.getElementById(idDisplay).innerHTML = msj2;
        document.getElementById(idDisplay).className = 'otherCombi2';
    }
}
