/** * @file * Global utilities. * */ (function (Drupal) { "use strict"; Drupal.behaviors.mitema = { attach: function (context, settings) { const botonPrincipalInfografia = document.querySelector( ".omb-infografia-content .omb-boton-sidebar--width" ); const botonesListaInfografia = document.querySelectorAll( ".omb-infografia-content .omb-sidebar-item > .omb-boton-sidebar " ); const botonesInfografia = [ botonPrincipalInfografia, ...botonesListaInfografia, ].filter(Boolean); const viewsInfografia = document.querySelectorAll( ".omb-cards-infogracia-container .views-element-container" ); if (botonesInfografia.length > 0 && viewsInfografia.length > 0) { // Mostrar solo la primera vista viewsInfografia.forEach((vista, i) => { vista.style.display = i === 0 ? "block" : "none"; }); // Marcar el primer botón como activo botonesInfografia.forEach((btn, i) => { btn.classList.toggle("omb-boton-sidebar--active", i === 0); }); // Asignar eventos a cada botón botonesInfografia.forEach((boton, index) => { boton.addEventListener("click", () => { console.log("boton_infografia", index); // Ocultar todas las vistas viewsInfografia.forEach((v) => (v.style.display = "none")); // Mostrar la correspondiente if (viewsInfografia[index]) { viewsInfografia[index].style.display = "block"; } // Actualizar clase activa botonesInfografia.forEach((b) => b.classList.remove("omb-boton-sidebar--active") ); boton.classList.add("omb-boton-sidebar--active"); }); }); } const botonTodasActualidades = document.querySelector( ".omb-noticias-container .omb-boton-sidebar--width" ); const botonesLista_ = document.querySelectorAll( ".omb-noticias-container .omb-sidebar-item > .omb-boton-sidebar" ); const botonesNoticias = [botonTodasActualidades, ...botonesLista_].filter( Boolean ); if (botonesNoticias.length > 0) { mostrarSoloVista(0); // Mostrar primera por defecto botonesNoticias.forEach((boton, index) => { boton.addEventListener("click", () => { console.log("botón_noticia", index); mostrarSoloVista(index); }); }); } const botonesAcordeon = document.querySelectorAll( ".omb-acordion-boton--home" ); const acordionContenido = document.querySelectorAll( ".omb-acordion-content-home" ); // Función para abrir un grupo por data-boton function abrirGrupo(botonId) { acordionContenido.forEach((contenido) => { if (contenido.dataset.boton === botonId) { contenido.style.maxHeight = contenido.scrollHeight + "px"; contenido.classList.add("abierto"); } }); botonesAcordeon.forEach((btn) => { if (btn.dataset.boton === botonId) { btn.classList.add("activo"); } }); } // Evento click botonesAcordeon.forEach((boton) => { boton.addEventListener("click", () => { const botonId = boton.dataset.boton; // Cerrar todos los que no coincidan acordionContenido.forEach((contenido) => { if (contenido.dataset.boton !== botonId) { contenido.style.maxHeight = null; contenido.classList.remove("abierto"); } }); botonesAcordeon.forEach((btn) => { if (btn.dataset.boton !== botonId) { btn.classList.remove("activo"); } }); // Alternar el grupo que coincide const grupoAbierto = document.querySelector( ".omb-acordion-content-home[data-boton='${botonId}'].abierto" ); if (grupoAbierto) { acordionContenido.forEach((contenido) => { if (contenido.dataset.boton === botonId) { contenido.style.maxHeight = null; contenido.classList.remove("abierto"); } }); botonesAcordeon.forEach((btn) => { if (btn.dataset.boton === botonId) { btn.classList.remove("activo"); } }); } else { abrirGrupo(botonId); } }); }); // 📌 Abrir por defecto el data-boton = "1" al cargar abrirGrupo("1"); // Tableros // 1. Botón principal "Todos los tableros" que sí debe funcionar (el que está fuera de la lista) const botonPrincipal = document.querySelector( ".omb-boton-sidebar--width" ); // 2. Todos los botones dentro del ul, excluyendo el que tiene aria-label="Todos los tableros" const botonesLista = document.querySelectorAll( ".omb-sidebar-item > .omb-boton-sidebar " ); // 3. Combina el botón principal con los botones válidos de la lista const buttonsTableros = [botonPrincipal, ...botonesLista].filter(Boolean); // 4. Selecciona las vistas correspondientes const viewsTableros = document.querySelectorAll( "#ombContainer .views-element-container" ); // 5. Aplica comportamiento solo si todo existe if (buttonsTableros.length > 0 && viewsTableros.length > 0) { // Mostrar solo la primera vista viewsTableros.forEach((vista, i) => { vista.style.display = i === 0 ? "block" : "none"; }); // Marcar el primer botón como activo buttonsTableros.forEach((btn, i) => { btn.classList.toggle("omb-boton-sidebar--active", i === 0); }); // Asignar eventos a cada botón buttonsTableros.forEach((boton, index) => { boton.addEventListener("click", () => { console.log("boton_tablero", index); // Ocultar todas las vistas viewsTableros.forEach((v) => (v.style.display = "none")); // Mostrar la correspondiente if (viewsTableros[index]) { viewsTableros[index].style.display = "block"; } // Actualizar clase activa buttonsTableros.forEach((b) => b.classList.remove("omb-boton-sidebar--active") ); boton.classList.add("omb-boton-sidebar--active"); }); }); } // MOVILIDAD const botonTodos = document.querySelector( ".omb-tableros-content .omb-boton-sidebar--width" ); const botonesListaMo = document.querySelectorAll( ".omb-tableros-content .omb-sidebar-item > .omb-boton-sidebar " ); // 3. Combina el botón principal con los botones válidos de la lista const buttonsMovilidad = [botonTodos, ...botonesListaMo].filter(Boolean); // 4. Selecciona las vistas correspondientes const viewsMovilidad = document.querySelectorAll( ".omb-cards-movilidad-container .views-element-container" ); // 5. Aplica comportamiento solo si todo existe if (buttonsMovilidad.length > 0 && viewsMovilidad.length > 0) { // Mostrar solo la primera vista viewsMovilidad.forEach((vista, i) => { vista.style.display = i === 0 ? "block" : "none"; }); // Marcar el primer botón como activo buttonsMovilidad.forEach((btn, i) => { btn.classList.toggle("omb-boton-sidebar--active", i === 0); }); // Asignar eventos a cada botón buttonsMovilidad.forEach((boton, index) => { boton.addEventListener("click", () => { console.log("boton_tablero", index); // Ocultar todas las vistas viewsMovilidad.forEach((v) => (v.style.display = "none")); // Mostrar la correspondiente if (viewsMovilidad[index]) { viewsMovilidad[index].style.display = "block"; } // Actualizar clase activa buttonsMovilidad.forEach((b) => b.classList.remove("omb-boton-sidebar--active") ); boton.classList.add("omb-boton-sidebar--active"); }); }); } const botonTablerosMobile = document.getElementById( "botonTablerosMobile" ); const iconoFlecha = document.querySelector(".icono-flecha"); const sidebar = document.querySelector(".omb-sidebar-container"); if (botonTablerosMobile) { botonTablerosMobile.addEventListener("click", () => { sidebar.classList.toggle("activo"); iconoFlecha.classList.toggle("activo"); }); } const opcionSeleccionada = document.querySelectorAll( ".omb-opcion-selecionada" ); const listasDeOpciones = document.querySelectorAll(".omb-opciones"); const flechaSelect = document.querySelector(".icono-flecha-select"); // Al cambiar el select de tipo de contenido opcionSeleccionada.forEach((boton) => { boton.addEventListener("click", () => { const valorSeleccionado = boton.dataset.select; listasDeOpciones.forEach((lista) => { if (lista.dataset.select === valorSeleccionado) { // Toggle SOLO en la lista correspondiente lista.classList.toggle("hidden"); flechaSelect.classList.toggle("activo"); } else { // Oculta las otras listas lista.classList.add("hidden"); } }); }); }); // const sidebarContent = document.getElementById("sidebar"); // function handleScroll() { // const scrollLimit = 150; // if (window.innerWidth >= 1024) { // if (window.scrollY >= scrollLimit) { // sidebarContent.style.position = "fixed"; // sidebarContent.style.top = "20px"; // } else { // sidebarContent.style.position = "static"; // } // } else { // sidebarContent.style.position = "static"; // } // } // window.addEventListener("scroll", handleScroll); // window.addEventListener("resize", handleScroll); if (window.location.pathname !== "/") { const preFooter = document.querySelector(".omb-suscripcion-section"); if (preFooter) { preFooter.style.marginTop = "-20px"; } } if (window.location.href.includes("/tableros")) { const allCategorias = document.querySelector(".omb-button__width"); const mainContainer = document.querySelector("#main-wrapper"); if (allCategorias) { allCategorias.classList.add("omb-content-button-active"); } if (mainContainer) { mainContainer.classList.add("omb-tableros-contenedor"); } } if (window.location.href.includes("/movilidad")) { const allCategoriasM = document.querySelector( ".omb-boton-sidebar--width" ); if (allCategoriasM) { allCategoriasM.classList.add("omb-boton-sidebar--active"); } const buttons = document.querySelectorAll(".omb-boton-sidebar"); const cards = document.querySelectorAll(".omb-card-informativa"); buttons.forEach((buttonM) => { buttonM.addEventListener("click", () => { buttons.forEach((btn) => { btn.classList.remove("omb-boton-sidebar--active"); }); buttonM.classList.add("omb-boton-sidebar--active"); const categoriaSeleccionada = buttonM.textContent.trim(); cards.forEach((card) => { const categoriaCard = card.dataset.categoria; if ( categoriaSeleccionada === "Todos los indicadores" || categoriaCard === categoriaSeleccionada ) { card.style.display = "flex"; // Mostrar } else { card.style.display = "none"; // Ocultar } }); }); }); } const botonReproducir = ``; const botonPausar = ` `; const swiperIndicadores = new Swiper(".indicadoresSwiper", { slidesPerView: 1, spaceBetween: 30, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, pagination: { el: ".omb-paginacion-indicadores", clickable: true, }, loop: true, autoplay: { delay: 3000, disableOnInteration: false, }, breakpoints: { 480: { slidesPerView: 2, spaceBetween: 20 }, 768: { slidesPerView: 3, spaceBetween: 30, }, 1024: { slidesPerView: 4, spaceBetween: 30 }, 1360: { slidesPerView: 5, spaceBetween: 30 }, }, }); let isPlaying = true; const pauseButton = document.getElementById("controlCarrucelIndicadores"); if (pauseButton) { pauseButton.addEventListener("click", () => { pauseButton.innerHTML = ""; if (isPlaying) { swiperIndicadores.autoplay.stop(); pauseButton.innerHTML = botonReproducir; } else { swiperIndicadores.autoplay.start(); pauseButton.innerHTML = botonPausar; } isPlaying = !isPlaying; }); } const swiperPublicacionesSection = new Swiper( ".publicacionesSectionSwiper", { slidesPerView: 1, spaceBetween: 30, navigation: { nextEl: ".omb-boton-next--publicaciones-home", prevEl: ".omb-boton-prev--publicaciones-home", }, pagination: { el: ".omb-paginacion--publicaciones-home", clickable: true, }, loop: true, autoplay: { delay: 3000, disableOnInteration: false, }, breakpoints: { 480: { slidesPerView: 1, spaceBetween: 20, }, 768: { slidesPerView: 2, spaceBetween: 0, }, 1024: { slidesPerView: 4, spaceBetween: 30, }, 1360: { slidesPerView: 4, }, }, } ); let isPlayingSectionPublicacion = true; const pauseButtonSectionPublicaion = document.querySelector( "#controlCarrucelSectionPublicacion > button" ); if (pauseButtonSectionPublicaion) { pauseButtonSectionPublicaion.addEventListener("click", () => { pauseButtonSectionPublicaion.innerHTML = ""; if (isPlayingSectionPublicacion) { swiperPublicacionesSection.autoplay.stop(); pauseButtonSectionPublicaion.innerHTML = botonReproducir; } else { swiperPublicacionesSection.autoplay.start(); pauseButtonSectionPublicaion.innerHTML = botonPausar; } isPlayingSectionPublicacion = !isPlayingSectionPublicacion; }); } const swiperSitosRelacionados = new Swiper( ".sitiosRelacionadosSlideSwiper", { slidesPerView: 1, spaceBetween: 30, navigation: { nextEl: ".omb-boton-sitios-relacionados-next", prevEl: ".omb-boton-sitios-relacionados-prev", }, pagination: { el: ".omb-paginacion-sitios-relacionados", clickable: true, }, loop: true, autoplay: { delay: 600000, disableOnInteration: false, }, breakpoints: { 480: { slidesPerView: 1, spaceBetween: 20, }, 768: { slidesPerView: 2, spaceBetween: 24, }, 1024: { slidesPerView: 3, }, 1360: { slidesPerView: 3, }, }, } ); let isPlayingSitiosRelacionados = true; const pauseButtonSitiosRelacionados = document.getElementById( "controlCarrucelSitiosRelacionados" ); if (pauseButtonSitiosRelacionados) { pauseButtonSitiosRelacionados.addEventListener("click", () => { pauseButtonSitiosRelacionados.innerHTML = ""; if (isPlayingSitiosRelacionados) { swiperSitosRelacionados.autoplay.stop(); pauseButtonSitiosRelacionados.innerHTML = botonReproducir; } else { swiperSitosRelacionados.autoplay.start(); pauseButtonSitiosRelacionados.innerHTML = botonPausar; } isPlayingSitiosRelacionados = !isPlayingSitiosRelacionados; }); } // CARRUSEL OTROS MAPAS const containerBotonMapas = document.querySelector( ".omb-boton-control-carrusel-container" ); const botonMapas = document.getElementById("detenerMapas"); const mapaSwiper = new Swiper(".mapasSwiper", { slidesPerView: 1, spaceBetween: 30, navigation: { nextEl: ".omb-boton-next", prevEl: ".omb-boton-prev", }, pagination: { el: ".omb-paginacion-mapas", clickable: true, }, loop: true, autoplay: { delay: 3000, disableOnInteration: false, }, breakpoints: { 640: { slidesPerView: 2, }, 1024: { slidesPerView: 3, }, }, }); let isPlayingMapas = true; if (botonMapas) { botonMapas.addEventListener("click", () => { if (isPlayingMapas) { mapaSwiper.autoplay.stop(); botonMapas.innerHTML = ` Reproducir`; } else { mapaSwiper.autoplay.start(); botonMapas.innerHTML = ` Pausar`; } isPlayingMapas = !isPlayingMapas; }); } if (document.querySelector("#block-home-seccion-acordeon")) { const botonesTab = document.querySelectorAll(".omb-tabs-boton--home"); const primerTab = document.querySelector("button[data-tab='1']"); primerTab.classList.add("activo"); const cardsObservatorio = document.querySelectorAll( ".omb-card-observatorio" ); const primeraCard = cardsObservatorio[0]; primeraCard.classList.remove("hidden"); botonesTab.forEach((boton) => { boton.addEventListener("click", () => { const tabSeleccionado = boton.dataset.tab; // 🔁 Quitar clase "activo" de todos los botones botonesTab.forEach((btn) => btn.classList.remove("activo")); // ✅ Agregar clase "activo" al botón clicado boton.classList.add("activo"); // 🔁 Mostrar solo la card correspondiente cardsObservatorio.forEach((card) => { if (card.dataset.tab === tabSeleccionado) { card.classList.remove("hidden"); } else { card.classList.add("hidden"); } }); }); }); } ///////////// PUBLICACIONES const swiperPublicaciones = new Swiper(".publicacionesSlideSwiper", { slidesPerView: 1, spaceBetween: 30, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, pagination: { el: ".swiper-pagination", clickable: true, }, loop: true, autoplay: { delay: 3000, disableOnInteration: false, }, breakpoints: { 480: { slidesPerView: 1, spaceBetween: 20, }, 768: { slidesPerView: 2, spaceBetween: 24, }, 1140: { slidesPerView: 3, }, }, }); const pauseButtonPublicaciones = document.getElementById( "controlCarrucelPublicaiones" ); if (pauseButtonPublicaciones) { pauseButtonPublicaciones.addEventListener("click", () => { pauseButtonPublicaciones.innerHTML = ""; if (isPlayingSectionPublicacion) { swiperPublicaciones.autoplay.stop(); pauseButtonPublicaciones.innerHTML = ``; } else { swiperPublicaciones.autoplay.start(); pauseButtonPublicaciones.innerHTML = ` `; } isPlayingSectionPublicacion = !isPlayingSectionPublicacion; }); } // contexto indicadores politicas const swiperTablerosInteres = new Swiper(".tablerosSwiper", { slidesPerView: 1, spaceBetween: 30, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, pagination: { el: ".swiper-pagination", clickable: true, }, loop: true, autoplay: { delay: 3000, disableOnInteration: false, }, breakpoints: { 640: { slidesPerView: 2, }, 1024: { slidesPerView: 3, }, 1280: { slidesPerView: 4, }, }, }); let isPlayingTI = true; const pauseButtonTablerosInteres = document.getElementById( "controlCarrucelTablerosInteres" ); if (pauseButtonTablerosInteres) { pauseButtonTablerosInteres.addEventListener("click", () => { pauseButtonTablerosInteres.innerHTML = ""; if (isPlayingTI) { swiperTablerosInteres.autoplay.stop(); pauseButtonTablerosInteres.innerHTML = ``; } else { swiperTablerosInteres.autoplay.start(); pauseButtonTablerosInteres.innerHTML = ` `; } isPlayingTI = !isPlayingTI; }); } // carrusel mapas contexto const swiperRecursosInteres = new Swiper(".recursosInteresSwiper", { slidesPerView: 1, spaceBetween: 30, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, pagination: { el: ".swiper-pagination", clickable: true, }, loop: true, autoplay: { delay: 3000, disableOnInteration: false, }, breakpoints: { 640: { slidesPerView: 2, }, 1024: { slidesPerView: 3, }, 1280: { slidesPerView: 4, }, }, }); let isPlayingRI = true; const pauseButtonRecursosInteres = document.getElementById( "controlCarrucelRecursosInteres" ); if (pauseButtonRecursosInteres) { pauseButtonRecursosInteres.addEventListener("click", () => { pauseButtonRecursosInteres.innerHTML = ""; if (isPlayingRI) { swiperRecursosInteres.autoplay.stop(); pauseButtonRecursosInteres.innerHTML = ``; } else { swiperRecursosInteres.autoplay.start(); pauseButtonRecursosInteres.innerHTML = ` `; } isPlayingRI = !isPlayingRI; }); } const buttonsGraf = document.querySelectorAll(".omb-botones-lista"); const graficaContainers = document.querySelectorAll(".omb-grafica"); // Mostrar solo "Fallecidos" por defecto const categoriaPorDefecto = "Fallecidos"; buttonsGraf.forEach((button) => { const categoria = button.textContent.trim(); if (categoria === categoriaPorDefecto) { button.classList.add("omb-botones-lista-seleccionado"); } button.addEventListener("click", () => { buttonsGraf.forEach((btn) => btn.classList.remove("omb-botones-lista-seleccionado") ); button.classList.add("omb-botones-lista-seleccionado"); const categoriaSeleccionada = button.textContent.trim(); graficaContainers.forEach((card) => { const grafica = card.dataset.grafica; if (grafica.toLowerCase() === categoriaSeleccionada.toLowerCase()) { card.style.display = "flex"; // Mostrar solo el que coincide } else { card.style.display = "none"; // Ocultar los demás } }); }); }); // Al cargar la página, solo mostrar "Fallecidos" graficaContainers.forEach((card) => { const grafica = card.dataset.grafica; card.style.display = grafica.toLowerCase() === categoriaPorDefecto.toLowerCase() ? "flex" : "none"; }); // noticias const swiperNoticiasInteres = new Swiper(".noticiasSwiper", { slidesPerView: 1, spaceBetween: 30, navigation: { nextEl: ".omb-boton-noticias-next", prevEl: ".omb-boton-noticias-prev", }, pagination: { el: ".swiper-pagination", clickable: true, }, loop: true, autoplay: { delay: 3000, disableOnInteration: false, }, breakpoints: { 640: { slidesPerView: 2, }, 1024: { slidesPerView: 3, }, 1140: { slidesPerView: 4, }, }, }); let isPlayingNoticias = true; const pauseButtonNoticiasInteres = document.getElementById( "controlCarrucelNoticiasInteres" ); if (pauseButtonNoticiasInteres) { pauseButtonNoticiasInteres.addEventListener("click", () => { pauseButtonNoticiasInteres.innerHTML = ""; if (isPlayingNoticias) { swiperNoticiasInteres.autoplay.stop(); pauseButtonNoticiasInteres.innerHTML = botonReproducir; } else { swiperNoticiasInteres.autoplay.start(); pauseButtonTablerosInteres.innerHTML = botonPausar; } isPlayingNoticias = !isPlayingNoticias; }); } const swiperPublicacionesInteres = new Swiper( ".publicacionesInteresSlideSwiper", { slidesPerView: 1, spaceBetween: 32, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, pagination: { el: ".swiper-pagination", clickable: true, }, loop: true, autoplay: { delay: 3000, disableOnInteration: false, }, breakpoints: { 480: { slidesPerView: 1, spaceBetween: 20, }, 768: { slidesPerView: 2, spaceBetween: 24, }, 1024: { slidesPerView: 3, }, }, } ); let isPlayingPI = true; const pauseButtonPublicacionesInteres = document.getElementById( "controlCarrucelPublicaionesInteres" ); if (pauseButtonPublicacionesInteres) { pauseButtonPublicacionesInteres.addEventListener("click", () => { pauseButtonPublicacionesInteres.innerHTML = ""; if (isPlayingPI) { swiperPublicacionesInteres.autoplay.stop(); pauseButtonPublicacionesInteres.innerHTML = ``; } else { swiperPublicacionesInteres.autoplay.start(); pauseButtonPublicacionesInteres.innerHTML = ` `; } isPlayingPI = !isPlayingPI; }); } /////////////////////// tabla grafica movilididad ////////////////////////// const buttonsM = document.querySelectorAll(".omb-botones-lista"); const graficaContainersM = document.querySelectorAll(".omb-grafica"); const categoriaPorDefectoM = "gráfica"; buttonsM.forEach((button) => { const categoria = button.textContent.trim(); if (categoria === categoriaPorDefectoM) { button.classList.add("omb-botones-lista-seleccionado"); } button.addEventListener("click", () => { buttonsM.forEach((btn) => btn.classList.remove("omb-botones-lista-seleccionado") ); button.classList.add("omb-botones-lista-seleccionado"); const categoriaSeleccionada = button.textContent.trim(); graficaContainersM.forEach((card) => { const grafica = card.dataset.grafica; if ( grafica && grafica.toLowerCase() === categoriaSeleccionada.toLowerCase() ) { card.style.display = "block"; } else { card.style.display = "none"; } }); //////tabla html (function () { const contenedor = document.getElementById("tabla"); if (!contenedor) return; const jsonContainer = contenedor.querySelector(".field__item"); if (!jsonContainer) return; let raw = jsonContainer.textContent.trim(); // Función para convertir tabla a CSV y forzar descarga function descargarCSVDesdeTabla(tabla, nombreArchivo) { let csv = []; const filas = tabla.querySelectorAll("tr"); filas.forEach((fila) => { let columnas = fila.querySelectorAll("th, td"); let filaCSV = Array.from(columnas) .map((col) => `"${col.textContent.replace(/"/g, '""')}"`) .join(","); csv.push(filaCSV); }); const contenidoCSV = csv.join("\n"); const blob = new Blob([contenidoCSV], { type: "text/csv;charset=utf-8;", }); const enlace = document.createElement("a"); enlace.href = URL.createObjectURL(blob); enlace.download = nombreArchivo; enlace.style.display = "none"; document.body.appendChild(enlace); enlace.click(); document.body.removeChild(enlace); } try { const grafica = JSON.parse(raw); const data = grafica.data; console.log("datos tabla", data); if (!Array.isArray(data) || data.length === 0) return; // Crear tabla const tabla = document.createElement("table"); tabla.className = "table table-striped table-hover table-responsive table-indicadores"; tabla.style.width = "auto"; tabla.style.height = "80vh"; tabla.style.margin = "auto"; tabla.style.fontSize = "14px"; tabla.style.color = "#000"; // Crear thead const thead = document.createElement("thead"); thead.className = "thead-light sticky-top"; const headRow = document.createElement("tr"); data[0].forEach((header, i) => { const th = document.createElement("th"); th.textContent = header; th.style.textAlign = "center"; th.style.color = "#000"; th.style.backgroundColor = "#DBF000"; th.style.backgroundSize = "100%"; if (i === 0) th.className = "sticky-col"; headRow.appendChild(th); }); thead.appendChild(headRow); tabla.appendChild(thead); // Crear tbody const tbody = document.createElement("tbody"); data.slice(1).forEach((fila) => { const tr = document.createElement("tr"); fila.forEach((celda, i) => { const td = document.createElement("td"); td.textContent = celda; td.style.textAlign = i === 0 ? "center" : "right"; if (i === 0) td.className = "sticky-col"; tr.appendChild(td); }); tbody.appendChild(tr); }); tabla.appendChild(tbody); // Crear botón de descarga const botonDescarga = document.createElement("button"); botonDescarga.textContent = "Descargar CSV"; botonDescarga.className = "btn btn-primary"; botonDescarga.style.margin = "20px auto"; botonDescarga.style.display = "inline-flex"; botonDescarga.style.position = "absolute"; botonDescarga.addEventListener("click", function () { descargarCSVDesdeTabla(tabla, "datos.csv"); }); // Reemplazar contenido del contenedor contenedor.innerHTML = ""; contenedor.appendChild(botonDescarga); contenedor.appendChild(tabla); } catch (error) { console.error("❌ Error al procesar el JSON:", error); } })(); /////fin tabla }); }); graficaContainersM.forEach((card) => { const grafica = card.dataset.grafica; card.style.display = grafica && grafica.toLowerCase() === categoriaPorDefectoM.toLowerCase() ? "flex" : "none"; }); //acordeon const botonMenu = document.getElementById("botonMenu"); const botonesTab = document.querySelectorAll(".omb-tabs-boton--home"); const cardsObservatorio = document.querySelectorAll( ".omb-card-observatorio" ); //const nav = document.querySelector(".omb-nav"); // botonMenu.addEventListener("click", () => { // if (nav.style.display === "flex") { // nav.style.display = "none"; // botonMenu.innerHTML = ` `; // } else { // nav.style.display = "flex"; // botonMenu.innerHTML = ``; // } // }); botonesTab.forEach((boton) => { boton.addEventListener("click", () => { const tabSeleccionado = boton.dataset.tab; console.log("boton click"); // 🔁 Quitar clase "activo" de todos los botones botonesTab.forEach((btn) => btn.classList.remove("activo")); // ✅ Agregar clase "activo" al botón clicado boton.classList.add("activo"); // 🔁 Mostrar solo la card correspondiente cardsObservatorio.forEach((card) => { if (card.dataset.tab === tabSeleccionado) { card.classList.remove("hidden"); } else { card.classList.add("hidden"); } }); }); }); function handleScroll() { const scrollStart = 144; if (!nav) return; // <-- evita el error if (window.innerWidth >= 1024) { if (window.scrollY >= scrollStart) { nav.style.position = "fixed"; nav.style.zIndez = "50"; nav.style.top = "0"; nav.style.width = "100%"; } else { nav.style.position = "static"; nav.style.top = ""; nav.style.display = "flex"; } } else { nav.style.position = "absolute"; } } window.addEventListener("scroll", handleScroll, { passive: true, }); window.addEventListener("resize", handleScroll, { passive: true, }); window.addEventListener("scroll", () => { //console.log(window.scrollY); }); const volverArribaBoton = document.getElementById("volverArribaBoton"); if (volverArribaBoton) { volverArribaBoton.addEventListener("click", () => { window.scrollTo({ top: 0, behavior: "smooth", }); }); } window.addEventListener("scroll", () => { if (window.scrollY > 100) { volverArribaBoton.classList.add("activo"); } else { volverArribaBoton.classList.remove("activo"); } }); const htmlRoot = document.documentElement; const contrasteBtn = document.getElementById("botonContraste"); const aumentarLetraBtn = document.getElementById("botonAumentarLetra"); const reducirLetraBtn = document.getElementById("botonReducirLetra"); // Valores configurables const CONTRASTE_CLASE = "modo-contraste-alto"; const MAX_FONT_SIZE = 150; const MIN_FONT_SIZE = 80; const FONT_STEP = 10; // Estado actual de fuente let fontSizePercent = 100; // Funci n para aplicar el tama o de fuente function aplicarTamanoFuente() { htmlRoot.style.fontSize = `${fontSizePercent}%`; } // Bot n de contraste if (contrasteBtn) { contrasteBtn.addEventListener("click", () => { // document.body.classList.toggle(CONTRASTE_CLASE); }); } // Bot n aumentar letra if (aumentarLetraBtn) { aumentarLetraBtn.addEventListener("click", () => { if (fontSizePercent < MAX_FONT_SIZE) { fontSizePercent += FONT_STEP; aplicarTamanoFuente(); } }); } // Bot n reducir letra if (reducirLetraBtn) { reducirLetraBtn.addEventListener("click", () => { if (fontSizePercent > MIN_FONT_SIZE) { fontSizePercent -= FONT_STEP; aplicarTamanoFuente(); } }); } /// buscar - ordenar actualidades SM///////////////////////////////////////// function mostrarSoloVista(index) { // Ocultar todas las vistas const viewsNoticias = document.querySelectorAll( ".omb-cards-noticias-container .views-element-container" ); viewsNoticias.forEach((vista) => (vista.style.display = "none")); // Mostrar la correspondiente if (viewsNoticias[index]) { viewsNoticias[index].style.display = "block"; } // Actualizar botones activos const botonesNoticias = document.querySelectorAll( ".omb-noticias-container .omb-boton-sidebar, .omb-noticias-container .omb-boton-sidebar--width" ); botonesNoticias.forEach((b, i) => b.classList.toggle("omb-boton-sidebar--active", i === index) ); } // /////////// ocultar json chart if ( document.querySelector( "#block-mitema-content > div > article > section.omb-section.omb-grafica-section > div > div:nth-child(2) > div > details > summary" ) ) { document.querySelector( "#block-mitema-content > div > article > section.omb-section.omb-grafica-section > div > div:nth-child(2) > div > details > summary" ).style.display = "none"; } ////////buscar para tableros/////////// (function () { "use strict"; function initBuscarTableros(context) { const boton_buscar_ = context.querySelector("#btnBuscarTablero"); if ( boton_buscar_ && !boton_buscar_.classList.contains("evento-busqueda-asignado") ) { boton_buscar_.classList.add("evento-busqueda-asignado"); boton_buscar_.addEventListener("click", function () { const opt3 = document.querySelector( "#orden > option:nth-child(2)" ); if (opt3) opt3.disabled = true; let ordenSelect = document.getElementById("orden"); let ordenSelect_key = document.getElementById("orden"); if (ordenSelect) { ordenSelect = ordenSelect.value; ordenSelect_key = ordenSelect_key.options[ordenSelect_key.selectedIndex].text; } let termino = document .getElementById("inputBusqueda") .value.trim(); if (!termino) { termino = "all"; } const url = `/tableros?field_busqueda=${encodeURIComponent( termino )}&orden=${encodeURIComponent( ordenSelect )}&orden_key=${encodeURIComponent(ordenSelect_key)}&ajax=1`; // Guardar el ndice del bot n activo let botonActivo = document.querySelector( ".omb-boton-sidebar--active" ); let indexActivo = botonActivo ? botonActivo.getAttribute("data-index") : 0; fetch(url) .then((response) => response.text()) .then((html) => { const tempDOM = document.createElement("div"); tempDOM.innerHTML = html; const newContent = tempDOM.querySelector("#ombContainer"); const contenedorActual = document.getElementById("ombContainer"); if (newContent && contenedorActual) { contenedorActual.innerHTML = newContent.innerHTML; // Reasignar behaviors despu s de AJAX if (window.Drupal) { Drupal.attachBehaviors(contenedorActual); } // Mostrar solo vista activa const viewsNoticias = document.querySelectorAll( "#ombContainer .views-element-container" ); viewsNoticias.forEach((vista, idx) => { vista.style.display = idx == indexActivo ? "block" : "none"; }); // Quitar clase activa a todos const botones = document.querySelectorAll(".omb-boton-sidebar"); botones.forEach((btn) => btn.classList.remove("omb-boton-sidebar--active") ); // Marcar el que estaba activo antes const botonRestaurado = document.querySelector( `.omb-boton-sidebar[data-index="${indexActivo}"]` ); if (botonRestaurado) { botonRestaurado.classList.add( "omb-boton-sidebar--active" ); } } }); }); } } if (window.Drupal) { Drupal.behaviors.buscarTableros = { attach: function (context) { initBuscarTableros(context); }, }; } initBuscarTableros(document); //////////////////////////////// INFOGRAFIAS //////////////////////////////////// function initBuscarInfografias(context) { const boton_buscar_ = context.querySelector("#btnBuscarInfografia"); if ( boton_buscar_ && !boton_buscar_.classList.contains("evento-busqueda-asignado") ) { boton_buscar_.classList.add("evento-busqueda-asignado"); boton_buscar_.addEventListener("click", function () { const opt3 = document.querySelector( "#orden > option:nth-child(2)" ); if (opt3) opt3.disabled = true; let ordenSelect = document.getElementById("orden"); let ordenSelect_key = document.getElementById("orden"); if (ordenSelect) { ordenSelect = ordenSelect.value; ordenSelect_key = ordenSelect_key.options[ordenSelect_key.selectedIndex].text; } let termino = document .getElementById("inputBusqueda") .value.trim(); if (!termino) { termino = "all"; } const url = `/publicaciones/infografias?field_busqueda=${encodeURIComponent( termino )}&orden=${encodeURIComponent( ordenSelect )}&orden_key=${encodeURIComponent(ordenSelect_key)}&ajax=1`; // Guardar el ndice del bot n activo let botonActivo = document.querySelector( ".omb-boton-sidebar--active" ); let indexActivo = botonActivo ? botonActivo.getAttribute("data-index") : 0; fetch(url) .then((response) => response.text()) .then((html) => { const tempDOM = document.createElement("div"); tempDOM.innerHTML = html; const newContent = tempDOM.querySelector( "#ombContainer-infografia" ); const contenedorActual = document.getElementById( "ombContainer-infografia" ); if (newContent && contenedorActual) { contenedorActual.innerHTML = newContent.innerHTML; // Reasignar behaviors despu s de AJAX if (window.Drupal) { Drupal.attachBehaviors(contenedorActual); } // Mostrar solo vista activa const viewsNoticias = document.querySelectorAll( "#ombContainer-infografia .views-element-container" ); viewsNoticias.forEach((vista, idx) => { vista.style.display = idx == indexActivo ? "block" : "none"; }); // Quitar clase activa a todos const botones = document.querySelectorAll(".omb-boton-sidebar"); botones.forEach((btn) => btn.classList.remove("omb-boton-sidebar--active") ); // Marcar el que estaba activo antes const botonRestaurado = document.querySelector( `.omb-boton-sidebar[data-index="${indexActivo}"]` ); if (botonRestaurado) { botonRestaurado.classList.add( "omb-boton-sidebar--active" ); } } }); }); } } if (window.Drupal) { Drupal.behaviors.buscarInfografias = { attach: function (context) { initBuscarInfografias(context); }, }; } initBuscarInfografias(document); /////////////////////////////// ACTUALIDAD ////////////////////////////////////////////////// function buscarActualidad(context) { const boton_buscar_ = context.querySelector("#btnBuscar"); // Verifica si el botón existe y aún no tiene el evento asignado if ( boton_buscar_ && !boton_buscar_.classList.contains("evento-busqueda-asignado") ) { boton_buscar_.classList.add("evento-busqueda-asignado"); // Marcamos para evitar duplicación boton_buscar_.addEventListener("click", function () { // Deshabilitar segunda opción const opt3 = document.querySelector( "#orden > option:nth-child(2)" ); if (opt3) { opt3.disabled = true; } let ordenSelect = document.getElementById("orden"); let ordenSelect_key = document.getElementById("orden"); if (ordenSelect) { ordenSelect = ordenSelect.value; ordenSelect_key = ordenSelect_key.options[ordenSelect_key.selectedIndex].text; } let termino = document .getElementById("inputBusqueda") .value.trim(); if (!termino) { termino = "all"; } const url = `/actualidad?field_busqueda=${encodeURIComponent( termino )}&orden=${encodeURIComponent( ordenSelect )}&orden_key=${encodeURIComponent(ordenSelect_key)}&ajax=1`; console.log("click en búsqueda", url); let botonActivo = document.querySelector( ".omb-boton-sidebar--active" ); let indexActivo = botonActivo ? botonActivo.getAttribute("data-index") : 0; fetch(url) .then((response) => response.text()) .then((html) => { const tempDOM = document.createElement("div"); tempDOM.innerHTML = html; const newContent = tempDOM.querySelector( "#contenedor-vista-ajax" ); const contenedorActual = document.getElementById( "contenedor-vista-ajax" ); if (newContent && contenedorActual) { contenedorActual.innerHTML = newContent.innerHTML; Drupal.attachBehaviors(contenedorActual); // Oculta las vistas anteriores const viewsNoticias = document.querySelectorAll( ".omb-cards-noticias-container .views-element-container" ); viewsNoticias.forEach( (vista) => (vista.style.display = "none") ); //let botones = document.querySelectorAll('.omb-boton-sidebar'); //let botonActivo = document.querySelector('.omb-boton-sidebar--active'); //if (botonActivo) { //let index_ = botonActivo.getAttribute('data-index'); //console.log("Índice desde data-index:", index_); mostrarSoloVista(indexActivo); const botones = document.querySelectorAll(".omb-boton-sidebar"); botones.forEach((btn) => btn.classList.remove("omb-boton-sidebar--active") ); const botonRestaurado = document.querySelector( `.omb-boton-sidebar[data-index="${indexActivo}"]` ); if (botonRestaurado) { botonRestaurado.classList.add( "omb-boton-sidebar--active" ); } //botones.forEach(btn => btn.classList.remove('omb-boton-sidebar--active')); // const nuevoActivo = document.querySelector(`.omb-boton-sidebar[data-index="${index_}"]`); // if (nuevoActivo) { // nuevoActivo.classList.add('omb-boton-sidebar--active'); // } //} } }); }); } } if (window.Drupal) { Drupal.behaviors.buscarActualidad = { attach: function (context) { buscarActualidad(context); }, }; } buscarActualidad(document); /////////////////////////////// MOVILIDAD ////////////////////////////////////////////////// function initBuscarMovilidad(context) { const boton_buscar_ = context.querySelector("#btnBuscarmovilidad"); if ( boton_buscar_ && !boton_buscar_.classList.contains("evento-busqueda-asignado") ) { boton_buscar_.classList.add("evento-busqueda-asignado"); boton_buscar_.addEventListener("click", function () { const opt3 = document.querySelector( "#orden > option:nth-child(2)" ); if (opt3) opt3.disabled = true; let ordenSelect = document.getElementById("orden"); let ordenSelect_key = document.getElementById("orden"); if (ordenSelect) { ordenSelect = ordenSelect.value; ordenSelect_key = ordenSelect_key.options[ordenSelect_key.selectedIndex].text; } let termino = document .getElementById("inputBusqueda") .value.trim(); if (!termino) termino = "all"; const url = `/indicadores-movilidad?field_busqueda=${encodeURIComponent( termino )}&orden=${encodeURIComponent( ordenSelect )}&orden_key=${encodeURIComponent(ordenSelect_key)}&ajax=1`; console.log("click en b squeda movilidad", url); // --- Guardar informaci n del bot n activo antes del fetch --- const botonActivo = document.querySelector( ".omb-boton-sidebar--active" ); console.log("botonActivo (antes fetch):", botonActivo); let savedDataIndex = null; let savedPosition = null; let savedText = null; if (botonActivo) { savedDataIndex = botonActivo.getAttribute("data-index"); const allButtonsBefore = Array.from( document.querySelectorAll(".omb-boton-sidebar") ); savedPosition = allButtonsBefore.indexOf(botonActivo); savedText = botonActivo.textContent ? botonActivo.textContent.trim().slice(0, 200) : null; } else { savedPosition = 0; } // --- Fetch --- fetch(url) .then((response) => response.text()) .then((html) => { const tempDOM = document.createElement("div"); tempDOM.innerHTML = html; const newContent = tempDOM.querySelector( "#ombContainer-movilidad" ); const contenedorActual = document.getElementById( "ombContainer-movilidad" ); if (newContent && contenedorActual) { // Reemplazo del contenido contenedorActual.innerHTML = newContent.innerHTML; // Reattach Drupal behaviors si aplica if (window.Drupal) { Drupal.attachBehaviors(contenedorActual); } // Tomar listado de botones en todo el documento tras la actualizaci n const allButtonsAfter = Array.from( document.querySelectorAll(".omb-boton-sidebar") ); // Quitar clase active de todos (globalmente) para evitar dobles activos allButtonsAfter.forEach((b) => b.classList.remove("omb-boton-sidebar--active") ); // Intentar restaurar por data-index -> text -> posici n let botonRestaurado = null; if (savedDataIndex !== null) { // intento directo por selector (fallback a b squeda manual si falla) try { // usar un selector seguro si data-index tiene caracteres raros botonRestaurado = document.querySelector( `.omb-boton-sidebar[data-index="${savedDataIndex}"]` ); } catch (e) { // si hay problema con el selector, buscar manualmente botonRestaurado = allButtonsAfter.find( (b) => b.getAttribute && b.getAttribute("data-index") == savedDataIndex ); } if (!botonRestaurado) { // fallback: buscar por atributo iterando botonRestaurado = allButtonsAfter.find( (b) => b.getAttribute && b.getAttribute("data-index") == savedDataIndex ); } } if (!botonRestaurado && savedText) { botonRestaurado = allButtonsAfter.find( (b) => (b.textContent || "").trim().slice(0, 200) === savedText ); } if (!botonRestaurado && savedPosition !== null) { if (allButtonsAfter.length > 0) { const pos = Math.max( 0, Math.min(savedPosition, allButtonsAfter.length - 1) ); botonRestaurado = allButtonsAfter[pos]; } } console.log("restauraci n: ", { savedDataIndex, savedPosition, savedText, botonRestaurado, }); if (botonRestaurado) { botonRestaurado.classList.add( "omb-boton-sidebar--active" ); } // Determinar ndice de la vista a mostrar: // Preferimos buscar la lista de botones que controla las vistas dentro del contenedor actualizado. let botonesControl = Array.from( contenedorActual.querySelectorAll(".omb-boton-sidebar") ); if (!botonesControl.length) { botonesControl = allButtonsAfter; // fallback a global } let indexToShow = 0; if (botonRestaurado) { indexToShow = botonesControl.indexOf(botonRestaurado); if (indexToShow === -1) { // intentar encontrar por data-index const di = botonRestaurado.getAttribute && botonRestaurado.getAttribute("data-index"); indexToShow = botonesControl.findIndex( (b) => b.getAttribute && b.getAttribute("data-index") == di ); } } else { indexToShow = savedPosition || 0; } if (indexToShow < 0) indexToShow = 0; // Mostrar/ocultar vistas seg n indexToShow const viewsNoticias = contenedorActual.querySelectorAll( ".views-element-container" ); viewsNoticias.forEach((vista, idx) => { vista.style.display = idx === indexToShow ? "block" : "none"; }); } else { console.warn( "No se encontr #ombContainer-movilidad en la respuesta AJAX" ); } }) .catch((err) => { console.error("Error en fetch indicadores-movilidad:", err); }); }); } } if (window.Drupal) { Drupal.behaviors.buscarMovilidad = { attach: function (context) { initBuscarMovilidad(context); }, }; } initBuscarMovilidad(document); //////////////////////////////////////////////////////////////////////////////////// // Reasignar si cambia el DOM (MutationObserver para casos fuera de Drupal AJAX) // const observer = new MutationObserver(() => { // initBuscarTableros(document); // }); // observer.observe(document.body, { childList: true, subtree: true }); })(); const correoHTML = document.querySelector("#inputSuscribir"); const correoWebform = document.querySelector("#edit-correo"); const confirmarHTML = document.querySelector("#suscribirmeBoton"); const confirmarWebform = document.querySelector( "#edit-actions-01-submit" ); if (correoHTML && correoWebform) { const patronCorreo = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; correoHTML.addEventListener("input", function () { const valor = correoHTML.value; if (!patronCorreo.test(valor)) { correoHTML.setCustomValidity("Ingrese un correo v lido."); } else { correoHTML.setCustomValidity(""); } correoWebform.value = valor; }); if (confirmarHTML && confirmarWebform) { confirmarHTML.addEventListener("click", function (e) { e.preventDefault(); // Validar antes de enviar if (!patronCorreo.test(correoHTML.value)) { alert("Por favor ingrese un correo v lido."); return; } correoWebform.value = correoHTML.value; confirmarWebform.click(); }); } } /////////////////////////////////////////////// const opcionSeleccionada2 = document.querySelectorAll( ".omb-opcion-selecionada" ); const listasDeOpciones2 = document.querySelectorAll(".omb-opciones"); // Al cambiar el select de tipo de contenido function cerrarListaSiPierdeFoco(boton) { const lista = [...listasDeOpciones2].find( (l) => l.dataset.select === boton.dataset.select ); setTimeout(() => { const focoActual = document.activeElement; const focoEnBoton = boton.contains(focoActual); const focoEnLista = lista && lista.contains(focoActual); // Si el foco NO est ni en el bot n ni en la lista ? cierra if (!focoEnBoton && !focoEnLista) { lista?.classList.add("hidden"); boton.classList.remove("activo"); } }, 100); } opcionSeleccionada2.forEach((boton) => { const manejarEvento = () => { const valorSeleccionado = boton.dataset.select; listasDeOpciones2.forEach((lista) => { if (lista.dataset.select === valorSeleccionado) { lista.classList.toggle("hidden"); boton.classList.toggle("activo"); } else { lista.classList.add("hidden"); } }); }; boton.addEventListener("click", manejarEvento); boton.addEventListener("keydown", (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); manejarEvento(); } }); // Detecta si se va el foco desde el bot n boton.addEventListener("blur", () => cerrarListaSiPierdeFoco(boton)); }); // Detecta si se va el foco desde la lista tambi n listasDeOpciones2.forEach((lista) => { lista.addEventListener( "blur", (e) => { const boton = [...opcionSeleccionada2].find( (b) => b.dataset.select === lista.dataset.select ); cerrarListaSiPierdeFoco(boton); }, true ); // true para capturar blur de hijos }); // Cierra si haces clic fuera document.addEventListener("click", (e) => { const hizoClickEnSelect = [...opcionSeleccionada2].some((boton) => boton.contains(e.target) ); const hizoClickEnLista = [...listasDeOpciones2].some((lista) => lista.contains(e.target) ); if (!hizoClickEnSelect && !hizoClickEnLista) { listasDeOpciones2.forEach((lista) => { lista.classList.add("hidden"); }); opcionSeleccionada2.forEach((boton) => { boton.classList.remove("activo"); }); } }); /////////////////////////////////////////////// const swiperInteres = new Swiper(".sectionInteresSwiper", { slidesPerView: 1, spaceBetween: 30, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, pagination: { el: ".swiper-pagination", clickable: true, }, loop: true, autoplay: { delay: 3000, disableOnInteration: false, }, breakpoints: { 480: { slidesPerView: 1, spaceBetween: 30 }, 768: { slidesPerView: 2, spaceBetween: 30, }, 1024: { slidesPerView: 3, spaceBetween: 30 }, 1280: { slidesPerView: 4, spaceBetween: 30, }, }, }); let isPlayingIn = true; const pauseButtonTablerosInteresP = document.getElementById( "controlCarrucelInteres" ); if (pauseButtonTablerosInteresP) { pauseButtonTablerosInteresP.addEventListener("click", () => { pauseButtonTablerosInteresP.innerHTML = ""; if (isPlayingIn) { swiperInteres.autoplay.stop(); pauseButtonTablerosInteresP.innerHTML = botonReproducir; } else { swiperInteres.autoplay.start(); pauseButtonTablerosInteresP.innerHTML = botonPausar; } isPlayingIn = !isPlayingIn; }); } const swiperInteres_3 = new Swiper(".sectionInteresSwiper--3", { slidesPerView: 1, spaceBetween: 30, navigation: { nextEl: ".omb-boton-next", prevEl: ".omb-boton-prev", }, pagination: { el: ".swiper-pagination", clickable: true, }, loop: true, autoplay: { delay: 3000, disableOnInteration: false, }, breakpoints: { 480: { slidesPerView: 1, spaceBetween: 30 }, 768: { slidesPerView: 2, spaceBetween: 30, }, 1024: { slidesPerView: 3, spaceBetween: 30 }, 1280: { slidesPerView: 3, spaceBetween: 30, }, }, }); let isPlayingEv = true; const pauseButtonEvInteres = document.getElementById( "controlCarrucelInteres" ); if (pauseButtonTablerosInteres) { pauseButtonEvInteres.addEventListener("click", () => { pauseButtonTablerosInteres.innerHTML = ""; if (isPlayingEv) { swiperInteres_3.autoplay.stop(); pauseButtonEvInteres.innerHTML = botonReproducir; } else { swiperInteres_3.autoplay.start(); pauseButtonEvInteres.innerHTML = botonPausar; } isPlayingEv = !isPlayingEv; }); } ///////////sitemap (async () => { const container = document.getElementById("html-sitemap"); try { const response = await fetch("/sitemap.xml"); const xmlText = await response.text(); const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlText, "application/xml"); const urls = xmlDoc.getElementsByTagName("url"); const sections = {}; for (let i = 0; i < urls.length; i++) { const loc = urls[i].getElementsByTagName("loc")[0].textContent; const path = new URL(loc).pathname; if (/^\/node(\/|$)/.test(path)) continue; let section = path.split("/")[1] || "Inicio"; if (section.trim() === "") section = "Inicio"; if (!sections[section]) sections[section] = []; sections[section].push({ url: loc, path }); } let html = ""; Object.keys(sections) .sort() .forEach((section) => { html += `
Error cargando el sitemap.
"; console.error(error); } })(); //////// ///////////////// }, }; })(Drupal); /////////////////////////////// document.addEventListener("DOMContentLoaded", function () { // Verifica si la URL actual es exactamente "/tableros" if (window.location.pathname === "/tableros") { // Si no tiene ya los par metros, los a adimos if ( !window.location.search.includes("field_busqueda=all") || !window.location.search.includes("orden=tableros") ) { const nuevaURL = `${window.location.origin}${window.location.pathname}?field_busqueda=all&orden=tableros`; window.location.replace(nuevaURL); } } if (window.location.pathname === "/actualidad") { // Si no tiene ya los par metros, los a adimos if ( !window.location.search.includes("field_busqueda=all") || !window.location.search.includes("orden=actualidad_bloque") ) { const nuevaURL = `${window.location.origin}${window.location.pathname}?field_busqueda=all&orden=actualidad_bloque&orden_key=A-Z&ajax=1`; window.location.replace(nuevaURL); } } if (window.location.pathname === "/indicadores-movilidad") { // Si no tiene ya los par metros, los a adimos if ( !window.location.search.includes("field_busqueda=all") || !window.location.search.includes("orden=indicadores") ) { const nuevaURL = `${window.location.origin}${window.location.pathname}?field_busqueda=all&orden=indicadores&orden_key=A-Z&ajax=1`; window.location.replace(nuevaURL); } } if (window.location.pathname === "/publicaciones/infografias") { // Si no tiene ya los par metros, los a adimos if ( !window.location.search.includes("field_busqueda=all") || !window.location.search.includes("orden=infografias") ) { const nuevaURL = `${window.location.origin}${window.location.pathname}?field_busqueda=all&orden=infografias`; window.location.replace(nuevaURL); } } }); const aplicar_filtro = document.getElementById("btnAplicarFiltros"); if (aplicar_filtro) { aplicar_filtro.addEventListener("click", function (e) { e.preventDefault(); // Capturamos los selects const tipoSelect = document.getElementById("tipoContenido"); const categoriaSelect = document.getElementById("categoria"); const ordenSelect = document.getElementById("orden"); // Creamos los params con la URL actual const params = new URLSearchParams(window.location.search); // Actualizamos seg n lo escogido params.set("contenido", tipoSelect.value || "all"); params.set( "contenido_key", tipoSelect.options[tipoSelect.selectedIndex].text || "Todos" ); params.set("categoria", categoriaSelect.value || "all"); params.set( "categoria_key", categoriaSelect.options[categoriaSelect.selectedIndex].text || "Todos" ); params.set("orden", ordenSelect.value || "block_3"); params.set( "orden_key", ordenSelect.options[ordenSelect.selectedIndex].text || "A-Z" ); // Redirigimos window.location.search = params.toString(); }); } ////indicadores movilidad responsive const botonesAcordeonI = document.querySelectorAll(".omb-acordion-boton"); botonesAcordeonI.forEach((boton) => { boton.addEventListener("click", () => { const dataGrafica = boton.getAttribute("data-grafica"); const contenido = document.querySelector( `.omb-acordion-content[data-grafica="${dataGrafica}"]` ); const isOpen = contenido.classList.contains("abierto"); document.querySelectorAll(".omb-acordion-content").forEach((el) => { el.style.maxHeight = null; el.classList.remove("abierto"); }); document.querySelectorAll(".omb-acordion-boton").forEach((btn) => { btn.classList.remove("activo"); }); if (!isOpen) { contenido.style.maxHeight = contenido.scrollHeight + "px"; contenido.classList.add("abierto"); boton.classList.add("activo"); } }); }); ///// TABS ACTIVO document.addEventListener("DOMContentLoaded", () => { const rutaActual = window.location.pathname; const primerSegmento = rutaActual === "/" ? "/" : "/" + rutaActual.split("/")[1]; const elementosNav = document.querySelectorAll(".nav-item"); const elementosNavMobile = document.querySelectorAll(".omb-nav a"); const elementoIndicador = document.querySelector(".omb-nav-item-indicadores"); elementosNav.forEach((elemento) => { const enlace = elemento.querySelector("a"); if (!enlace) return; const hrefEnlace = enlace.getAttribute("href"); // Solo marcar "Inicio" si la ruta es exactamente "/" if (hrefEnlace === "/" && rutaActual === "/") { elemento.classList.add("is-active"); } // Para los demás, marcar solo si el primer segmento coincide exactamente else if ( hrefEnlace !== "/" && hrefEnlace.split("?")[0] === primerSegmento ) { elemento.classList.add("is-active"); } }); elementosNavMobile.forEach((elemento) => { const enlace = elemento; if (!enlace) return; const hrefEnlace = enlace.getAttribute("href"); // Solo marcar "Inicio" si la ruta es exactamente "/" if (hrefEnlace === "/" && rutaActual === "/") { elemento.classList.add("activo"); } // Para los demás, marcar solo si el primer segmento coincide exactamente else if ( hrefEnlace !== "/" && hrefEnlace.split("?")[0] === primerSegmento ) { elemento.classList.add("activo"); } }); if ( window.location.href.includes("/indicadores-movilidad") || window.location.href.includes("/indicadores-planes-y-politicas") ) { elementoIndicador.classList.add("activo"); } }); (function () { const contenedor = document.getElementById("grafica-mobile"); if (!contenedor) return; const jsonContainer = contenedor.querySelector(".field__item"); if (!jsonContainer) return; let raw = jsonContainer.textContent.trim(); try { const grafica = JSON.parse(raw); console.log("datos grafica", grafica); if ( !grafica.data || !Array.isArray(grafica.data) || grafica.data.length === 0 ) return; // Cargar Google Charts google.charts.load("current", { packages: ["corechart"] }); google.charts.setOnLoadCallback(drawChart); function drawChart() { const data = google.visualization.arrayToDataTable(grafica.data); // Asegurar que exista el div let chartDiv = document.getElementById(grafica.drupalChartDivId); if (!chartDiv) { chartDiv = document.createElement("div"); chartDiv.id = grafica.drupalChartDivId; chartDiv.style.width = "100%"; // ?? Importante: ocupa todo el ancho disponible chartDiv.style.height = "400px"; // altura adaptable contenedor.innerHTML = ""; contenedor.appendChild(chartDiv); } const chart = new google.visualization[grafica.visualization](chartDiv); // Dibujar gr fico chart.draw(data, grafica.options); } // ?? Redibujar al cambiar el tama o de la ventana (responsivo) window.addEventListener("resize", drawChart); } catch (error) { console.error("? Error al procesar el JSON:", error); } })(); (function () { const contenedor = document.getElementById("datos-tabla-mobile"); if (!contenedor) return; const jsonContainer = contenedor.querySelector(".field__item"); if (!jsonContainer) return; let raw = jsonContainer.textContent.trim(); // Funci n para convertir tabla a CSV y forzar descarga function descargarCSVDesdeTabla(tabla, nombreArchivo) { let csv = []; const filas = tabla.querySelectorAll("tr"); filas.forEach((fila) => { let columnas = fila.querySelectorAll("th, td"); let filaCSV = Array.from(columnas) .map((col) => `"${col.textContent.replace(/"/g, '""')}"`) .join(","); csv.push(filaCSV); }); const contenidoCSV = csv.join("\n"); const blob = new Blob([contenidoCSV], { type: "text/csv;charset=utf-8;", }); const enlace = document.createElement("a"); enlace.href = URL.createObjectURL(blob); enlace.download = nombreArchivo; enlace.style.display = "none"; document.body.appendChild(enlace); enlace.click(); document.body.removeChild(enlace); } try { const grafica = JSON.parse(raw); const data = grafica.data; console.log("datos tabla", data); if (!Array.isArray(data) || data.length === 0) return; // Crear tabla const tabla = document.createElement("table"); tabla.className = "table table-striped table-hover table-indicadores"; tabla.style.width = "100%"; tabla.style.margin = "auto"; tabla.style.fontSize = "14px"; tabla.style.color = "#000"; // Crear thead const thead = document.createElement("thead"); thead.className = "thead-light sticky-top"; const headRow = document.createElement("tr"); data[0].forEach((header, i) => { const th = document.createElement("th"); th.textContent = header; th.style.textAlign = "center"; th.style.color = "#000"; th.style.backgroundColor = "#DBF000"; th.style.whitespace = "normal"; th.style.wordbreak = "break-word"; if (i === 0) th.className = "sticky-col"; headRow.appendChild(th); }); thead.appendChild(headRow); tabla.appendChild(thead); // Crear tbody const tbody = document.createElement("tbody"); data.slice(1).forEach((fila) => { const tr = document.createElement("tr"); fila.forEach((celda, i) => { const td = document.createElement("td"); td.textContent = celda; td.style.textAlign = i === 0 ? "center" : "right"; if (i === 0) td.className = "sticky-col"; tr.appendChild(td); }); tbody.appendChild(tr); }); tabla.appendChild(tbody); // Crear bot n de descarga const botonDescarga = document.createElement("button"); botonDescarga.textContent = "Descargar CSV"; botonDescarga.className = "btn btn-primary"; botonDescarga.style.margin = "10px 0"; botonDescarga.style.display = "block"; botonDescarga.style.width = "100%"; botonDescarga.addEventListener("click", function () { descargarCSVDesdeTabla(tabla, "datos.csv"); }); // Contenedor responsivo (scroll en m vil) const responsiveWrapper = document.createElement("div"); responsiveWrapper.style.overflowX = "auto"; responsiveWrapper.style.width = "100%"; responsiveWrapper.style.maxHeight = "70vh"; responsiveWrapper.style.border = "1px solid #ddd"; responsiveWrapper.style.padding = "10px"; responsiveWrapper.style.background = "#fff"; // Agregar bot n dentro del wrapper responsiveWrapper.appendChild(botonDescarga); responsiveWrapper.appendChild(tabla); // Reemplazar contenido del contenedor contenedor.innerHTML = ""; contenedor.appendChild(responsiveWrapper); } catch (error) { console.error("? Error al procesar el JSON:", error); } })(); const nav = document.querySelector(".navbar-expand-lg"); function handleScroll() { const scrollStart = 144; if (window.innerWidth >= 1024) { if (window.scrollY >= scrollStart) { nav.style.position = "fixed"; nav.style.zIndez = "50"; nav.style.top = "0"; nav.style.width = "100%"; } else { nav.style.position = "static"; nav.style.top = ""; // nav.style.display = "flex"; } } else { nav.style.position = "static"; } } window.addEventListener("scroll", handleScroll); window.addEventListener("resize", handleScroll); ///////////////////////////////////// Nav mobil ///////////////////////////////// const navMobile = document.querySelector(".omb-nav"); const botonMenu = document.getElementById("botonMenu"); // Función para abrir/cerrar menú function toggleMenu(forceClose = false) { if (forceClose || navMobile.style.display === "flex") { navMobile.style.display = "none"; botonMenu.innerHTML = `