diff --git a/img/blue-bus-180-hi.png b/img/blue-bus-180-hi.png new file mode 100644 index 0000000..24abfec Binary files /dev/null and b/img/blue-bus-180-hi.png differ diff --git a/img/relojRojo.png b/img/relojRojo.png new file mode 100644 index 0000000..3f58103 Binary files /dev/null and b/img/relojRojo.png differ diff --git a/js/index.js b/js/index.js index 1b16c78..816d867 100644 --- a/js/index.js +++ b/js/index.js @@ -4769,8 +4769,8 @@ function imgConverter(url) { trueUrl = 'https://www.emtusahuelva.com/' + url } } else { - if (url.indexOf('http://www.emtusahuelva') != 1) { - trueUrl = url.replace('http', 'https') + if (url.indexOf('http://www.emtusahuelva') == 0) { + trueUrl = url.replace('http://', 'https://') } else { trueUrl = url } diff --git a/slick/index.js b/slick/index.js deleted file mode 100644 index 1b16c78..0000000 --- a/slick/index.js +++ /dev/null @@ -1,6227 +0,0 @@ -//Variables -var urlDatos = 'https://datos.emtusahuelva.es/' -var urlMapas = 'https://osm.tecnosis.net/' -var urlRutas = 'https://osrm.tecnosis.net/' -var urlNomin = 'https://nominatim.tecnosis.net/' -var urlSrch = 'https://katon.tecnosis.net/api?' -var version = parseFloat(0.35).toFixed(2); -var tiempoRecargaMilis = 15000; -var servidor = 's=0'; -var storage; -var online = true; -var plataforma = "web"; -var lineaSelecionada; -var codParadaMasCercana = null; var codParadaMasCercana2 = null; -String.prototype.toHHorMMorSS = function () { - var time; - var sec_num = parseInt(this, 10); - var hours = Math.floor(sec_num / 3600); - var minutes = Math.floor((sec_num - (hours * 3600)) / 60); - var seconds = sec_num - (hours * 3600) - (minutes * 60); - - hours = hours - minutes = ("0" + minutes).slice(-2); - seconds = ("0" + seconds).slice(-2); - - if (hours > 00) { - if (hours == 1) { - time = '1 hora ' - } else { - time = hours + ' horas ' - } - time += minutes + ' min.'; - } else if (minutes != "00") { - time = minutes + ' min.'; - } else if (parseInt(seconds) > 0) { - //time = 'Llegando…'; - time = "Próxima Llegada" - } else { - time = 'En Parada';// + '(' + seconds + 'seg)' - } - return time; -} -String.prototype.toHHMMorMMSS = function () { - var time; - var sec_num = parseInt(this, 10); - var hours = Math.floor(sec_num / 3600); - var minutes = Math.floor((sec_num - (hours * 3600)) / 60); - var seconds = sec_num - (hours * 3600) - (minutes * 60); - - hours = ("0" + hours).slice(-2); - minutes = ("0" + minutes).slice(-2); - seconds = ("0" + seconds).slice(-2); - - if (hours == "00") { - time = minutes + 'm ' + seconds + "s"; - } else { - time = hours + 'h ' + minutes + 'm '; - } - return time; -} -String.prototype.toHHMMSS = function () { - var sec_num = parseInt(this, 10); - var hours = Math.floor(sec_num / 3600); - var minutes = Math.floor((sec_num - (hours * 3600)) / 60); - var seconds = sec_num - (hours * 3600) - (minutes * 60); - - if (hours < 10) { - hours = "0" + hours; - } - if (minutes < 10) { - minutes = "0" + minutes; - } - if (seconds < 10) { - seconds = "0" + seconds; - } - var time = hours + ':' + minutes + ':' + seconds; - return time; -} -Array.prototype.unique = function (a) {//array sin repetidos - return function () { return this.filter(a) } -}(function (a, b, c) { return c.indexOf(a, b + 1) < 0 }); -(function ($) { - $.each(['show', 'hide'], function (i, ev) { - var el = $.fn[ev]; - $.fn[ev] = function () { - this.trigger(ev); - return el.apply(this, arguments); - }; - }); -})(jQuery); -function toRadians(a) { - return (a * Math.PI / 180.0) -} -function pad(num, size) { - var s = num + ""; - while (s.length < size) s = "0" + s; - return s; -} -function getSeconds(horaA, horaB) { - var arrA = replaceAll(replaceAll(horaA, "/", " "), ":", " ").split(" ") - var arrB = replaceAll(replaceAll(horaB, "/", " "), ":", " ").split(" ") - var fechaA = new Date(arrA[2], parseInt(arrA[1]) - 1, arrA[0], arrA[3], arrA[4], arrA[5], 0) - var fechaB = new Date(arrB[2], parseInt(arrB[1]) - 1, arrB[0], arrB[3], arrB[4], arrB[5], 0) - var cambio = false; - if (fechaA.getTime() > fechaB.getTime()) { - var fechacop = fechaA - fechaA = fechaB - fechaB = fechacop - cambio = true; - } - calculo = (fechaB.getTime() - fechaA.getTime()) / 1000 - - return calculo -} -function replaceAll(text, busca, reemplaza) { - while (text.toString().indexOf(busca) != -1) { - text = text.toString().replace(busca, reemplaza); - } - return text; -} -function distanciaMetros(lat1, lon1, lat2, lon2) { - var R = 6371e3; // metres - var φ1 = toRadians(lat1); - var φ2 = toRadians(lat2); - var Δφ = toRadians((lat2 - lat1)); - var Δλ = toRadians((lon2 - lon1)); - - var a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) + - Math.cos(φ1) * Math.cos(φ2) * - Math.sin(Δλ / 2) * Math.sin(Δλ / 2); - var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); - - var d = R * c; - return d -} -function CalculartiempoNormal(distancia, velocidad) { - var distmetros = 1; - var velocidadKilometros = 0.277777777777777777777777777777777777; - // calculamos tiempo en segundos - segundos = (distancia * distmetros) / (velocidad * velocidadKilometros); - // convert to hours, minutes, seconds - return segundos; -} -//////////////////////////////////////////////////////////////////////////FUNCIONES GENERALES//////////////////////////////////////////////////// -//#region general -function CheckPlataforma() { - if (typeof cordova != 'undefined') { - plataforma="cordova" - } -} -function SinConexion(restrictivo) { - //TODO: - if (restrictivo) { - LanzarSwalBasico("Sin Conexion", "Esta aplicación requiere conexión a internet para obtener datos importantes. Por favor active Wi-Fi o datos móviles e inténtelo de nuevo.") - $("#loadText").text("Esperando acceso a Internet") - $(".spinner") - } else { - $("#sinInternet").removeClass("conectado") - } -} -function ProblemaConexion(tipo, visible, texto) { - //TODO:Mejorar esta zona, porfa no uses if, pon un switch - if (tipo == 'CRASH') { - LanzarSwalBasico("Poblema al Conectar", "Ha ocurrido un problema al recibir datos del servidor, es posible que se encuentre en mantenimiento, vuelva a intentarlo más tarde y perdone las molestias ocasionadas") - $("#loadText").text("Por favor intentelo más tarde") - } else if (tipo == 'TIMEOUT') { - LanzarSwalBasico("Servidor Ocupado", "El servidor esta tardando demasiado en responder, puede encontrarse saturado debido a gran demanda por los usuarios, vuelva a intentarlo más tarde") - $("#loadText").text("Servidor ocupado, reintenteló más tarde") - } else if (tipo == 'DATOSCORRUPTOS') { - LanzarSwalBasico("Problema de compilación", texto) - } else { - LanzarSwalBasico("Error Inesperado", "Ha ocurrido un error, disculpe las molestias") - } -} -function AbrirMenu() { - $('#panelMenu').trigger('create'); - $('#' + $.mobile.activePage.attr('data-url')).append($('#panelMenu')); - $('#panelMenu').panel().panel("open"); -} -function AbrirPanel(idPanel) { - $('#' + idPanel).panel().panel('open'); -} -function CerrarPanel(idPanel) { - $('#' + idPanel).panel().panel('close'); -} -function ColorLuminance(hex, lum) { - if (hex.indexOf("rgb") > -1) { - var hex_rgb = hex.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); - function hexa(x) { return ("0" + parseInt(x).toString(16)).slice(-2); } - if (hex_rgb) { - hex = "#" + hexa(hex_rgb[1]) + hexa(hex_rgb[2]) + hexa(hex_rgb[3]); - } - } - // validate hex string - hex = String(hex).replace(/[^0-9a-f]/gi, ''); - if (hex.length < 6) { - hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; - } - lum = lum || 0; - - // convert to decimal and change luminosity - var rgb = "#", c, i; - for (i = 0; i < 3; i++) { - c = parseInt(hex.substr(i * 2, 2), 16); - c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16); - rgb += ("00" + c).substr(c.length); - } - - return rgb; -} -function ObtenerAbreviaturaMargen(codigo, backColor, foreColor) { - return '' + codigo + '' -} -function GetSeconds(horaA, horaB) { - var arrA = ReplaceAll(ReplaceAll(horaA, "/", " "), ":", " ").split(" ") - var arrB = ReplaceAll(ReplaceAll(horaB, "/", " "), ":", " ").split(" ") - var fechaA = new Date(arrA[2], parseInt(arrA[1]) - 1, arrA[0], arrA[3], arrA[4], arrA[5], 0) - var fechaB = new Date(arrB[2], parseInt(arrB[1]) - 1, arrB[0], arrB[3], arrB[4], arrB[5], 0) - var cambio = false; - if (fechaA.getTime() > fechaB.getTime()) { - var fechacop = fechaA - fechaA = fechaB - fechaB = fechacop - cambio = true; - } - calculo = (fechaB.getTime() - fechaA.getTime()) / 1000 - - return calculo -} -function tiempoNormal(seconds, permitir) { - var returnTiempo = "" - seconds = seconds.toString() - if (verHoraLlegada || permitir) { - returnTiempo = seconds.toHHMMorMMSS() - var tiempo = seconds.toHHMMSS().split(":") - var horaActual = new Date() - horaActual.setSeconds(horaActual.getSeconds() + parseInt(tiempo[2])); - horaActual.setMinutes(horaActual.getMinutes() + parseInt(tiempo[1])); - horaActual.setHours(horaActual.getHours() + parseInt(tiempo[0])); - - returnTiempo = " (" + pad(horaActual.getHours(), 2) + ":" + pad(horaActual.getMinutes(), 2) + ")" - } - return returnTiempo -} -function ReplaceAll(text, busca, reemplaza) { - text = text.toString() - while (text.indexOf(busca) != -1) { - text = text.replace(busca, reemplaza); - } - return text; -} -function BlinkElement() { - return window.setInterval(function () { - $('.blink').fadeTo('slow', 0.1).fadeTo('slow', 1.0); - }, 1000); -} -function LanzarSwalBasico(titulo, texto) { - Swal.fire({ - title: titulo, - text: texto, - allowOutsideClick: false, - }); -} -//#endregion general -///////////////////////////////////////////////////////////////////FUNCIONES DE CARGA E INICIALIZACION DE WEB/////////////////////////////////// -function WebCargada() { - //setTimeout(function () { - console.log("cargada") - $('body').toggleClass('loaded'); - //}, 3000); - //pruebas - //SinConexion(true) -} -CheckPlataforma() -if (plataforma == "web") { - $(document).ready(function () { - CargarApp() - }); -} else { - (function () { - "use strict"; - - document.addEventListener('deviceready', onDeviceReady.bind(this), false); - - function onDeviceReady() { - // Controlar la pausa de Cordova y reanudar eventos - document.addEventListener('pause', onPause.bind(this), false); - document.addEventListener('resume', onResume.bind(this), false); - //document.addEventListener('chcp_updateIsReadyToInstall', onUpdateReady(this), false); - //document.addEventListener('chcp_nothingToUpdate', nothingToUpdate(this), false); - // TODO: Cordova se ha cargado. Haga aquí las inicializaciones que necesiten Cordova. - var parentElement = document.getElementById('deviceready'); - codePush.sync(); - CargarApp() - - }; - - function onPause() { - // TODO: esta aplicación se ha suspendido. Guarde el estado de la aplicación aquí. - }; - - function onResume() { - // TODO: esta aplicación se ha reactivado. Restaure el estado de la aplicación aquí. - codePush.sync(); - }; - - function finalizarApp() { - - } - - //function onUpdateReady(){ - // console.log("La actualización está lista para instalar") - //} - //function nothingToUpdate() { - // console.log("Nada que actualizar, la aplicacion está actualizada") - //} - - })(); -} - -function CargarApp() { - //$("#popup").popup();//instanciamos el popup - - InicializarLocalStorage() - LimpiarLocalStorage() - LSMenuLineas = storage.get('MEN') - LSLineas = storage.get('ITI') - LSParadas = storage.get('PAR') - LSTrayectos = (storage.isSet('TRY')) ? storage.get('TRY').Tray : null - LSVerTodasLineas = storage.get('verTodasLineas') - LSReferenciadas = storage.get("Referenciadas") - LSUltLocalizacion = storage.get("lstLoc") - LSVerCercanas = (storage.isSet('LSVC')) ? storage.get('LSVC') : true - LSFecNot = storage.get("ultFN") - LSFavoritos = storage.get("FV") - if (storage.isSet("AB")) { - AlarmaBajadaActiva = true - AlarmaBajada = storage.get("AB") - } - layersSeleccionados = (storage.isSet('LS')) ? storage.get('LS') : []; - mostrarBus = (storage.isSet('MB')) ? storage.get('MB') : true; - verCorrespondencia = (storage.isSet('VC')) ? storage.get('VC') : true; - verHoraLlegada = (storage.isSet('VHL')) ? storage.get('VHL') : true; - favoritosInicio = (storage.isSet('FI')) ? storage.get('FI') : false; - vibracion = (storage.isSet('VB')) ? storage.get('VB') : true; - sonido = (storage.isSet('SN')) ? storage.get('SN') : true; - ComprobarVersion() - - //Para saber que version y plataforma estamos usando - if (storage.isSet("server")) { - servidor = storage.get("server") - } - if (storage.isSet("url")) { - urlDatos = storage.get("url") - } - InicializarListenersEventos() - ComprobarHashApp() - ObtenerNumeroNoticiasNuevas() -} -function InicializarListenersEventos() { - //TODO: Restricciones - //#region PAGESHOW - $(document).on("pageshow", "#pageInicio", function () { - //if (storage.isSet("PreguntarNoticias")) { - // if ((Date.parse(new Date()) - Date.parse(storage.get("PreguntarNoticias"))) >= 300000) { - // storage.set("PreguntarNoticias", new Date()) - // ObtenerNumeroNoticiasNuevas() - // console.log('Vuelta cuenta noticia') - // } - //} else { - // console.log('Primer cuenta noticia') - // storage.set("PreguntarNoticias", new Date()) - // ObtenerNumeroNoticiasNuevas() - //} - }); - $(document).on("pageshow", "#pageLinea", function () { - //if (!EstaRestringido(2)) { - if (storage.isSet('ITI')) { - MostrarLineasDisponibles() - } else { - LineasInexistententes() - } - //} else { - // AccesoRestringido(2) - //} - }); - $(document).on("pageshow", "#pageLineaVer", function () { - //if (!EstaRestringido(2)) { - if (storage.isSet('LineaVer')) { - DibujarLineaEsquema(); - } else { - $.mobile.changePage("#pageInicio"); - } - //} else { - // AccesoRestringido(2) - //} - }); - $(document).on("pageshow", "#pageMapa", function () { - //if (!EstaRestringido(3)) { - if (online) { - //TODO: mostrar mensajes? - //if (!storage.isSet('popMap') && !iraloc && !storage.isSet('LineaPpal')) { - // swal({ - // title: "Modo Mapa", - // text: 'Consulte lineas seleccionandolas a través del menu "Líneas" o marque su ubicación mediante el botón "Gestión"' - // }); - // storage.set('popMap', true) - //} - //TODO: haremos que el botón de localizarte parpadee cuando se sigue en tiempo real - //if (storage.isSet('popPanLoc')) { - // $("#headMapa span").removeClass('blink') - //} - try { - setTimeout(function () { - InicializarMapa(); - DibujarLineasSeleccionadas() - PedirAutobusesMapa() - }, 10);//200 - MostrarLineasMapaDisponibles() - } catch (err) { alert(err.message) }; - //setTimeout(function () { CargarSelectRutas(); }, 0); - //setTimeout(function () { CargarListaPuntosInteres() }, 10); - //setTimeout(function () { CargarListaPuntosInteresUsuario() }, 10); - //if (navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/Windows Phone/i) || navigator.userAgent.match(/edge/i) || indexModo == "cordova") { - // $('#footerMapa').addClass("footerFix"); - //} - } else { - mapaCargado = false; - $("#mapCanvas").empty() - $("#mapCanvas").html('

El uso de los mapas requiere conexión de red.
Conecte el dispositivo a una red móvil o Wifi para utilizar los mapas
') - //$("#gestionMapa").hide(); - } - //} else { - // AccesoRestringido(3) - //} - }); - $(document).on("pageshow", "#pageComoLLegar", function () { - //if (!EstaRestringido(3)) { - if (online) { - //TODO: mostrar mensajes? - //if (!storage.isSet('popMap') && !iraloc && !storage.isSet('LineaPpal')) { - // swal({ - // title: "Modo Mapa", - // text: 'Consulte lineas seleccionandolas a través del menu "Líneas" o marque su ubicación mediante el botón "Gestión"' - // }); - // storage.set('popMap', true) - //} - //TODO: haremos que el botón de localizarte parpadee cuando se sigue en tiempo real - //if (storage.isSet('popPanLoc')) { - // $("#headMapa span").removeClass('blink') - //} - try { - setTimeout(function () { - InicializarMapaComoLlegar(); - }, 10);//200 - } catch (err) { alert(err.message) }; - //setTimeout(function () { CargarSelectRutas(); }, 0); - //setTimeout(function () { CargarListaPuntosInteres() }, 10); - //setTimeout(function () { CargarListaPuntosInteresUsuario() }, 10); - //if (navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/Windows Phone/i) || navigator.userAgent.match(/edge/i) || indexModo == "cordova") { - // $('#footerMapa').addClass("footerFix"); - //} - } else { - mapaCargado = false; - $("#mapCanvas").empty() - $("#mapCanvas").html('

El uso de los mapas requiere conexión de red.
Conecte el dispositivo a una red móvil o Wifi para utilizar los mapas
') - //$("#gestionMapa").hide(); - } - //} else { - // AccesoRestringido(3) - //} - }); - $(document).on("pageshow", "#pageInfo", function () { - //if (!EstaRestringido(7)) { - ObtenerNoticias() - if (LSFecNot) { - un = new Date(LSFecNot); - if (un.getFullYear() != 1990) { - $("#ultPuls").text("" + un.getDate() + "/" + (un.getMonth() + 1) + "/" + un.getFullYear() + " " + pad(un.getHours(), 2) + ":" + pad(un.getMinutes(), 2)); - } else { - $("#ultPuls").text("Ninguno Mostrado") - } - } - //} else { - // AccesoRestringido(7) - //} - }); - $(document).on("pageshow", "#pageFavoritos", function () { - //if (!EstaRestringido(6)) { - DibujarFavoritos() - //} else { - // AccesoRestringido(6) - //} - }); - $(document).on("pageshow", "#pageAlarmaLlegada", function () { - //if (!EstaRestringido(6)) { - if (AlarmaBajadaActiva == false) { - AlarmaModoFormulario() - } else { - AlarmaModoMapa() - } - //} else { - // AccesoRestringido(6) - //} - }); - //#endregion PAGESHOW - - //#region PAGEBEFOREHIDE - $(document).on("pagebeforehide", "#pageLineaVer", function () { - window.clearInterval(idLineas); - window.clearInterval(idParadas); - - $('#ListLineasPageLineas').empty() - $('#ListLineasPageLineas').append("Cargando, por favor espere...") - - $('#headLineasVer').text(''); - $('#headLineasVer').css('text-shadow', "2px 2px white"); - $('#subHeadLineasVer').text(''); - $('#subHeadLineasVer').css('text-shadow', "1px 2px white"); - $('#verLineasContNombre').css('background-color', 'white'); - }); - $(document).on("pagebeforehide", "#pageFavoritos", function () { - window.clearInterval(idFavoritos); - }); - $(document).on("pagebeforehide", "#pageMapa", function () { - window.clearInterval(idMapa); - window.clearInterval(idMapaParada); - }); - $(document).on("pagebeforehide", "#pageBuscarParada", function () { - window.clearInterval(idBusqueda); - }); - //#endregion PAGEBEFOREHIDE - $(document).on("pagecontainerbeforechange", function (e, data) { - if ($("#ventanaAyuda").css('display') == "block") { - $("#ventanaAyuda").hide(); - } - }); - //#region CLICK - $(".menuButtonGest").click(function () { - AbrirPanel($(this).attr('panel')); - }); - $(".btnCerrarPanel").click(function () { - CerrarPanel($(this).attr('panel')); - }); - $(".slide").click(function () { - $("#" + $(this).getAttribute('toogle')).slideToggle(); - }); - $(".menuButtonMenu").click(function () { - //AbrirMenu() - $.mobile.changePage('#pageInicio'); - }) - $(".menuAyuda").click(function () { - MostrarAyuda($(this).getAttribute('ayuda')) - }) - var oldVal; - $("#txtBuscar").on("change paste keyup", function () { - var val = this.value; - continuar = false; - if (val !== oldVal) { - oldVal = val; - continuar = true; - } - if (continuar) { - //TODO: terminar la parte de paradas cercanas en busqueda - //if (this.value.length > 0) { - // $("#contParCercanasBusqueda").hide() - //} else { - // $("#contParCercanasBusqueda").show() - //} - if (this.value.length == 2 && (this.value.toLowerCase() == "*a" || this.value.toLowerCase() == "*n")) { - var aaa = this.value - setTimeout(function () { RealizarBusqueda(aaa) }, 100); - //TODO: Implementar Konami Code - //} else if (this.value.toLowerCase() == "*inspector") { - // if (!storage.isSet("mdInspector")) { - // storage.get("mdInspector", false) - // } - // if (storage.get("mdInspector") == true) { - // storage.set("mdInspector", false) - // sweetAlert("Inspector", "Se ha desactivado el modo Inspector"); - // $("#menuIns").hide() - // $("#ins").hide() - // //$("#errorApp").show() - // } else if (storage.get("mdInspector") == false) { - // storage.set("mdInspector", true) - // swal({ - // title: "Inspector", - // text: "Se ha activado el modo Inspector", - // confirmButtonText: "Continuar" - // }, function () { $.mobile.changePage("#pageIns"); }); - // $("#menuIns").show() - // $("#ins").show() - // PedirConductores() - // //$("#errorApp").show() - // } - //} else if (this.value.toLowerCase() == "*verlogsi") { - // storage.set("log", true) - // sweetAlert("Log", "Se ha activado el mantenimiento de el historial de errores"); - // $("#menuError").show() - // $("#errorApp").show() - //} else if (this.value.toLowerCase() == "*verlogno") { - // storage.remove("log") - // sweetAlert("Log", "Se ha desactivado el mantenimiento de el historial de errores"); - // $("#menuError").hide() - // $("#errorApp").hide() - //} else if (this.value.toLowerCase() == "modopruebasi") { - // storage.set('modoPrueba', true) - // modoPrueba = true - // $("a[onclick='AbrirMenu()']").css('background-color', '#fff1a8') - // $("#mpVersion").show(); - // $("#recEsquema").show(); - // $("#cambiarTimeout").show(); - // if (indexModo == "cordova") { - // $("#pruebaNotificacion").show() - // $("#pruebaLuminosidad").show() - // } - // sweetAlert("Modo Prueba Sí", "Modo prueba activo"); - //} else if (this.value.toLowerCase() == "modopruebano") { - // storage.set('modoPrueba', false) - // modoPrueba = false - // $("a[onclick='AbrirMenu()']").css('background-color', '#dfefff') - // $("#mpVersion").hide(); - // $("#recEsquema").hide(); - // $("#cambiarTimeout").hide(); - // if (indexModo == "cordova") { - // $("#pruebaNotificacion").hide() - // $("#pruebaLuminosidad").hide() - // } - // sweetAlert("Modo Prueba No", "Modo prueba desactivado"); - //} else if (this.value.length >= 3 && this.value.indexOf('s=') == 0 && this.value.indexOf('.') == this.value.length - 1 && storage.get('modoPrueba')) { - // var numServidor = this.value.split('=')[1] - // if (Number.isInteger(parseInt(numServidor))) { - // servidor = "s=" + numServidor - // storage.set("server", servidor.slice(0, -1)) - // swal({ - // title: "Servidor cambiado", - // text: "La aplicación redirige al servidor " + numServidor + " (si borras los datos o la caché volvera a usar el servidor por defecto)", - // confirmButtonText: "Aceptar" - // }, function () { - // $.mobile.changePage('#pageInicio'); - // storage.remove('lineas'); - // window.location.reload(); - // }); - // } - //} else if (this.value.length >= 3 && this.value.indexOf('u=') == 0 && this.value.indexOf('..') == this.value.length - 2 && storage.get('modoPrueba')) { - // urlDatos = this.value.slice(2, -2) - // storage.set("url", urlDatos) - // swal({ - // title: "Servidor cambiado", - // text: "La aplicación usa la url de datos " + urlDatos + " (si borras los datos o la caché volvera a usar la url por defecto)", - // confirmButtonText: "Aceptar" - // }, function () { - // $.mobile.changePage('#pageInicio'); - // storage.remove('lineas'); - // window.location.reload(); - // }); - //} - } else if (this.value.length >= 3) { - RealizarBusqueda(this.value.toLowerCase().trimEnd()) - } else { - $('#resultadoBusqueda').empty() - } - } - }); - $("#marcarNot").click(function () { - $(".circuloNuevo").hide(); - $.each($(".blueDome span.fechaDeNoticia"), function (f, fecha) { - $(fecha).parent().removeClass("blueDome"); - }); - $("#iniInfo").attr("data-badge", 0) - $("#iniInfo").removeClass("badge1") - LSFecNot = storage.get("NoticiaModerna") - storage.set("ultFN", LSFecNot) - - un = new Date(LSFecNot); - $("#ultPuls").text("" + un.getDate() + "/" + (un.getMonth() + 1) + "/" + un.getFullYear() + " " + pad(un.getHours(), 2) + ":" + pad(un.getMinutes(), 2)) - $(".numAvisos").text(0) - CambiarNumeroMenu(0) - }) - $("#desmarcarNot").click(function () { - LSFecNot = new Date(1990, 1, 1, 0, 0, 0) - storage.set("ultFN", LSFecNot) - $("#ultPuls").text("") - storage.remove("PreguntarNoticias") - ObtenerNumeroNoticiasNuevas() - }) - $("#btnAlarmaBajada").click(function () { CrearAlarmaBajada() }); - //#endregion CLICK - //#region checkear - if (mostrarBus == true) { - $("#switch-MostrarBus").click() - } - if (verCorrespondencia == true) { - $("#switch-VerCorrespondencias").click() - } - if (verHoraLlegada == true) { - $("#switch-VerHoraLlegada").click() - } - if (favoritosInicio == true) { - $("#switch-FavoritosIniciar").click() - $.mobile.changePage("#pageFavoritos"); - } - if (vibracion == true) { - $("#switch-Vibracion").click() - } - if (sonido == true) { - $("#switch-Sonido").click() - } - //#endregion checkear - //#region Close - $("#panelGeoloc").panel({ - open: function (event, ui) { - window.clearInterval(idMapa) - OcultarAutobuses() - }, - close: function (event, ui) { - console.log('cerrando Panel') - PedirAutobusesMapa() - DibujarCuadrosLineasSeleccionadas() - } - }); - $('#containerLineasMapa').on('show', function () { - console.log('abriendo Panel') - window.clearInterval(idMapa) - OcultarAutobuses() - }); - $('#containerLineasMapa').on('hide', function () { - console.log('cerrando Panel') - PedirAutobusesMapa() - DibujarCuadrosLineasSeleccionadas() - }); - - //#region Close - $(window).resize(function () { - if ($.mobile.activePage.attr('data-url') == 'pageInfo') { - resizeNavBar() - } - }); - - //Opciones - $("#recargar").click(function () { - Swal.fire({ - title: "Reiniciar", - text: "Reiniciar la aplicación puede ayudar a solucionar errores. ¿Desea continuar?", - showCancelButton: true, - confirmButtonColor: "#DD6B55", - confirmButtonText: "Sí", - cancelButtonText: "No" - }).then((result) => { - if (result.value == true) { - $.mobile.changePage('#pageInicio'); - window.location.reload(); - } - }) - }); - $("#borrar").click(function () { - Swal.fire({ - type: "warning", - title: "Reestablecer APP", - text: "La aplicación volverá a su estado inicial, borrando datos de localización, configuración de opciones, favoritos, rutas... ¿Está de acuerdo?", - showCancelButton: true, - confirmButtonText: "Sí", - cancelButtonText: "No" - }).then((result) => { - if (result.value == true) { - localStorage.clear() - window.location.reload(); - } - }) - }); - - //Micrófono - $("#btnMic").mousedown(function () { - $("#radar").show() - }); - $("#btnMic").mouseup(function () { - $("#radar").hide() - }); -} -function trigerChange() { - -} -/////////////////////////////////////////////////////////////////////ALMACENAMIENTO DE DATOS//////////////////////////////////////////////////// -var LSMenuLineas = null; -var LSLineas = null; -var LSParadas = null; -var LSTrayectos = null; -var LSReferenciadas = null -function InicializarLocalStorage() { - storage = $.localStorage; -} -function LimpiarLocalStorage() { - var aBorrar = [] - for (var i = 0; i < localStorage.length; i++) { - var key = localStorage.key(i); - if (key.indexOf("EBL") > -1 || key.indexOf("EPR") > -1 || key.indexOf("UTH") > -1 || key.indexOf("IBM") > -1) { - aBorrar.push(key) - } - } - for (var i = 0; i < aBorrar.length; i++) storage.remove(aBorrar[i]) -} -function ComprobarVersion() { - //Si la versión cambia o no estan los datos inicializados - if (!storage.isSet('Version') || parseFloat(storage.get('Version')) != parseFloat(version)) { - $("#loadText").text("Preparando Actualización") - $.mobile.changePage("#pageInicio"); - //Se almacenan las variables que merecen ser guardadas - //TODO - //Se limpia el storage - storage.removeAll() - //Se vuelve a inicializar - storage.set('Version', version); - } -} -function ComprobarHashApp() { - console.log("ComprobarHashApp()") - if (online) { - $("#loadText").text("Comprobando Información") - JSZipUtils.getBinaryContent(urlDatos + 'api/JQ/JSONQRYZIP/HASHLTP?i=' + Math.random() + '&' + servidor + '&p=' + plataforma + '&v=' + version, function (err, data) { - var elt = document.getElementById('jszip_utils'); - if (!err) { - try { - JSZip.loadAsync(data).then(function (zip) { return zip.file("datos.json").async("string") }) - .then(function success(text) { - try { - data = JSON.parse(text.substring(1)) - if (!storage.isSet('hshs') || data.HG != storage.get('hshs').HG) { - storage.set('hshs', data) - SolicitarDatosLineasParadasTrayecto(data) - } else if (!storage.isSet("ITI") || !storage.isSet("PAR") || !storage.isSet("TRY") || !storage.isSet("MEN") || !storage.isSet("Referenciadas")) { //por si hubiese pasado algo y no se hubiesen inicializado - storage.set('hshs', data) - SolicitarDatosLineasParadasTrayecto(data) - } else { - $("#loadText").text("Listo") - WebCargada() - } - } catch (ex) { - if (!saltaLineasStorage) { - //SolicitarLineasStorage(saltar) - saltaLineasStorage = true; - } - console.log(ex + "" + text.toString()) - ProblemaConexion("CRASH") - } - }, function error(e) { ErrorServidor('errorZip', 'CHSH01', 'ocurrencia baja') }); - } catch (e) { ErrorServidor('errorDesconocido', 'CHSH01', e) } - } else { ErrorServidor('noRespuesta', 'CHSH01', ''); return; } - }); - } else { - SinConexion(true); - } -} -var saltaLineasStorage = false; -function SolicitarDatosLineasParadasTrayecto(hashData) { - console.log("SolicitarDatosLineasParadasTrayecto()") - if (online) { - $("#loadText").text("Obteniendo Datos") - var arrayDatos = [null, null, null, null] - var arrayDatosDescargados = [false, false, false, false]; - if (storage.isSet("hshs") && hashData.HL != storage.get("hshs").HL) { - arrayDatos[0] = storage.get("ITI") - arrayDatosDescargados[0] = true; - } else { - console.log("obteniendo Lineas") - JSZipUtils.getBinaryContent(urlDatos + 'api/JQ/JSONQRYZIP/DEFLIN?i=' + Math.random() + '&' + servidor + '&p=' + plataforma + '&v=' + version, function (err, data) { - var elt = document.getElementById('jszip_utils'); - if (!err) { - try { - JSZip.loadAsync(data).then(function (zip) { return zip.file("datos.json").async("string") }) - .then(function success(text) { - try { - data = JSON.parse(text.substring(1)) - - arrayDatos[0] = data - arrayDatosDescargados[0] = true; - terminadoLin = true; - $.each(arrayDatosDescargados, function (el, estadoLin) { - if (estadoLin == false) { - terminadoLin = false; - } - }) - if (terminadoLin) { - GuardarDatosLineasParadasTrayecto(arrayDatos) - } - saltaLineasStorage = false; - } catch (ex) { - if (!saltaLineasStorage) { - //SolicitarLineasStorage(saltar) - saltaLineasStorage = true - ProblemaConexion("CRASH"); - } - console.log(ex + "" + text.toString()) - } - }, function error(e) { ErrorServidor('errorZip', 'PULL01', 'ocurrencia baja') }); - } catch (e) { ErrorServidor('errorDesconocido', 'PULL01', e) } - } else { ErrorServidor('noRespuesta', 'PULL01', ''); return; } - }); - } - if (storage.isSet("hshs") && hashData.HP != storage.get("hshs").HP) { - arrayDatos[1] = storage.get("PAR") - arrayDatosDescargados[1] = true; - } else { - console.log("obteniendo Paradas") - JSZipUtils.getBinaryContent(urlDatos + 'api/JQ/JSONQRYZIP/DEFPAR?i=' + Math.random() + '&' + servidor + '&p=' + plataforma + '&v=' + version, function (err, data) { - var elt = document.getElementById('jszip_utils'); - if (!err) { - try { - JSZip.loadAsync(data).then(function (zip) { return zip.file("datos.json").async("string") }) - .then(function success(text) { - try { - data = JSON.parse(text.substring(1)) - arrayDatos[1] = data; - arrayDatosDescargados[1] = true; - ////////////////// - terminadoPar = true; - $.each(arrayDatosDescargados, function (ep, estadoPar) { - if (estadoPar == false) { - terminadoPar = false; - } - }) - if (terminadoPar) { - GuardarDatosLineasParadasTrayecto(arrayDatos) - } - saltaLineasStorage = false; - } catch (ex) { - if (!saltaLineasStorage) { - //SolicitarLineasStorage(saltar) - saltaLineasStorage = true; - ProblemaConexion("CRASH") - } - console.log(ex + "" + text.toString()) - } - }, function error(e) { ErrorServidor('errorZip', 'PULP01', 'ocurrencia baja') }); - } catch (e) { ErrorServidor('errorDesconocido', 'PULP01', e) } - } else { ErrorServidor('noRespuesta', 'PULP01', ''); return; } - }); - } - if (storage.isSet("hshs") && hashData.HT != storage.get("hshs").HT) { - arrayDatos[2] = storage.get("TRY") - arrayDatosDescargados[2] = true; - } else { - console.log("obteniendo Trayectos") - JSZipUtils.getBinaryContent(urlDatos + 'api/JQ/JSONQRYZIP/DEFTRY?i=' + Math.random() + '&' + servidor + '&p=' + plataforma + '&v=' + version, function (err, data) { - var elt = document.getElementById('jszip_utils'); - if (!err) { - try { - JSZip.loadAsync(data).then(function (zip) { return zip.file("datos.json").async("string") }) - .then(function success(text) { - try { - data = JSON.parse(text.substring(1)) - arrayDatos[2] = data; - arrayDatosDescargados[2] = true; - ////////////////// - terminadoTray = true; - $.each(arrayDatosDescargados, function (et, estadoTra) { - if (estadoTra == false) { - terminadoTray = false; - } - }) - if (terminadoTray) { - GuardarDatosLineasParadasTrayecto(arrayDatos) - } - saltaLineasStorage = false - } catch (ex) { - if (!saltaLineasStorage) { - //SolicitarLineasStorage(saltar) - saltaLineasStorage = true; - ProblemaConexion("CRASH") - } - console.log(ex + "" + text.toString()) - } - }, function error(e) { ErrorServidor('errorZip', 'PULT01', 'ocurrencia baja') }); - } catch (e) { ErrorServidor('errorDesconocido', 'PULT01', e) } - } else { ErrorServidor('noRespuesta', 'PULT01', ''); return; } - }); - } - if (storage.isSet("hshs") && hashData.HM != storage.get("hshs").HM) { - arrayDatos[3] = storage.get("MEN") - arrayDatosDescargados[3] = true; - } else { - console.log("obteniendo Menú") - JSZipUtils.getBinaryContent(urlDatos + 'api/JQ/JSONQRYZIP/DEFMENU?i=' + Math.random() + '&' + servidor + '&p=' + plataforma + '&v=' + version, function (err, data) { - var elt = document.getElementById('jszip_utils'); - if (!err) { - try { - JSZip.loadAsync(data).then(function (zip) { return zip.file("datos.json").async("string") }) - .then(function success(text) { - try { - data = JSON.parse(text.substring(1)) - arrayDatos[3] = data; - arrayDatosDescargados[3] = true; - ////////////////// - terminadoHSH = true; - $.each(arrayDatosDescargados, function (et, estadoHSH) { - if (estadoHSH == false) { - terminadoHSH = false; - } - }) - if (terminadoHSH) { - GuardarDatosLineasParadasTrayecto(arrayDatos) - } - saltaLineasStorage = false - } catch (ex) { - if (!saltaLineasStorage) { - //SolicitarLineasStorage(saltar) - saltaLineasStorage = true; - ProblemaConexion("CRASH") - } - console.log(ex + "" + text.toString()) - } - }, function error(e) { ErrorServidor('errorZip', 'PULT01', 'ocurrencia baja') }); - } catch (e) { ErrorServidor('errorDesconocido', 'PULT01', e) } - } else { ErrorServidor('noRespuesta', 'PULT01', ''); return; } - }); - } - } else { - SinConexion(true); - } -} -function GuardarDatosLineasParadasTrayecto(dataArray) { - console.log("GuardarDatosLineasParadasTrayecto") - //Guardamos los HASH para futuro uso - $("#loadText").text("Preparando Datos") - - var linData = dataArray[0] - var parData = dataArray[1] - var tryData = dataArray[2] - var menData = dataArray[3] - storage.set('MEN', menData.Lin) - LSMenuLineas = menData.Lin - //Transformamos los datos recibidos y guardamos - if (linData.Err == null && tryData.Err == null && parData.Err == null && menData.Err == null) { - var itinerarios = [] - var listaLineasParadas - var paradas = [] - //Primero montamos el array de paradas - $.each(parData.Paradas, function (p, par) { - par.EB = [] - par.Iti = [] - paradas.push(par) - }); - storage.set("PAR", paradas) - LSParadas = paradas - var paradasDeLinea = [] - $.each(linData.Lin, function (li, linea) { - $.each(linea.Iti, function (it, itinerario) { - //TODO:Parche porque ahora viene CI y CL identico, lo ideal es que CL venga bien en el futuro - itinerario.CL = linea.Cod - //Añadimos el itinerario - //Si no tiene color especifico se coge el del padre - if (itinerario.BC == null) { - itinerario.BC = linea.BC.substring(2) - } else { - itinerario.BC = itinerario.BC.substring(2) - } - if (itinerario.FC == null) { - itinerario.FC = linea.FC.substring(2) - } else { - itinerario.FC = itinerario.FC.substring(2) - } - //Si en menu NPS viniese modificado hay que aplicarselo al itinerario, recuerda que cada vez que un hash cambie, esto se limpia - var linMenu = ObtenerMenuLinea(itinerario.Cla) - if (linMenu != null && linMenu.NPS != null) { - itinerario.NPS = linMenu.NPS - } - //lo mismo con el comentario - if (linMenu != null && linMenu.CMT != null) { - itinerario.CMT = linMenu.CMT - } - itinerarios.push(itinerario) - $.each(itinerario.Sen, function (tS, sentido) { - sentido.XY = [] - $.each(sentido.Tray, function (iit, itiTray) {//cogemos sus codigos de trayecto - $.each(tryData.Tray, function (t, tray) {//lo buscamos en la parte de trayectos - if (tray.ID == itiTray) { - AnadirCodLineaParada(tray.CP1, itinerario.Cla) - AnadirCodLineaParada(tray.CP2, itinerario.Cla) - var X = [] - var Y = [] - for (var w = 0; w < tray.XY.length; w++) { - (w % 2 == 0) ? X.push(tray.XY[w]) : Y.push(tray.XY[w]); - } - for (var w2 = 0; w2 < X.length; w2++) { - sentido.XY.push([Y[w2], X[w2]]) - } - } - }); - }); - }); - }); - }); - //Como ya tenemos las Paradas, separamos las de referencias para futuras busquedas - EncontrarParadasReferencia() - //Añadimos las paradas a la linea, para futuras busquedas. - $.each(itinerarios, function (it, itinerario) { - var pos = 0 - $.each(itinerario.Sen, function (tS, sentido) { - sentido.Par = [] - $.each(sentido.Tray, function (iit, itiTray) {//cogemos sus codigos de trayecto - - $.each(tryData.Tray, function (t, tray) {//lo buscamos en la parte de trayectos - if (tray.ID == itiTray) { - var copyPar = { Nivel: 0 } - - sentido.Par.push(ObtenerParada(tray.CP1)) - pos++ - if (iit == 0) { - sentido.Par[sentido.Par.length - 1].Nivel = 1 - } else if (pos % 5 == 0) { - sentido.Par[sentido.Par.length - 1].Nivel = 2 - } else { - sentido.Par[sentido.Par.length - 1].Nivel = 3 - } - } - }); - }); - if (itinerario.Sen.length == 1) { - sentido.Par.push(ObtenerParada(sentido.Tray[sentido.Tray - 1].CP2)) - sentido.Par[sentido.Par.length - 1].Nivel = 3 - } else if (itinerario.Sen.length == 2 && sentido.CS == 2) { - LSTrayectos = tryData.Tray - trInicio = ObtenerTrayecto(itinerario.Sen[0].Tray[0]) - trFinal = ObtenerTrayecto(itinerario.Sen[1].Tray[itinerario.Sen[1].Tray.length - 1]) - if (trInicio.CP1 != trFinal.CP2) { - sentido.Par.push(ObtenerParada(trFinal.CP2)) - sentido.Par[sentido.Par.length - 1].Nivel = 3 - } - } else if (itinerario.Sen.length == 2 && sentido.CS == 1) { - LSTrayectos = tryData.Tray - trFinInicio = ObtenerTrayecto(itinerario.Sen[0].Tray[itinerario.Sen[0].Tray.length - 1]) - trInicioVuelta = ObtenerTrayecto(itinerario.Sen[1].Tray[0]) - if (trFinInicio.CP2 != trInicioVuelta.CP1) { - sentido.Par.push(ObtenerParada(trFinInicio.CP2)) - sentido.Par[sentido.Par.length - 1].Nivel = 3 - } - } - }); - if (itinerario.Sen.length == 1) { - itinerario.NumP = itinerario.Sen[0].Par.length - } else if (itinerario.Sen.length == 2) { - itinerario.NumP = itinerario.Sen[0].Par.length + itinerario.Sen[1].Par.length - } - }); - - storage.set('TRY', tryData) - storage.set('ITI', itinerarios) - LSLineas = itinerarios - LSTrayectos = tryData.Tray - //rellenamos los menulineas con los datos que faltan, así si tengo que pintar es más comodo - var menlin = LSMenuLineas - $.each(menlin, function (l, ml) { - iti = ObtenerItinerario(ml.CL + '.' + ml.CI) - ml.FC = iti.FC - ml.BC = iti.BC - ml.Nom = iti.Nom - ml.Abr = iti.Abr - ml.Cla = iti.Cla - if (ml.CMT == null && iti.CMT != null) { - ml.CMT = iti.CMT - } - ml.NumP = iti.NumP - }) - storage.set('MEN', menlin) - LSMenuLineas = menlin - $("#loadText").text("Listo") - WebCargada() - //ComprobarFechaXml(false, false) - } else { - ErrorServidor('jsonError', 'PUSC01', 'l->' + linData.err + ", t->" + tryData.err + ', p->' + parData.err) - return null - } - - if (itinerarios != null) { - //TODO: Revisar - //ObtenerPosicionParadasEnRecorrido(); - //RellenarSelectLineaPage(data, "#selectLineaPageRutas"); - //RellenarSelectLineaPage(data, "#selectLineaAvisos"); - //RellenarSelectLineaPage(data, "#selectLineaAvisosEditar"); - //InicializarMapa(); - //if ($.mobile.activePage.attr('data-url') == 'pageLinea') { - // MostrarLineasDisponibles() - //} - } -} -function AnadirCodLineaParada(codParada, clave) { - var listaPar = LSParadas - $.each(listaPar, function (cp, parada) { - if (parada.CP == codParada && $.inArray(clave, parada.Iti) == -1) { - parada.Iti.push(clave) - } - }); - storage.set("PAR", listaPar) - LSParadas = listaPar -} -function ObtenerMenuLinea(clave) { - var lineaBuscada; - lineaBuscada = $.grep(LSMenuLineas, function (l) { - return l.CL + "." + l.CI == clave; - })[0]; - return lineaBuscada; -} -function ObtenerParada(codParada) { - var paradaBuscada; - paradaBuscada = $.grep(LSParadas, function (n) { - return n.CP == codParada; - })[0]; - - return JSON.parse(JSON.stringify(paradaBuscada)); -} -function ObtenerSentidoParada(lineaC, codParada) { - sentido = null; - codParadaIndex = 0; - parRegulacionIndex = 0; - for (var osp = 0; osp < lineaC.Sen.length; osp++) { - sen = lineaC.Sen[osp] - for (var osp2 = 0; osp2 < sen.Par.length; osp2++) { - if (sen.Par[osp2].CP == codParada) { - sentido = osp; - break; - } - } - if (sentido != null) { - break; - } - } - - return sentido + 1; -} -function ObtenerPosicionParada(lineaC, codParada) { - pos = null; - codParadaIndex = 0; - parRegulacionIndex = 0; - contador = -1 - for (var osp = 0; osp < lineaC.Sen.length; osp++) { - sen = lineaC.Sen[osp] - for (var osp2 = 0; osp2 < sen.Par.length; osp2++) { - contador++ - if (sen.Par[osp2].CP == codParada) { - pos = contador; - break; - } - } - if (pos != null) { - break; - } - } - - return pos; -} -function CrearCoche(bus, hora) { - var splitTra = bus.Tra.split('-') - return ({ - codigo: bus.CB, - codigoLinea: bus.Lin, - conductor: bus.CE, - distancia: bus.DP, - latitud: bus.XY[1], - longitud: bus.XY[0], - tiempo: GetSeconds(hora, bus.TP).toString(), - terminal: bus.CT, - clase: bus.CLA, - estado: bus.Est, - fiabilidad: bus.Fia, - itinerario: bus.Iti, - orden: bus.Ord, - sentido: bus.Sen, - TRL: bus.TRL, - aviso: bus.Avi, - orientacion: bus.OB, - trayecto: Math.abs(splitTra[0]), - posEnTrayecto: Math.abs(splitTra[1]) - }) -} -function ObtenerItinerario(n) { - var lineaBuscada; - n = n.toString();//parseamos por si fuera int - if (n && n.length > 0) { //TODO:whaat? Esto evita que intentemos dibujar una parada cuando no hay ninguna seleccionada. - if (LSLineas == null) { - localStorage.removeItem('hshs'); - LineasInexistententes() - } else { - lineaBuscada = $.grep(LSLineas, function (l) { - return l.Cla == n; - })[0]; - } - } - return lineaBuscada; -} -function ObtenerTrayecto(n) { - var trayectoBuscado; - trayectoBuscado = $.grep(LSTrayectos, function (l) { - return l.ID == n; - })[0]; - return trayectoBuscado; -} -function EncontrarParadasReferencia() { - paradasReferencias = [] - listaReferenciadas = [] - $.each(LSParadas, function (p, parada) { - if (parada.CP != parada.CPRef && $.inArray(parada.CPRef, listaReferenciadas) == -1) { - paradasReferencias.push({ Codigo: parada.CPRef, Paradas: [], Cadena: "" }) - listaReferenciadas.push(parada.CPRef) - cadena = "" - $.each(LSParadas, function (sp, subparada) { - if (subparada.CPRef == parada.CPRef) { - paradasReferencias[paradasReferencias.length - 1].Paradas.push(subparada) - cadena += subparada.CP + "|" - } - }) - paradasReferencias[paradasReferencias.length - 1].Cadena = cadena.substring(0, cadena.length - 1) - } - }) - - storage.set("Referenciadas", paradasReferencias) - LSReferenciadas = paradasReferencias -} -function EsReferenciada(idParadaRef) { - var referenciada = null - for (cont = 0; cont < LSReferenciadas.length; cont++) { - if (LSReferenciadas[cont].Codigo == idParadaRef) { - referenciada = LSReferenciadas[cont] - break; - } else { - for (cont2 = 0; cont2 < LSReferenciadas[cont].Paradas.length; cont2++) { - if (LSReferenciadas[cont].Paradas[cont2].CP == idParadaRef) { - referenciada = LSReferenciadas[cont] - break; - } - } - } - } - return referenciada -} -//Controles de errores -function LineasInexistententes() { - $('body').toggleClass('loaded'); - $.mobile.changePage("#pageInicio"); - ComprobarHashApp(); -} -//////////////////////////////////////////////////////////////GESTIONLINEAS///////////////////////////////////////////////////////////////////// -function ComprobarCambiosInformacion(h, mensaje) { - var continuar = false; - if (storage.get("hshs").HG != h && h != null) { - $.mobile.changePage("#pageInicio"); - if (mensaje) { - Swal.fire({ - title: "Advertencia", - text: "Se ha detectado una actualización de las líneas, la aplicación se va a reiniciar para aplicar los cambios", - allowOutsideClick: false - }).then((value) => { - window.location.reload(); - }); - } else { - window.location.reload(true); - } - } else { - continuar = true; - } - return continuar -} -function BuscarParadaInyeccion(EP, codigo) { - var parada = null; - parada = $.grep(EP, function (p) { - return p.Cla == codigo; - })[0] - return parada -} -function ZipToBlob(data) { - newContent = ""; - for (var i = 0; i < data.length; i++) { - newContent += String.fromCharCode(data.charCodeAt(i) & 0xFF); - } - var bytes = new Uint8Array(newContent.length); - for (var i = 0; i < newContent.length; i++) { - bytes[i] = newContent.charCodeAt(i); - } - blob = new Blob([bytes], { type: "application/zip" }) - return blob -} -function ObtenerLineaConParada(claveLI, comando, extra) { - //Esta función sirve para obtener la linea con paradas. - //Para ello comprueba si las lineas son anteriores al tiempo de recarga. - //el comando es que debe hacer después de obtener la linea - var EsParadaReferenciada; - if (extra != null) { - if (extra.paradaReferencia != null) - ParadaReferenciada = EsReferenciada(extra.paradaReferencia) - } - var idReferencia; - //TODO:Es posible que las referenciadas nunca se usen aquí - //if ((comando == 'mostrar informacion' || - // comando == 'mostrar informacion popup light' || - // comando == 'recargar informacion') && ParadaReferenciada != null) { - // //Esta es la parte que se encarga de redirigir las referenciadas, como son de varias lineas, lo optimo era pedir solo las paradas, excluyendo la linea - // //TODO: MIRAR COMO ACTUAN LAS REFERENCIADAS RESPECTO LINEA A LA QUE PERTENECEN Y TAL - // ObtenerParadasReferenciadas(storage.get('CodUltParadaPulsada') + ParadaReferenciada.Cadena, codLineas, claveLI, comando, extra) - //} else - if (storage.isSet('EBL' + claveLI) && storage.get('EBL' + claveLI) != '') { - //Esta parte se encarga de redireccionar las lineas que se piden, si la linea se obtuvo en un pequeño plazo se coge la almacenada, si no se vuelve a pedir - tiempo = Date.now() - storage.get('UTH' + claveLI); - if (tiempo >= (tiempoRecargaMilis - 500)) { - console.log("Debug: se pide linea " + claveLI) - //Si se pasan de tiempo las borramos del array y volvemos a pedir. - localStorage.removeItem('EBL' + claveLI) - SolicitarLineasConParadasStorage(claveLI, comando, extra); - } else { - console.log("Debug:ya existe la linea" + claveLI) - //Si no la obtenemos del array - LlamarFuncion(storage.get('EBL' + claveLI), comando, extra); - } - } else { - SolicitarLineasConParadasStorage(claveLI, comando, extra); - } -} -var saltaSolicitarLineasParStorage = false; -function SolicitarLineasConParadasStorage(claveLI, comando, extra) { - console.log('Debug: SolicitarLineasConParadas(' + claveLI + ',' + comando + ',' + extra + ')') - if (online) { - $.ajax({ - type: 'GET', - url: urlDatos + 'api/JQ/JSONQRYZIP/ESTLIN2|' + claveLI + '?i=' + Math.random() + '&' + servidor + '&p=' + plataforma + '&v=' + version, - dataType: 'text', - mimeType: 'text/plain; charset=x-user-defined', - retryCount: 0, - retryLimit: 5, - timeout: tiempoRecargaMilis, - success: function (data) { - JSZip.loadAsync(ZipToBlob(data)) - .then(function (zip) { - return zip.file("datos.json").async("string") - }) - .then(function success(text) { - try { - if (text.indexOf('ESTLIN') > -1) { - console.log(text) - } - data = JSON.parse(text.substring(1)) - if (ComprobarCambiosInformacion(data.HG, true)) { - storage.set('UTH' + claveLI, Date.now()) - //EMPIEZA AQUI - linea = ObtenerItinerario(claveLI) - for (var a1 = 0; a1 < linea.Sen.length; a1++) { - sentido = linea.Sen[a1] - for (var a2 = 0; a2 < sentido.Par.length; a2++) { - parada = sentido.Par[a2] - par = BuscarParadaInyeccion(data.EP, parada.CP) - EBTotal = [] - - for (var a3 = 0; a3 < par.EB.length; a3++) { - coche = par.EB[a3] - EBTotal.push(CrearCoche(coche, data.FH)) - } - parada.EB = EBTotal - } - } - linea.PC=data.PC - storage.set('EBL' + claveLI, linea); - LlamarFuncion(linea, comando, extra) - } - saltaSolicitarLineasParStorage = false; - } catch (ex) { - //TODO:que cuando de error vuelva a intentar ¿? - if (!saltaSolicitarLineasParStorage) { - if (storage.isSet('EBL' + claveLI)) { - ProblemaConexion("DATOSCORRUPTOS", false, 'El servidor ha devuelto información, pero falla algo en código:' + ex.stack) - saltaSolicitarLineasParStorage = true; - } else { - SolicitarLineasConParadasStorage(claveLI, comando, extra) - saltaSolicitarLineasParStorage = true; - } - } else { - ProblemaConexion("DATOSCORRUPTOS", false, ex.message) - } - } - }, function error(e) { - ErrorServidor('errorZip', 'LINP01', 'ocurrencia baja') - }); - }, - error: function (xmlhttprequest, textstatus, message) { - ProblemaConexion("TIMEOUT", false, message) - }, - async: true - }); - } else { - SinConexion(true); - } -} -function SolicitarParadas(cadenaParadas, funcionParada, extra) { - if (online) { - $.ajax({ - type: 'GET', - url: urlDatos + 'api/JQ/JSONQRYZIP/ESTPAR|' + cadenaParadas + '?i=' + Math.random() + '&' + servidor + '&p=' + plataforma + '&v=' + version, - dataType: 'text', - mimeType: 'text/plain; charset=x-user-defined', - retryCount: 0, - retryLimit: 5, - timeout: tiempoRecargaMilis, - success: function (data) { - JSZip.loadAsync(ZipToBlob(data)) - .then(function (zip) { - return zip.file("datos.json").async("string") - }) - .then(function success(text) { - try { - //TODO: comprobar hash - data = JSON.parse(text.substring(1)) - console.log(data) - var EPCompleto = [] - - for (var a = 0; a < data.EP.length; a++) { - var nuePar = ObtenerParada(data.EP[a].CP) - nuePar.EB = data.EP[a].EB - $.each(nuePar.EB, function (c, coche) { - coche.TP = GetSeconds(data.FH, coche.TP).toString()//.push(CrearCoche(coche, data.FH)) - }) - EPCompleto.push(nuePar) - } - - data.EP = EPCompleto - storage.set('EPR' + cadenaParadas, data) - storage.set('UTHP' + cadenaParadas, Date.now()) - LlamarFuncionParada(data, funcionParada, extra) - } catch (ex) { - //TODO: CapturarExcepciones - //if (!saltaSolicitarLineasParStorage) { - // if (storage.isSet('EPR'+cadenaParadas)) { - ProblemaConexion("DATOSCORRUPTOS", false, 'El servidor ha devuelto información, pero falla algo en código:' + ex.stack) - // // saltaSolicitarLineasParStorage = true; - // } - // //else { - // // SolicitarLineasConParadasStorage(claveLI, comando, extra) - // // saltaSolicitarLineasParStorage = true; - // //} - //} else { - // ProblemaConexion("DATOSCORRUPTOS", false, ex.message) - //} - } - }, function error(e) { - ErrorServidor('errorZip', 'LINP01', 'ocurrencia baja') - }); - }, - error: function (xmlhttprequest, textstatus, message) { - ProblemaConexion("TIMEOUT", false, message) - }, - async: false - }); - } else { - SinConexion(true); - } -} -function LlamarFuncion(linea, comando, extra) { - console.log(linea + "," + comando + "," + extra) - //Funciones que deberia hacer al obtener la línea. - switch (comando) { - case 'recargar lineaVer': - if (extra == null) { - DibujarLineaVer(linea); - } else { - DibujarLineaVer(linea, extra.Timeout) - } - break - } -} -function LlamarFuncionParada(parada, comando, extra) { - switch (comando) { - case 'ObtenerParadaEsquema': - //Obtenemos la parada principal y le añadimos los autobuses de las otras - var par = null - - if (parada.EP.length == 1) {//solo una parada llego, no se modifica y se envia - par = parada.EP[0] - } else { - //referenciada, se crea un objeto para la ocasion uniendo todas en la principal, se le añade todas las lineas para que pueda leerse, y un array de solo a las que referencia para su tratamiento - par = ObtenerParada(extra.CodParada) - p = CrearUnionReferencia(parada, extra) - par.Ref = p.Ref - par.Iti = p.Iti - par.EB = p.EB - } - htmltexto = SolicitarHTMLInformacionParadaLight(par, extra.CodParada, extra.Linea, extra.Posicion, extra.Sentido); - Swal.fire({ - html: htmltexto, - showConfirmButton: false, - customClass: 'SwalInformacionParada', - animation: !Swal.isVisible() - //showCloseButton:true - }).then((result) => { - console.log("Me han cerrado :(") - CerrarInfoDot() - window.clearInterval(idParadas) - window.clearInterval(idLineas) - if (storage.isSet('UTH' + storage.get('LineaVer'))) { - tiempo = tiempoRecargaMilis - (Date.now() - storage.get('UTH' + storage.get('LineaVer'))); - console.log("tiempo para refresco:" + tiempo) - if (tiempo > 0) { - idLineas = TimeoutRecargarLineaAutomaticamente(tiempo); - } else { - idLineas = TimeoutRecargarLineaAutomaticamente(0); - } - } else { - idLineas = TimeoutRecargarLineaAutomaticamente(0); - } - }) - idParadas = TimeoutRecargarParadaAutomaticamente(par.CP, extra.Linea, extra.Posicion, extra.Sentido) - break; - case 'ObtenerParadaMapa': - ObtenerParadaMapa(parada, comando, extra, false) - break; - case 'ObtenerParadaMapaCombi': - ObtenerParadaMapa(parada, comando, extra, true) - break; - case 'ObtenerParadaBusqueda': - ObtenerParadaBusqueda(parada, comando, extra) - break; - case 'ObtenerParadaFavoritos': - ObtenerParadaFavoritos(parada, comando, extra) - - } -} -function ObtenerParadaMapa(parada, comando, extra, combi) { - //Obtenemos la parada principal y le añadimos los autobuses de las otras - var par = null - - if (parada.EP.length == 1) {//solo una parada llego, no se modifica y se envia - par = parada.EP[0] - } else if (!combi) { - //referenciada, se crea un objeto para la ocasion uniendo todas en la principal, se le añade todas las lineas para que pueda leerse, y un array de solo a las que referencia para su tratamiento - par = ObtenerParada(extra.CodParada) - p = CrearUnionReferencia(parada, extra) - par.Ref = p.Ref - par.Iti = p.Iti - par.EB = p.EB - } - if (!combi) { - htmltexto = SolicitarHTMLInformacionParadaLight(par, extra.CodParada, extra.Linea, extra.Posicion, extra.Sentido); - } else { - htmltexto = SolicitarHTMLInformacionParadaCombi(par); - } - var m = extra.marker - var popup = m.getPopup() - if (popup == null) { - m.bindPopup(htmltexto).on('popupclose', function (e) { window.clearInterval(idMapaParada) }).openPopup(); - } else { - popup.setContent(htmltexto).openPopup(); - } - idMapaParada = TimeoutRecargarParadaMapaAutomaticamente(par.CP, extra.Linea, extra.Posicion, extra.Sentido, extra.marker) - -} -function ObtenerParadaBusqueda(parada, comando, extra, combi) { - //Obtenemos la parada principal y le añadimos los autobuses de las otras - var par = parada.EP[0] - - htmltexto = SolicitarHTMLInformacionParadaCombi(par); - idBusqueda = TimeoutRecargarParadaBusquedaAutomaticamente(par.CP); - Swal.fire({ - html: htmltexto, - showConfirmButton: false, - customClass: 'SwalInformacionParada', - animation: !Swal.isVisible() - //showCloseButton:true - }).then((result) => { - window.clearInterval(idBusqueda) - }) -} -function ObtenerParadaFavoritos(parada, comando, extra) { - //Obtenemos la parada principal y le añadimos los autobuses de las otras - var par = parada.EP[0] - - htmltexto = SolicitarHTMLInformacionParadaLight(par, extra.CodParada, extra.Linea, extra.Posicion, extra.Sentido); - window.clearInterval(idFavoritos) - idFavoritos = TimeoutRecargarParadaPulsadaFavoritosAutomaticamente(extra.index); - Swal.fire({ - html: htmltexto, - showConfirmButton: false, - customClass: 'SwalInformacionParada', - animation: !Swal.isVisible() - //showCloseButton:true - }).then((result) => { - DibujarFavoritos() - }) -} -function ObtenerAutobusesMapa(idLineas) { - tiempo = Date.now() - ultFechaBusMapa; - if (tiempo >= (tiempoRecargaMilis - 500) && storage.isSet("BMI" + idLineas)) { - DibujarAutobusesMapa(storage.get("BMI" + idLineas)) - - } else { - JSZipUtils.getBinaryContent(urlDatos + 'api/JQ/JSONQRYZIP/ESTGRAL' + idLineas + '?i=' + Math.random() + '&' + servidor + '&p=' + plataforma + '&v=' + version, function (err, data) { - var elt = document.getElementById('jszip_utils'); - if (err) { - ErrorServidor('noRespuesta', 'PUGR01', '') - return; - } else { - try { - JSZip.loadAsync(data) - .then(function (zip) { - return zip.file("datos.json").async("string") - }) - .then(function success(text) { - try { - data = JSON.parse(text.substring(1)) - coches = [] - $.each(data.EL, function (e, li) { - $.each(li.EC, function (ec, bus) { - bus.TPS = getSeconds(data.FH, bus.TPS).toString() - bus.TPF = getSeconds(data.FH, bus.TPF).toString() - }); - - var aBorrar = [] - for (var i = 0; i < localStorage.length; i++) { - var key = localStorage.key(i); - if (key.indexOf("IBM") > -1) { - aBorrar.push(key) - } - } - for (var i = 0; i < aBorrar.length; i++) storage.remove(aBorrar[i]) - - storage.set("IBM" + idLineas, data.EL) - autobusesActuales = data.EL - DibujarAutobusesMapa(data.EL) - }) - } catch (ex) { - console.log(ex + "" + text.toString()) - } - }, function error(e) { - ErrorServidor('errorZip', 'PUGR01', 'ocurrencia baja') - }); - } catch (e) { - ErrorServidor('errorDesconocido', 'PUGR01', e) - } - } - }); - } -} -function CrearUnionReferencia(parada, extra) { - var clonParada = JSON.parse(JSON.stringify(parada)) - var parBus = [] - var parIti = [] - for (var cnt = 0; cnt < clonParada.EP.length; cnt++) { - if (clonParada.EP[cnt].CP == extra.CodParada) { - par = clonParada.EP[cnt] - } - parBus = parBus.concat(clonParada.EP[cnt].EB) - parIti = parIti.concat(clonParada.EP[cnt].Iti) - } - parIti = parIti.unique().sort(function (a, b) { return parseFloat(a) - parseFloat(b) }) - ref = parIti - for (cnt2 = 0; cnt2 < par.Iti.length; cnt2++) { - ref = ref.filter(function (e) { return e !== par.Iti[cnt2] }) - } - return { Ref: ref, Iti: parIti, EB: parBus } -} -function InyectarDatosLinea(data, idLinea) { - linea = ObtenerLinea(idLinea) - $.each(linea.Paradas, function (p, parada) { - par = BuscarParadaInyeccion(data.EP, parada.CP) - $.each(par.EB, function (p, bus) { - parada.Coches.push(CrearCoche(bus, data.FH)) - }) - }) - return linea -} -function BuscarParadaInyeccion(EP, codigo) { - var parada = null; - parada = $.grep(EP, function (p) { - return p.CP == codigo; - })[0] - return parada -} -///////////////////////////////////////////////////////////////////////LINEAS/////////////////////////////////////////////////////////////////// -var LSVerTodasLineas = false -function CambiarVistaLineas(nombre) { - //TODO: debe de rellenar tambien la lista de lineas del mapa - var estado = !document.getElementById(nombre).checked - - document.getElementById('checkboxTodasLineas').checked = estado - document.getElementById('checkboxTodasLineasB').checked = estado - storage.set('verTodasLineas', estado) - LSVerTodasLineas = estado - - if ($.mobile.activePage.attr('data-url') == 'pageLinea') { - MostrarLineasDisponibles() - } else if ($.mobile.activePage.attr('data-url') == 'pageMapa') { - MostrarLineasMapaDisponibles() - } -} -function MostrarLineasDisponibles() { - document.getElementById('checkboxTodasLineas').checked = LSVerTodasLineas - html = "" - - $('#ListaLineas').html(html) -} -function MostrarLineasMapaDisponibles() { - document.getElementById('checkboxTodasLineasB').checked = LSVerTodasLineas - html = '

Pulse sobre las líneas para visualizarlas en el mapa

' - html += "" - - //$('#lineasMapa').html(html) - $('#listaLineasMapa').html(html) - //componentHandler.upgradeDom(); -} -////////////////////////////////////////////////////////////////LINEAVER//////////////////////////////////////////////////////////////////////// -var horaActual; var idBlink = null; var Scroll = ''; var ultimaSeleccionada = ""; var idLineas = null; var idParadas = null; var busPintados = []; var ultFechaBusMapa = null; -function VerLinea(idLinea, idParada) { - storage.set('LineaVer', idLinea) - //storage.set('LineaPpal', idLinea); - if ($.mobile.activePage.attr('data-url') == 'pageLineaVer') { - DibujarLineaEsquema() - } else { - $.mobile.changePage("#pageLineaVer"); - } - if (idParada != null) { - //TODO:Añadir posición y sentido - LineaParadaPulsada(idParada, idLinea) - Scroll = idParada - } -} -function DibujarLineaEsquema() { - infolinea = ObtenerItinerario(storage.get('LineaVer')); - color = "#" + infolinea.BC; - nombre = infolinea.Nom - //if (infolinea.Definicion.Codigo == 3) { nombre = 'Zafra – Higueral – Universidad – C.C. Holea' } - $('#toptitleLineasVerText').html("L-" + infolinea.Abr) - $('#headLineasVer').text(infolinea.Abr + ': ' + nombre); - $('#headLineasVer').css('text-shadow', "none"); - - $('#verLineasContNombre').css('background-color', color); - $('#verLineasContNombre').css('color', '#' + infolinea.FC); - //$('#verLineasContNombre').css('border', '1px solid ' + ColorLuminance(infolinea.Apariencia.BackColor.substring(2), -0.5)); - if (online) { - if (storage.isSet('UTH' + storage.get('LineaVer'))) { - tiempo = tiempoRecargaMilis - (Date.now() - storage.get('UTH' + storage.get('LineaVer'))); - console.log(tiempo)//Debug - ObtenerLineaConParada(storage.get('LineaVer'), 'recargar lineaVer', { Timeout: tiempo }); - } else { - ObtenerLineaConParada(storage.get('LineaVer'), 'recargar lineaVer'); - } - } else { - verLineaOffline() - } - -} -function DibujarLineaVer(data, timeout) { - console.log("DibujarLineaVer " + timeout) - var $select = $("#ListLineasPageLineas"); - if ($select.text().trim() != "Cargando, por favor espere...") { - RefrescarLineaVer(data, timeout) - } else { - $select.empty(); - busPintados = []; - lineaActual = data.Cla; - var contadorParada = 0; - var tipo = "2" - if (data.Sen.length == 1) { - tipo = '1' - } - var paradaInicioVuelta = "" - for (i = 0; i < data.Sen.length; i++) { - for (posParada = 0; posParada < data.Sen[i].Par.length; posParada++) { - parada = data.Sen[i].Par[posParada] - contadorParada += 1; - var codTrayecto = 0; - if (posParada > 0) { codTrayecto = data.Sen[i].Tray[posParada - 1] } //la primera coje el final del trayecto de vuelta - parada = ObtenerBotonEsquema(parada, tipo, lineaActual, contadorParada, codTrayecto, posParada, data, i) - if (posParada == 0 && tipo == "2" && i == 0) { - codTrayecto = "" - paradaInicioVuelta = parada - } - $select.append(parada); - } - ActivarAutobuses(data.Cla,data.PC) - } - //seteamos la hora para luego actualizar o no - horaActual = Date.now(); - //si hemos venido seleccionando una parada la seteamos - //TODO: deberia borrar el codUltParadaPulsada - if (storage.isSet('CodUltParadaPulsada')) { - SeleccionarParada('btnMapa' + storage.get('CodUltParadaPulsada')); - } - if (tipo == 2) { - $select.append(paradaInicioVuelta) - } else { - $("#ListLineasPageLineas button").last().addClass("paradaRegulacion") - } - - $('style').remove(); - $('head').append(''); - $('head').append(''); - $('.textoLineaHellip').width($('.parada h1').width() - 20 + 'px'); - window.clearInterval(idBlink) - $('.blink').fadeTo('slow', 0.1).fadeTo('slow', 1.0); - idBlink = BlinkElement(); - if (Scroll != '' && Scroll != null) { - document.getElementById("btnMapa" + scroll).scrollIntoView(); - scroll = '' - } - if ($("#cambiarTimeout").text() == "Iniciar" && storage.get('modoPrueba')) { - - } else { - window.clearInterval(idLineas); - - if (timeout == null) { - //console.log('timeout normal') - idLineas = TimeoutRecargarLineaAutomaticamente(); - } else { - //console.log("mini timeout"+ timeout) - idLineas = TimeoutRecargarLineaAutomaticamente(timeout); - } - } - } -} -function ActivarAutobuses(clave, CochesActivos) { - $(".clickBusM").remove() - $(".clickBusL").remove() - for (var cBus = 0; cBus < CochesActivos.length; cBus++) { - var bus = CochesActivos[cBus] - if (bus != null) { - console.log(bus.Tra + ": " + bus.Coc + "->" + bus.Pos) - trayecto = ObtenerTrayecto(bus.Tra) - parada1 = ObtenerParada(trayecto.CP1) - parada2 = ObtenerParada(trayecto.CP2) - - if (bus.Pos > 0) {//movimiento - $("#" + parada2.CP + " h1").addClass("llegadaM").prepend('
') - } else if (bus.Pos == 100) {//en parada 2 - $("#" + parada2.CP + " h1").addClass("llegadaL").prepend('
') - } else {//en parada 1 - $("#" + parada1.CP + " h1").addClass("llegadaL").prepend('
') - } - } - } -} -function RefrescarLineaVer(data, timeout) { - $(".parada h1").removeClass("llegadaL"); - $(".clickBusL").remove() - busPintados = [] - $(".parada h1").removeClass("llegadaM"); - $(".clickBusM").remove() - var tipo = "2" - if (data.Sen.length == 1) { - tipo = '1' - } - var contadorParada = 0; - for (i = 0; i < data.Sen.length; i++) { - for (posParada = 0; posParada < data.Sen[i].Par.length; posParada++) { - parada = data.Sen[i].Par[posParada] - - contadorParada += 1; - p = posParada - trayecto = 0 - if (posParada > 0) { - trayecto = data.Sen[i].Tray[posParada - 1] - } else { - if (data.Sen.length == 1) {//unilinea - trayecto = data.Sen[i].Tray[data.Sen[i].Tray.length - 1] - } else if (i == 0) {//ida - trayecto = data.Sen[1].Tray[data.Sen[1].Tray.length - 1] - } else {//vuelta - trayecto = data.Sen[0].Tray[data.Sen[0].Tray.length - 1] - } - } - var autobus = null; - for (var b = 0; b < parada.EB.length; b++) { - coche = parada.EB[b] - //NOTAS:En teoria tratamos esto como ida/vuelta/ida+vuelta ya veremos que pasa despues - if (coche.itinerario == data.CI && coche.codigoLinea == data.CL) {//&& EstaEnTrayecto(coche.trayecto, trayecto, p) - //console.log('El primer bus de ' + parada.Nombre + ' tiene el codigo ' + coche.codigo); - autobus = coche; - break; - } - } - if (parada.CP == codParadaMasCercana || parada.CP == codParadaMasCercana2) { - htmlGeo = '+cerca ' - } else { - htmlGeo = ''; - } - //comprobamos si hay bus o no, si no hay monstramos "sin información" - if (!autobus) { - htmlbus = ''; - } else { - busPintados.push(autobus) - if (autobus.tiempo < 179) { - classBlink = 'blink '; - blink = true - } else { - classBlink = ''; - } - - var partHora = [autobus.tiempo.toHHorMMorSS()] - if (autobus.tiempo.toHHorMMorSS() != 'En Parada' && autobus.tiempo.toHHorMMorSS() != 'Próxima Llegada') { - partHora = autobus.tiempo.toHHorMMorSS().split(' ');//autobus.tiempo - } - if (partHora.length >= 4) { - time = '' + partHora[0] + ' ' + partHora[1] + ' ' + partHora[2] + ' ' + partHora[3] - } else if (partHora.length == 1) { - time = '' + partHora[0] + '' - } else { - time = '' + partHora[0] + ' ' + partHora[1] - } - htmlbus = '' - + htmlGeo - + 'Hora ' - + '' + data.Abr + '' - + time - + tiempoNormal(autobus.tiempo) + '';//' + htmlOtrasLineas + ' - - $(".btnMapa" + parada.CP + " label").html(htmlbus) - } - var itiyuse = AdquirirtiempoProximoItinerarios(parada, data.CL, data.CI) - var itinerariosHermanos = itiyuse.hermanas - $(".btnMapa" + parada.CP + " label.hermana").remove() - if (document.getElementById("corresp" + parada.CP) != null) { - $(itinerariosHermanos).insertBefore("#corresp" + parada.CP) - } else { - $(".btnMapa" + parada.CP).append(itinerariosHermanos) - } - } - } - horaActual = Date.now(); - window.clearInterval(idBlink) - $('.blink').fadeTo('slow', 0.1).fadeTo('slow', 1.0); - idBlink = BlinkElement(); - ActivarAutobuses(data.Cla,data.PC) - if ($("#cambiarTimeout").text() == "Iniciar" && storage.get('modoPrueba')) { - - } else { - window.clearInterval(idLineas); - - if (timeout == null) { - //console.log('timeout normal') - idLineas = TimeoutRecargarLineaAutomaticamente(); - } else { - //console.log("mini timeout"+ timeout) - idLineas = TimeoutRecargarLineaAutomaticamente(timeout); - } - } -} -function ObtenerAutobusTrayecto(bus, busesActivos) { - var buses =null - for (var d = 0; d < busesActivos.length; d++) { - if(busesActivos[d].Coc == bus.codigo) { - buses = busesActivos[d] - break; - } - } - return buses -} -function ObtenerBotonEsquema(parada, tipo, linea, contadorParada, trayecto, p, data, i) { - var busRaro = false;//para controlar si el bus tiene algo inusual - var primera = true; - var classLlegada = ""; - var htmlTotal = ""; - var htmlOtrasLineas = "", htmlGeo = "", htmlbus = "" - //Obtenemos el sentido, en caso de ser la primera parada de idavuelta, obtiene el sentido contrario, porque "llegan a su posición" - - //Para pintar de verde si es primera o regulación - var cssClass = ''; - var classAlubia = '' - if (p == 0) { - cssClass = ' paradaRegulacion'; - classAlubia = 'ppal' - } - //buscamos el mismo coche para la parada anterior (aunque sea la última del otro sentido) y la siguiente (aunque sea la primera del otro sentido) para luego dibujar el coche a la derecha - var autobus = null, autobusAnt = null, autobusSig = null; - $.each(parada.EB, function (b, coche) { - //NOTAS:En teoria tratamos esto como ida/vuelta/ida+vuelta ya veremos que pasa despues - if (coche.itinerario == data.CI && coche.codigoLinea == data.CL) { - //console.log('El primer bus de ' + parada.Nombre + ' tiene el codigo ' + coche.codigo); - autobus = coche; - return false; - } - }); - //Ponemos el icono del muñeco corriendo si es parada + cercana - if (parada.CP == codParadaMasCercana || parada.CP == codParadaMasCercana2) { - htmlGeo = '+cerca ' - } else { - htmlGeo = ''; - } - //comprobamos si hay bus o no, si no hay monstramos "sin información" - if (!autobus) { - htmlbus = ''; - } else { - //console.log(i+". cod:" + autobus.codigo + "-> " + autobusSig.tiempo + ' > ' + autobus.tiempo + ' && ' + autobusAnt.tiempo + ' > ' + autobus.tiempo) - if (autobus.trayecto == trayecto) { - console.log(contadorParada + ")" + autobus.trayecto + "-" + autobus.posEnTrayecto + " tp:" + autobus.tiempo.toHHorMMorSS()) - busPintados.push(autobus) - } else { - classLlegada = ''; - classBlink = ''; - } - if (autobus.tiempo < 179) { - classBlink = 'blink '; - blink = true - } else { - classBlink = ''; - } - - var partHora = [autobus.tiempo.toHHorMMorSS()] - if (autobus.tiempo.toHHorMMorSS() != 'En Parada' && autobus.tiempo.toHHorMMorSS() != 'Próxima Llegada') { - partHora = autobus.tiempo.toHHorMMorSS().split(' ');//autobus.tiempo - } - if (partHora.length >= 4) { - time = '' + partHora[0] + ' ' + partHora[1] + ' ' + partHora[2] + ' ' + partHora[3] - } else if (partHora.length == 1) { - time = '' + partHora[0] + '' - } else { - time = '' + partHora[0] + ' ' + partHora[1] - } - htmlbus = ''; - } - var itiyuse = AdquirirtiempoProximoItinerarios(parada, data.CL, data.CI) - var itinerariosHermanos = itiyuse.hermanas - - if (verCorrespondencia == true) { - if (parada.Iti.length > 1) {//TODO: && storage.get("verTransbordos") == true - htmlOtrasLineas = 'Corresp. : ' - //recorremos las lineas - var limite = 8 - var sobremas = false; - for (index = 0; index < parada.Iti.length; index++) { - if (itiyuse.usadas.indexOf(parada.Iti[index]) == -1) { - if (limite > 0) { - if (parada.Iti[index] != lineaActual) { - limite = limite - 1; - lineaInfo = ObtenerItinerario(parada.Iti[index]); - idLineaSize = parada.Iti[index] - padding = '' - htmlOtrasLineas += '' + lineaInfo.Abr + ''; - } - } else { - sobremas = true - } - } - } - if (sobremas) { - htmlOtrasLineas += '...'; - } - htmlOtrasLineas += "" - if (htmlOtrasLineas == 'Corresp. : ') { - htmlOtrasLineas = "" - } - } - } - - htmlTotal = '
' - + '

' + - '' - + '' - + '' - + '

' - + '
'; - if (classLlegada != '') { - htmlTotal = '
' - + '

' + - '
' + - '' - + '' - + '' - + '

' - + '
'; - } - if (p == 0) { - if (classLlegada == 'class="llegadaL"' || classLlegada == 'class="llegadaL raro"') { - var clas = "llegadaInicio" - if (classLlegada.indexOf("raro") > -1) { - clas = "llegadaInicio raro" - } - htmlTotal = '
' - + '

' + - '
' + - '' - + '' - + '' - + '

' - + '
'; - } - } - return htmlTotal -} -function AdquirirtiempoProximoItinerarios(parada, padre, lineaActual) { - var hermanas = "" - var codigosUsados = [] - //Comprobamos si por aqui pasa un itinerario de la misma linea9292 - - lineasHermanas = $.grep(LSLineas, function (l) { - return l.CL == padre; - }) - - for (var cpcl = 0; cpcl < lineasHermanas.length; cpcl++) { - var lin = lineasHermanas[cpcl] - var codigo = lin.CI - if (lineaActual != codigo) { - if (lin.CL == padre) { - //si es de la misma hermana se busca el primer coche de esta y se muestra - for (var aaa = 0; aaa < parada.EB.length; aaa++) { - var bus = parada.EB[aaa] - if (bus.itinerario == codigo) { - codigosUsados.push(codigo) - var aaBlinka = "" - var partHora = [bus.tiempo.toHHorMMorSS()] - if (bus.tiempo.toHHorMMorSS() != 'En Parada' && bus.tiempo.toHHorMMorSS() != 'Próxima Llegada') { - partHora = bus.tiempo.toHHorMMorSS().split(' ');//autobus.tiempo - } - if (partHora.length >= 4) { - time = '' + partHora[0] + ' ' + partHora[1] + ' ' + partHora[2] + ' ' + partHora[3] - } else if (partHora.length == 1) { - time = '' + partHora[0] + '' - } else { - time = '' + partHora[0] + ' ' + partHora[1] - } - hermanas += ''; - - //hermanas += "" - break; - } - } - } - } - } - return { hermanas: hermanas, usadas: codigosUsados } -} -function getBus(codigo, orden, parada, itinerario) { - var b = []; - b = $.grep(parada.EB, function (co) { - return (co.codigo == codigo && co.orden == orden && co.itinerario == itinerario); - })[0]; - if (b == null) { - b = []; - } - return b; -} -function LineaParadaPulsada(codigo, idLinea, posicion, sentido, funcionRealizar, extra) { - var funcion = '' - switch (funcionRealizar) { - case 1: - funcion = 'ObtenerParadaMapa' - break; - case 2: - funcion = 'ObtenerParadaBusqueda' - break; - case 3: - funcion = 'ObtenerParadaFavoritos' - break; - default: - funcion = 'ObtenerParadaEsquema' - break; - } - var extras = { Linea: idLinea, Posicion: posicion, CodParada: codigo, Sentido: sentido } - var extras = $.extend({}, extras, extra); - try { - window.clearInterval(idLineas) - if (online) { - var par = ObtenerParada(codigo) - var ref = EsReferenciada(par.CPRef) - var codigos = codigo - if (funcionRealizar == 2) { - ref = null - } - if (ref != null) { - codigos = ref.Cadena - } - if (funcionRealizar == 1 && par.Iti.length > 1 && layersSeleccionados.length > 1) { - for (var cD = 0; cD < par.Iti.length; cD++) { - cod = par.Iti[cD] - for (var cP = 0; cP < layersSeleccionados.length; cP++) { - layer = layersSeleccionados[cP] - if (cod == layer && layer != idLinea) { - console.log("si tio, aqui debes cambiar la funcion a la doble") - funcion = 'ObtenerParadaMapaCombi' - ref = null - } - } - } - } - // te quedaste arreglando eso para que no vaya lento por culpa del estorage - if (localStorage['EPR' + codigos] != null) { - tiempo = Date.now() - localStorage['UTHP' + codigos]; - if (tiempo >= (tiempoRecargaMilis - 500)) { - console.log("Debug: se pide parada " + codigos) - if (ref != null) { - SolicitarParadas(ref.Cadena, funcion, extras) - } else { - SolicitarParadas(codigo, funcion, extras) - } - } else { - console.log("Debug:ya existe la parada" + codigos) - if (ref != null) { - LlamarFuncionParada(storage.get('EPR' + codigos), funcion, extras) - } else { - LlamarFuncionParada(storage.get('EPR' + codigos), funcion, extras) - } - } - } else { - if (ref != null) { - SolicitarParadas(ref.Cadena, funcion, extras) - } else { - SolicitarParadas(codigo, funcion, extras) - } - } - - } else { - //TODO: Cambiar a swal - AbrirParadaOffline(codigo, idLinea, posicion); - } - } catch (ex) { - swal.close() - console.log(ex.stack) - //si fallase abriendo la parada por lo que sea, recargamos el esquema - if ($.mobile.activePage.attr('data-url') == 'pageLineaVer') { - idLineas = TimeoutRecargarLineaAutomaticamente(); - RecargarModoLineasAutomaticamente() - } - } - if (funcion == "ObtenerParadaEsquema") { - SeleccionarParada('btnMapa' + codigo); - } -} - -function verLineaOffline() { - var $select = $("#ListLineasPageLineas"); - $select.empty(); - busPintados = []; - data = ObtenerItinerario(storage.get('LineaVer')); - var contadorParada = 0; - var tipo = "2" - if (data.Sen.length == 1) { - tipo = '1' - } - var paradaInicioVuelta = "" - for (i = 0; i < data.Sen.length; i++) { - $.each(data.Sen[i].Par, function (posParada, parada) { - contadorParada += 1; - var codTrayecto = 0; - if (posParada > 0) { codTrayecto = data.Sen[i].Tray[posParada - 1] } //la primera coje el final del trayecto de vuelta - parada = ObtenerBotonEsquema(parada, tipo, lineaActual, contadorParada, codTrayecto, posParada, data, i) - if (posParada == 0 && tipo == "2" && i == 0) { - codTrayecto = "" - paradaInicioVuelta = parada - } - $select.append(parada); - }); - } - if (tipo == 2) { - $select.append(paradaInicioVuelta) - } else { - $("#ListLineasPageLineas button").last().addClass("paradaRegulacion") - } - $('style').remove(); - $('head').append(''); - $('head').append(''); - $('.textoLineaHellip').width($('.parada h1').width() - 20 + 'px'); -} - -var infodotAbierto = false; -function SolicitarHTMLInformacionParadaLight(data, paradaPpal, idLinea, posicion, sentido) { - var iwContenidoTotal = ''; - if (data != null) { - //obtenemos el itinerario en lugar de infolinea para el tratamiento de paradas - miLinea = ObtenerItinerario(idLinea) - - var paradaPrimera = miLinea.Sen[0].Par[0].CP - var paradaRegulacion = null - if (miLinea.Sen.length > 1) { - paradaRegulacion = miLinea.Sen[1].Par[0].CP - } - - var par = data - var iwCoches = [] - //var pos = (ObtenerPosicionParada(ObtenerLinea(idLinea).Paradas, data)) + 1 - var pos = posicion; - abierto = "display:none;" - //TODO: InfodotAbierto (al pulsar en 3 puntos), se debe cerrar cuando cierre el popup (que no cuando salga otro encima de este) - if (infodotAbierto) { - abierto = "display:block;" - } - var iwContenido1 = '
' + - '
' + - '' + - '
' + (pos + 1) + ': ' + par.Nom + ' (' + par.CP + ')
' + - '' + - '' + - '
' + - '
' + - '

Cómo Llegar a Píe

' + - '

Ver en Mapa

' + - '

Street View

' + - '

Crear Alerta

' + - '
' + - '
' - var iwLinea = '

L-' + miLinea.Abr + ': ' + miLinea.Nom + '

'; - var iwContenido2 = '
'; - var iwContenidoRegulacion = '

regulación

'; - var iwDireccion = ""; - var iwDistancia = ""; - var iwMenu = '' - - return html -} -function ObtenerBusEsquema(codigo, clave) { - window.clearInterval(idLineas) - tiempo = Date.now() - ultFechaBusMapa; - if (tiempo <= (tiempoRecargaMilis - 500) && storage.isSet("BSE" + codigo)) { - MostrarAutobusEsquema(storage.get("BSE" + codigo), clave) - - } else { - JSZipUtils.getBinaryContent(urlDatos + 'api/JQ/JSONQRYZIP/ESTGRAL|' + clave + '?i=' + Math.random() + '&' + servidor + '&p=' + plataforma + '&v=' + version, function (err, data) { - var elt = document.getElementById('jszip_utils'); - if (err) { - ErrorServidor('noRespuesta', 'PUGR01', '') - return; - } else { - try { - JSZip.loadAsync(data) - .then(function (zip) { - return zip.file("datos.json").async("string") - }) - .then(function success(text) { - try { - data = JSON.parse(text.substring(1)) - ultFechaBusMapa = Date.now() - $.each(data.EL[0].EC, function (ec, bus) { - bus.TPS = getSeconds(data.FH, bus.TPS).toString() - bus.TPF = getSeconds(data.FH, bus.TPF).toString() - if (bus.CB == codigo) { - storage.set("BSE" + bus.CB, bus) - MostrarAutobusEsquema(bus, clave) - return false - } - }) - } catch (ex) { - console.log(ex + "" + text.toString()) - } - }, function error(e) { - ErrorServidor('errorZip', 'PUGR01', 'ocurrencia baja') - }); - } catch (e) { - ErrorServidor('errorDesconocido', 'PUGR01', e) - } - } - }); - } -} -function MostrarAutobusEsquema(data, clave) { - htmlTexto = ObtenerHtmlInformacionBus(data, clave) - Swal.fire({ - html: htmlTexto, - showConfirmButton: false, - customClass: 'SwalInformacionAutobus', - animation: !Swal.isVisible() - //showCloseButton:true - }).then((result) => { - console.log("Me han cerrado :(") - CerrarInfoDot() - window.clearInterval(idLineas) - if (storage.isSet('UTH' + storage.get('LineaVer'))) { - tiempo = tiempoRecargaMilis - (Date.now() - storage.get('UTH' + storage.get('LineaVer'))); - console.log("tiempo para refresco:" + tiempo) - if (tiempo > 0) { - idLineas = TimeoutRecargarLineaAutomaticamente(tiempo); - } else { - idLineas = TimeoutRecargarLineaAutomaticamente(0); - } - } else { - idLineas = TimeoutRecargarLineaAutomaticamente(0); - } - }) - idLineas = TimeoutRecargarBusEsquemaAutomaticamente(data.CB, clave) -} -function TimeoutRecargarBusEsquemaAutomaticamente(codigo, clave) { - tiempo = tiempoRecargaMilis - return window.setInterval(function () { - ObtenerBusEsquema(codigo, clave); - }, tiempo); -} -//TODO: popup offline -function AbrirParadaOffline(codParada, codLinea, posicion) { - paradaActual = codParada; - listaLineasFavoritos = null - storage.set('CodUltParadaPulsada', codParada); - lineaActual = codLinea; - paradaABuscar = ObtenerParada(codParada); - Swal.fire({ - html: SolicitarHTMLInformacionOffline(paradaABuscar, lineaActual), - showConfirmButton: false, - customClass: 'SwalInformacionParada' - //showCloseButton:true - }).then((result) => { - console.log("Me han cerrado :(") - CerrarInfoDot() - window.clearInterval(idLineas) - }) -} -function SolicitarHTMLInformacionOffline(parada, idLinea) { - var html = "" - var data = parada; - codParada = parada.CP - miLinea = ObtenerItinerario(idLinea) - var iwContenido1 = '
' + - '
' + - '' + - '

' + data.Nom + ' (' + data.CP + ')

' + "
" - var iwLinea = '

L-' + miLinea.Abr + ': ' + miLinea.Nom + '

'; - var iwContenidoRegulacion = '

regulación

'; - var iwDireccion = ""; - var iwDistancia = ""; - var iwMenu = '