/** * FUNCIONES COMPARTIDAS * Utilidades reutilizables en todas las calculadoras */ // ═══════════════════════════════════════════════════════════ // FUNCIONES DE UX Y NAVEGACIÓN // ═══════════════════════════════════════════════════════════ /** * Detecta si estamos en un dispositivo móvil/tablet */ function esMobile() { return window.innerWidth < 1024; } /** * Cierra el teclado virtual en móviles */ function cerrarTeclado() { if (document.activeElement) { document.activeElement.blur(); } } /** * Hace scroll suave hacia un elemento con compensación del header */ function scrollSuaveHacia(elementoId) { const elemento = document.getElementById(elementoId) || document.querySelector(elementoId); if (elemento) { elemento.scrollIntoView({ behavior: 'smooth', block: 'start' }); } } /** * Aplica destello sutil a la tarjeta de resultado */ function aplicarDestelloResultado() { const resultadoCard = document.querySelector('.resultado-card'); if (resultadoCard) { // Remover clase si ya existe (para poder repetir la animación) resultadoCard.classList.remove('destello-sutil'); // Forzar reflow para reiniciar la animación void resultadoCard.offsetWidth; // Agregar clase de animación resultadoCard.classList.add('destello-sutil'); // Remover clase después de la animación setTimeout(() => { resultadoCard.classList.remove('destello-sutil'); }, 500); } } /** * Maneja el clic del botón Calcular * - En móvil: cierra teclado, hace scroll y destello * - En desktop: solo destello */ function manejarBotonCalcular(calculadoraNombre) { const mobile = esMobile(); if (mobile) { // Cerrar teclado cerrarTeclado(); // Esperar un momento para que se cierre el teclado setTimeout(() => { // Scroll hacia resultado const resultadoCard = document.querySelector('.resultado-card'); if (resultadoCard) { resultadoCard.scrollIntoView({ behavior: 'smooth', block: 'start' }); } // Destello después del scroll setTimeout(() => { aplicarDestelloResultado(); }, 400); }, 100); } else { // En desktop solo destello aplicarDestelloResultado(); } } /** * Inicializa los botones de calcular en cada calculadora */ function inicializarBotonesCalcular() { // Botón Calcular ISR const btnCalcularISR = document.getElementById('btn-calcular-isr'); if (btnCalcularISR) { btnCalcularISR.addEventListener('click', () => { manejarBotonCalcular('isr'); }); } // Botón Calcular Aguinaldo const btnCalcularAguinaldo = document.getElementById('btn-calcular-aguinaldo'); if (btnCalcularAguinaldo) { btnCalcularAguinaldo.addEventListener('click', () => { manejarBotonCalcular('aguinaldo'); }); } // Botón Calcular Finiquito const btnCalcularFiniquito = document.getElementById('btn-calcular-finiquito'); if (btnCalcularFiniquito) { btnCalcularFiniquito.addEventListener('click', () => { manejarBotonCalcular('finiquito'); }); } } /** * Inicializa los botones "Ver desglose paso a paso" */ function inicializarBotonesVerDesglose() { // Botón Ver Desglose ISR const btnVerDesgloseISR = document.getElementById('btn-ver-desglose-isr'); if (btnVerDesgloseISR) { btnVerDesgloseISR.addEventListener('click', (e) => { e.preventDefault(); scrollSuaveHacia('desglose-detallado-isr'); }); } // Botón Ver Desglose Aguinaldo const btnVerDesgloseAguinaldo = document.getElementById('btn-ver-desglose-aguinaldo'); if (btnVerDesgloseAguinaldo) { btnVerDesgloseAguinaldo.addEventListener('click', (e) => { e.preventDefault(); scrollSuaveHacia('desglose-detallado-aguinaldo'); }); } // Botón Ver Desglose Finiquito const btnVerDesgloseFiniquito = document.getElementById('btn-ver-desglose-finiquito'); if (btnVerDesgloseFiniquito) { btnVerDesgloseFiniquito.addEventListener('click', (e) => { e.preventDefault(); scrollSuaveHacia('desglose-detallado-finiquito'); }); } } /** * Inicializa toda la funcionalidad compartida */ function inicializarShared() { inicializarBotonesCalcular(); inicializarBotonesVerDesglose(); } // Inicializar cuando el DOM esté listo if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', inicializarShared); } else { inicializarShared(); } // ═══════════════════════════════════════════════════════════ // FORMATEO DE MONEDA // ═══════════════════════════════════════════════════════════ /** * Formatea un número como moneda mexicana * @param {number} cantidad - Cantidad a formatear * @param {boolean} incluirCentavos - Si incluye centavos o no * @returns {string} - Cantidad formateada */ function formatearMoneda(cantidad, incluirCentavos = true) { if (isNaN(cantidad) || cantidad === null || cantidad === undefined) { return '$0.00'; } const opciones = { style: 'currency', currency: 'MXN', minimumFractionDigits: incluirCentavos ? 2 : 0, maximumFractionDigits: incluirCentavos ? 2 : 0 }; return new Intl.NumberFormat('es-MX', opciones).format(cantidad); } /** * Formatea un número sin símbolo de moneda * @param {number} cantidad - Cantidad a formatear * @returns {string} - Cantidad formateada */ function formatearNumero(cantidad, decimales = 2) { if (isNaN(cantidad) || cantidad === null || cantidad === undefined) { return '0'; } return new Intl.NumberFormat('es-MX', { minimumFractionDigits: decimales, maximumFractionDigits: decimales }).format(cantidad); } /** * Remueve formato de moneda y devuelve número * @param {string} texto - Texto con formato de moneda * @returns {number} - Número sin formato */ function parsearMoneda(texto) { if (!texto) return 0; // Remover $, comas y espacios const limpio = texto.toString().replace(/[$,\s]/g, ''); const numero = parseFloat(limpio); return isNaN(numero) ? 0 : numero; } // ═══════════════════════════════════════════════════════════ // VALIDACIÓN DE INPUTS // ═══════════════════════════════════════════════════════════ /** * Valida que un input sea un número positivo * @param {HTMLInputElement} input - Elemento input * @returns {boolean} - true si es válido */ function validarNumeroPositivo(input) { const valor = parseFloat(input.value); if (isNaN(valor) || valor < 0) { input.classList.add('error'); return false; } input.classList.remove('error'); return true; } /** * Limita un input a solo números * @param {Event} e - Evento de teclado */ function soloNumeros(e) { const char = String.fromCharCode(e.which); if (!/[0-9.]/.test(char)) { e.preventDefault(); } } /** * Formatea input de moneda en tiempo real * @param {HTMLInputElement} input - Elemento input */ function formatearInputMoneda(input) { let valor = input.value.replace(/[^0-9.]/g, ''); // Solo un punto decimal const partes = valor.split('.'); if (partes.length > 2) { valor = partes[0] + '.' + partes.slice(1).join(''); } input.value = valor; } // ═══════════════════════════════════════════════════════════ // MANEJO DE FECHAS // ═══════════════════════════════════════════════════════════ /** * Calcula la diferencia en años entre dos fechas * @param {Date|string} fechaInicio - Fecha de inicio * @param {Date|string} fechaFin - Fecha de fin * @returns {number} - Años de diferencia (con decimales) */ function calcularAniosEntreFechas(fechaInicio, fechaFin) { const inicio = new Date(fechaInicio); const fin = new Date(fechaFin); if (isNaN(inicio.getTime()) || isNaN(fin.getTime())) { return 0; } const milisegundos = fin - inicio; const dias = milisegundos / (1000 * 60 * 60 * 24); const anios = dias / 365.25; return anios; } /** * Calcula días entre dos fechas * @param {Date|string} fechaInicio - Fecha de inicio * @param {Date|string} fechaFin - Fecha de fin * @returns {number} - Días de diferencia */ function calcularDiasEntreFechas(fechaInicio, fechaFin) { const inicio = new Date(fechaInicio); const fin = new Date(fechaFin); if (isNaN(inicio.getTime()) || isNaN(fin.getTime())) { return 0; } const milisegundos = fin - inicio; const dias = Math.floor(milisegundos / (1000 * 60 * 60 * 24)); return dias; } /** * Obtiene el año actual desde los datos fiscales * @returns {number} - Año fiscal actual */ function obtenerAnioActual() { return FISCAL_CONFIG_2026.metadatos.anioFiscal; } // ═══════════════════════════════════════════════════════════ // DEBOUNCE PARA CÁLCULOS EN TIEMPO REAL // ═══════════════════════════════════════════════════════════ /** * Crea una función con debounce para evitar cálculos excesivos * @param {Function} func - Función a ejecutar * @param {number} delay - Delay en milisegundos (default 300ms) * @returns {Function} - Función con debounce */ function debounce(func, delay = 300) { let timeoutId; return function(...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => { func.apply(this, args); }, delay); }; } // ═══════════════════════════════════════════════════════════ // ANIMACIONES Y EFECTOS VISUALES // ═══════════════════════════════════════════════════════════ /** * Anima el cambio de un número en pantalla * @param {HTMLElement} elemento - Elemento a animar * @param {number} valorInicial - Valor inicial * @param {number} valorFinal - Valor final * @param {number} duracion - Duración en ms */ function animarNumero(elemento, valorInicial, valorFinal, duracion = 500) { const inicio = performance.now(); const diferencia = valorFinal - valorInicial; function actualizar(tiempo) { const progreso = Math.min((tiempo - inicio) / duracion, 1); const valorActual = valorInicial + (diferencia * progreso); elemento.textContent = formatearMoneda(valorActual); if (progreso < 1) { requestAnimationFrame(actualizar); } } requestAnimationFrame(actualizar); } /** * Muestra un elemento con fade in * @param {HTMLElement} elemento - Elemento a mostrar */ function fadeIn(elemento) { elemento.style.opacity = '0'; elemento.style.display = 'block'; let opacity = 0; const interval = setInterval(() => { if (opacity >= 1) { clearInterval(interval); } elemento.style.opacity = opacity; opacity += 0.1; }, 30); } // ═══════════════════════════════════════════════════════════ // MANEJO DEL MENÚ MÓVIL // ═══════════════════════════════════════════════════════════ /** * Inicializa el menú hamburguesa móvil */ function inicializarMenuMovil() { const menuToggle = document.getElementById('menu-toggle'); const navMenu = document.getElementById('nav-menu'); if (menuToggle && navMenu) { menuToggle.addEventListener('click', () => { const expanded = menuToggle.getAttribute('aria-expanded') === 'true'; menuToggle.setAttribute('aria-expanded', !expanded); navMenu.classList.toggle('active'); }); // Cerrar menú al hacer clic en un enlace const enlaces = navMenu.querySelectorAll('a'); enlaces.forEach(enlace => { enlace.addEventListener('click', () => { menuToggle.setAttribute('aria-expanded', 'false'); navMenu.classList.remove('active'); }); }); } } // ═══════════════════════════════════════════════════════════ // SCROLL SUAVE // ═══════════════════════════════════════════════════════════ /** * Hace scroll suave a un elemento * @param {string} selector - Selector del elemento */ function scrollSuave(selector) { const elemento = document.querySelector(selector); if (elemento) { elemento.scrollIntoView({ behavior: 'smooth', block: 'start' }); } } // ═══════════════════════════════════════════════════════════ // PAGE TRANSITIONS - Smooth Navigation // ═══════════════════════════════════════════════════════════ /** * Intercepta clics en enlaces internos para transición suave */ function inicializarTransicionesDePagina() { document.addEventListener('click', (e) => { const enlace = e.target.closest('a'); // Ignorar si no es un enlace if (!enlace) return; const href = enlace.getAttribute('href'); const target = enlace.getAttribute('target'); // Ignorar enlaces externos, target="_blank", anclas, mailto, wa.me if (!href) return; if (href.startsWith('#')) return; if (href.startsWith('mailto:')) return; if (href.includes('wa.me')) return; if (target === '_blank') return; if (enlace.hasAttribute('download')) return; // Ignorar clics con modificadores (Ctrl/Cmd/Shift) if (e.ctrlKey || e.metaKey || e.shiftKey) return; // Solo interceptar enlaces internos .html del mismo sitio if (!href.endsWith('.html') && !href.endsWith('/')) return; // Verificar que sea del mismo origen try { const url = new URL(href, window.location.href); if (url.origin !== window.location.origin) return; } catch { // Si falla el parsing, asumir que es relativo y válido } // Interceptar la navegación e.preventDefault(); // Agregar clase de salida document.body.classList.add('page-leaving'); // Navegar después de la animación de salida setTimeout(() => { window.location.href = href; }, 140); }); } /** * Maneja el evento pageshow para limpiar clase al usar botón Atrás */ function manejarBfcache() { window.addEventListener('pageshow', (e) => { // Remover clase inmediatamente (importante para bfcache) document.body.classList.remove('page-leaving'); }); } // ═══════════════════════════════════════════════════════════ // INICIALIZACIÓN AL CARGAR LA PÁGINA // ═══════════════════════════════════════════════════════════ document.addEventListener('DOMContentLoaded', () => { // Inicializar menú móvil inicializarMenuMovil(); // Inicializar transiciones de página inicializarTransicionesDePagina(); manejarBfcache(); // Marcar página activa en navegación const rutaActual = window.location.pathname; const enlaces = document.querySelectorAll('.nav-menu a'); enlaces.forEach(enlace => { const href = enlace.getAttribute('href'); if (rutaActual.includes(href) && href !== '/') { enlace.classList.add('active'); } else if (rutaActual === '/' && href === '/') { enlace.classList.add('active'); } }); });