﻿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("/rAlojamientos/include/buscAlo.xsl");
var BusquedaTerminada = false;
var semaforoResultados = true;
var semaforoFin = false;
var totalPags = 0;

function marcarFin() {
    semaforoFin = true;
    semaforoResultados = true;
}

/* 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();
    xmlDocText.getRemoteDocument("/rAlojamientos/include/ResultadosHotel.aspx?f=" + Cronometro + "&Buscar=1&Pagina=1&MaxPaginas=" + nHoteles);
}

/* 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 = xslt(xmlDocText.XMLDOMComponent, xmlDocXSL.XMLDOMComponent);
    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];
                htMapasGlobal[htMapasGlobal.length] = new hotelMarker(nodo.getAttribute("IdCbu"), nodo.getAttribute("Latitud"), nodo.getAttribute("Longitud"), nodo.getAttribute("Zona"), nodo.getAttribute("Nombre"), String.fromCharCode(htMapasGlobal.length + 65), "", "0", nodo.getAttribute("Thumb"));
                if (htMapasGlobal[htMapasGlobal.length-1].lat != 0) {
                    bounds.extend(htMapasGlobal[htMapasGlobal.length-1].LatLng);
                }
            }
        }
        else {
            GoogleDisponible = false;
        }
    }
    catch (e) {
        GoogleDisponible = false;
    }
    var s = document.getElementById("subzonas");
    if (s.options.length <= 1) {
        var zonas = xmlDocText.selectNodes("alojamientos/zonas/zona");
         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[s.options.length] = 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[s.options.length] = new Option(zonas[i].text, zonas[i].getAttribute("id"));
                }
            }             
        }
        
        if (zonas.length == 1) {
            s.options[0] = new Option("- - - - - - - - -", "undefined");
        }
    }
} /*Fin procesar resultados*/


<!-- mostramos u ocultamos y mensajes dependiendo de los resultados encontrados -->
function MostrarListadoOMensajeResultados() {
    document.getElementById("TextoBuscandoIzq").style.display = 'none';
    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();
}


/* Dejamos de buscar */
function CancelarBusqueda() {
    initSliderPrecios();
    initSliderPaginas();
    MostrarListadoOMensajeResultados()
    BusquedaTerminada = true;
}

/* Buscamos en BBDD si hay resultados (Primera Búsqueda)*/
function ProcesarResultadosBusqueda() {
    
    try {
        ProcesarResultados();
    }
    catch (e) {
        //alert(e);   'Quitamos los alert ya que por ejemplo mientras estamos buscando y enlazamos a otra pagina salta un alert con el error.
    }
    var HemosTerminado = "0"
    try {
        HemosTerminado = xmlDocText.selectNodes("alojamientos")[0].getAttribute("busquedaFinalizada");
    }
    catch (e) {
        //alert(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);
    }
}

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;
    }
 
}



var RestartPag = false;

/* Cargamos los alojamientos según los filtros, sin buscar en BBDD */

function cargarAlojamientos(RestartPaginacion) {
    if (semaforoResultados) {
        semaforoResultados = false;
        mostrarMensajeFiltrando();
        RestartPag = RestartPaginacion;
        setTimeout(cargarAlojamientos2, 100);
    }
}

function cargarAlojamientos2() {
    if (BusquedaTerminada) {
        crearxmlDocText();
        xmlDocText = new XMLRemoteRequest("xmlDocText");
        xmlDocText.async = false;
        
        var str = '';
        str += '&PreMin=' + document.getElementById("precioValue1").innerHTML;
        str += '&PreMax=' + document.getElementById("precioValue2").innerHTML;
        str += '&Nombre=' + escape(document.getElementById("txtNombreHotel").value);
        if (!RestartPag) {
            str += '&Pagina=' + document.getElementById("txtNumPagina").innerHTML;
        }
        str += '&Orden=' + document.getElementById("lAloja_orden")[document.getElementById("lAloja_orden").selectedIndex].value;
        if (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("/rAlojamientos/include/ResultadosHotel.aspx?f=" + Cronometro + "&Buscar=0&MaxPaginas=" + nHoteles + str + CatStr);
        marcarFin();
        ProcesarResultadosFiltrados();
        if (RestartPag) {
            slider.setValue(0, true, true, false);
            /* En Firefox reiniciamos el slider para que se vea bien, en Explorer no funciona y da problemas */
            if (navigator.userAgent.toLowerCase().indexOf('msie') < 0) {
                initSliderPaginas();
            }
            RestartPaginacion();
        }
    }
    ocultarMensajeFiltrando();
}

/*  Prepara el objeto xmlDocText para una nueva petición AJAX */

function crearxmlDocText() {
    if (xmlDocText) {
        xmlDocText = null;
    }
}

/* Mensajes de Filtrando*/

function mostrarMensajeFiltrando() {
    document.getElementById("MsjFiltrando").style.display = '';
}

function ocultarMensajeFiltrando() {
    document.getElementById("MsjFiltrando").style.display = 'none';
}

/* Funciones auxiliares */

function xslt(xmlDoc, xslDoc) {
    var transform;
    if (typeof ActiveXObject != 'undefined') {
        transform = xmlDoc.transformNode(xslDoc);
    }
    else {
        var xsl = new XSLTProcessor();
        xsl.importStylesheet(xslDoc);
        var fragment = xsl.transformToFragment(xmlDoc, document);
        transform = (new XMLSerializer()).serializeToString(fragment);
    }
    return transform;
}

function MostrarEstadisticas() {
    var Mensaje = '';
    var contador;
    for (contador in Estadisticas) {
        Mensaje += Estadisticas[contador] + '\n';
    }
    alert(Mensaje);
}

function cambiar(id){
    document.getElementById(id).style.display = 'block';
}





/* Funciones/objetos para controlar la paginacion */
/* Clase control paginacion */
function controlPaginacion() {
    this.idsIncrementadores = new Array();
    this.tiposIncrementadores = new Array();
    this.totalIncrementadores = 0;
    
    this.idsSelects = new Array();
    this.totalSelects = 0;
    
    this.idsMaxPagina = new Array();
    this.totalMaxPagina = 0;
    
    this.agregaIncrementador = agregaIncrementador;
    this.agregaSelect = agregaSelect;
    this.agregaMaxPagina = agregaMaxPagina;
}

function agregaIncrementador(id, tipo) {
    this.idsIncrementadores[this.totalIncrementadores] = id;
    this.tiposIncrementadores[this.totalIncrementadores] = tipo;
    this.totalIncrementadores += 1;
}

function agregaSelect(id) {
    this.idsSelects[this.totalSelects] = id;
    this.totalSelects += 1;
}

function agregaMaxPagina(id) {
    this.idsMaxPagina[this.totalMaxPagina] = id;
    this.totalMaxPagina += 1;
}

function inicializarSelectPaginas(totalPaginas) {
    for (i = 0; i < objPaginacion.totalSelects; i++) {
        obj = document.getElementById(objPaginacion.idsSelects[i]);
        obj.options.length = 0;
        for(var j=1; j<=totalPaginas; j++) {
            obj.options[obj.length] = new Option(j , j );
        }
        if (totalPaginas == 0)obj.options[0] = new Option('-' , 0 );
        obj.options.value = 1;
    }
    totalPags = totalPaginas;
    actualizarPaginacion(1);
}


/* Funciones de actualizacion de la paginacion */
function actualizarPaginacion(paginaActual) {
    for (i=0; i<objPaginacion.totalMaxPagina; i++) {
        var max = parseInt(document.getElementById(objPaginacion.idsMaxPagina[i]).innerHTML);
    }
    if (paginaActual > totalPags) { paginaActual = totalPags }
    if (paginaActual <= 0) { paginaActual = 1 }
    
    txtNumPagina.innerHTML = paginaActual;
    ResultadosMostrados = paginaActual;

    // Actualizamos los "decrementadores de pagina"
    var estilo = "hidden";
    if (paginaActual != 1) { estilo = "visible"; }
    for (i = 0; i < objPaginacion.totalIncrementadores; i++) {
        if (objPaginacion.tiposIncrementadores[i] == '-') {
            document.getElementById(objPaginacion.idsIncrementadores[i]).style.visibility = estilo;            
        }
    }

    // Actualizamos los "incrementadores de pagina"
    estilo = "visible";
    if (paginaActual == totalPags) { estilo = "hidden"; }
    for (i = 0; i < objPaginacion.totalIncrementadores; i++) {
        if (objPaginacion.tiposIncrementadores[i] == '+') {
            document.getElementById(objPaginacion.idsIncrementadores[i]).style.visibility = estilo;
        }
    }
    
    // Actualizamos los "selects de pagina"
    for (i = 0; i < objPaginacion.totalSelects; i++) {
        document.getElementById(objPaginacion.idsSelects[i]).selectedIndex = paginaActual-1;
    }
    cargarAlojamientos(false);
}

function cambiarPagina(obj) {
    actualizarPaginacion(obj.selectedIndex+1);
}

function sumarPagina(incremento) {
    var numPag = parseInt(document.getElementById("txtNumPagina").innerHTML);
    if (incremento == '+') {
        actualizarPaginacion(numPag + 1);
    }
    else {
        actualizarPaginacion(numPag - 1);                
    }
}
