PageSourceSearch

https://www.directoriocubano.info/wp-content/plugins/loteria-profesional/loteria-ajax.js

js directoriocubano.info collected 2026-09-24 18:26:25 UTC 16,445 bytes, 427 lines download raw bytes

1/**
2 * JavaScript para funcionalidades AJAX del plugin de lotería
3 * Versión 2.1 - Completa y Corregida
4 */
5
6(function($) {
7    'use strict';
8
9    // Función para cambiar fecha de los resultados
10    window.cambiarFecha = function(tipo, fecha) {
11        // Buscar el contenedor específico del tipo
12        const container = $('#loteria-' + tipo);
13        const innerContent = container.find('.loteria-inner-content');
14        
15        // Si no existe el contenedor interno, usar el contenedor principal
16        const targetElement = innerContent.length > 0 ? innerContent : container;
17        
18        // Guardar el HTML original
19        const originalHtml = targetElement.html();
20        
21        // Mostrar indicador de carga
22        targetElement.html('<div class="loteria-loading">Cargando resultados...</div>');
23        
24        // Realizar petición AJAX
25        const data = {
26            'action': 'obtener_resultados_fecha',
27            'fecha': fecha,
28            'tipo': tipo,
29            'nonce': loteria_ajax.nonce
30        };
31
32        $.post(loteria_ajax.ajax_url, data, function(response) {
33            if (response.success) {
34                // Actualizar solo el contenido interno, no todo el contenedor
35                targetElement.html(response.data);
36                
37                // Re-vincular eventos para el nuevo selector de fecha
38                bindDateSelector('#fecha-selector-' + tipo);
39            } else {
40                targetElement.html('<div class="loteria-error">Error al cargar los resultados: ' + (response.data || 'Error desconocido') + '</div>');
41                
42                // Restaurar contenido original después de 3 segundos
43                setTimeout(function() {
44                    targetElement.html(originalHtml);
45                    bindDateSelector('#fecha-selector-' + tipo);
46                }, 3000);
47            }
48        }).fail(function(xhr, status, error) {
49            console.error('Error AJAX:', error);
50            targetElement.html('<div class="loteria-error">Error de conexión. Inténtalo de nuevo.</div>');
51            
52            // Restaurar contenido original después de 3 segundos
53            setTimeout(function() {
54                targetElement.html(originalHtml);
55                bindDateSelector('#fecha-selector-' + tipo);
56            }, 3000);
57        });
58    };
59
60    // Función para vincular eventos a selectores de fecha
61    function bindDateSelector(selector) {
62        $(selector).off('change').on('change', function() {
63            const tipo = $(this).data('tipo');
64            const fecha = $(this).val();
65            if (tipo && fecha) {
66                cambiarFecha(tipo, fecha);
67            }
68        });
69    }
70
71    // Función para refrescar resultados automáticamente
72    window.refrescarResultados = function(tipo) {
73        const fechaSelector = $('#fecha-selector-' + tipo);
74        const fechaSeleccionada = fechaSelector.val() || new Date().toISOString().split('T')[0];
75        cambiarFecha(tipo, fechaSeleccionada);
76    };
77
78    // Inicialización cuando el documento esté listo
79    $(document).ready(function() {
80        
81        // Agregar estilos CSS para el indicador de carga
82        const loadingStyles = `
83            <style id="loteria-custom-styles">
84                .loteria-loading {
85                    text-align: center;
86                    padding: 40px;
87                    font-size: 16px;
88                    color: #667eea;
89                    background: #f8f9ff;
90                    border-radius: 16px;
91                    margin: 20px 0;
92                }
93                
94                .loteria-loading:before {
95                    content: '';
96                    display: inline-block;
97                    width: 20px;
98                    height: 20px;
99                    border: 2px solid #667eea;
100                    border-radius: 50%;
101                    border-top-color: transparent;
102                    animation: spin 1s ease-in-out infinite;
103                    margin-right: 10px;
104                    vertical-align: middle;
105                }
106                
107                .loteria-error {
108                    text-align: center;
109                    padding: 20px;
110                    background: #ffe6e6;
111                    color: #c0392b;
112                    border-radius: 12px;
113                    margin: 20px 0;
114                    border: 1px solid #ffcccc;
115                }
116                
117                @keyframes spin {
118                    to { transform: rotate(360deg); }
119                }
120                
121                /* Efecto hover en selectores de fecha */
122                .selector-fecha select:hover {
123                    border-color: #667eea;
124                    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
125                }
126                
127                .selector-fecha select:focus {
128                    outline: none;
129                    border-color: #667eea;
130                    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
131                }
132                
133                /* Animaciones suaves para cambios */
134                .loteria-container {
135                    transition: opacity 0.3s ease-in-out;
136                }
137                
138                .numero-circulo {
139                    transition: transform 0.2s ease;
140                }
141                
142                .numero-circulo:hover {
143                    transform: scale(1.1);
144                    cursor: pointer;
145                }
146                
147                /* Estilos para el aviso de fallback */
148                .loteria-fallback-notice {
149                    animation: slideDown 0.5s ease-out;
150                }
151                
152                @keyframes slideDown {
153                    from {
154                        opacity: 0;
155                        transform: translateY(-20px);
156                    }
157                    to {
158                        opacity: 1;
159                        transform: translateY(0);
160                    }
161                }
162                
163                /* Responsive mejorado */
164                @media (max-width: 768px) {
165                    .significados-tabla {
166                        padding: 15px;
167                    }
168                    
169                    .significado-item {
170                        padding: 10px 0;
171                    }
172                    
173                    .significado-numero {
174                        width: 40px;
175                        height: 40px;
176                        font-size: 14px;
177                    }
178                    
179                    .significado-texto {
180                        font-size: 14px;
181                        line-height: 1.3;
182                    }
183                    
184                    .loteria-fallback-notice {
185                        font-size: 13px;
186                        padding: 10px 15px;
187                    }
188                }
189            </style>
190        `;
191        
192        if (!$('#loteria-custom-styles').length) {
193            $('head').append(loadingStyles);
194        }
195        
196        // Función para vincular todos los selectores de fecha
197        function bindAllDateSelectors() {
198            $('.selector-fecha-loteria').each(function() {
199                bindDateSelector('#' + $(this).attr('id'));
200            });
201        }
202        
203        // Manejar cambios en selectores de fecha existentes
204        bindAllDateSelectors();
205        
206        // Agregar funcionalidad de teclado para navegación
207        $(document).on('keydown', function(e) {
208            if (e.ctrlKey || e.metaKey) {
209                switch(e.keyCode) {
210                    case 37: // Flecha izquierda - día anterior
211                        e.preventDefault();
212                        navegarFecha('anterior');
213                        break;
214                    case 39: // Flecha derecha - día siguiente
215                        e.preventDefault();
216                        navegarFecha('siguiente');
217                        break;
218                    case 82: // R - refrescar
219                        e.preventDefault();
220                        refrescarTodosLosResultados();
221                        break;
222                }
223            }
224        });
225        
226        // Función para navegación con teclado
227        function navegarFecha(direccion) {
228            $('.selector-fecha-loteria').each(function() {
229                const selector = $(this);
230                const opciones = selector.find('option');
231                const indiceActual = selector.prop('selectedIndex');
232                let nuevoIndice;
233                
234                if (direccion === 'anterior' && indiceActual < opciones.length - 1) {
235                    nuevoIndice = indiceActual + 1;
236                } else if (direccion === 'siguiente' && indiceActual > 0) {
237                    nuevoIndice = indiceActual - 1;
238                } else {
239                    return;
240                }
241                
242                selector.prop('selectedIndex', nuevoIndice);
243                selector.trigger('change');
244            });
245        }
246        
247        // Función para refrescar todos los resultados
248        function refrescarTodosLosResultados() {
249            $('.selector-fecha-loteria').each(function() {
250                const tipo = $(this).data('tipo');
251                if (tipo) {
252                    refrescarResultados(tipo);
253                }
254            });
255        }
256        
257        // Auto-actualización cada 5 minutos para resultados de hoy
258        let autoUpdateInterval = setInterval(function() {
259            $('.selector-fecha-loteria').each(function() {
260                const fechaSeleccionada = $(this).val();
261                const hoy = new Date().toISOString().split('T')[0];
262                
263                // Solo auto-actualizar si es la fecha de hoy
264                if (fechaSeleccionada === hoy) {
265                    const tipo = $(this).data('tipo');
266                    if (tipo) {
267                        console.log('Auto-actualizando resultados de ' + tipo + ' para hoy');
268                        refrescarResultados(tipo);
269                    }
270                }
271            });
272        }, 5 * 60 * 1000); // 5 minutos
273        
274        // Limpiar interval cuando se abandona la página
275        $(window).on('beforeunload', function() {
276            if (autoUpdateInterval) {
277                clearInterval(autoUpdateInterval);
278            }
279        });
280        
281        // Mejorar accesibilidad
282        $(document).on('mouseenter', '.numero-circulo', function() {
283            $(this).attr('title', 'Número ' + $(this).text().trim());
284        });
285        
286        $('.numero-circulo').attr('role', 'button').attr('tabindex', '0');
287        $('.numero-fireball').attr('aria-label', 'Número Fireball');
288        
289        // Agregar eventos de teclado para elementos focusables
290        $(document).on('keypress', '.numero-circulo', function(e) {
291            if (e.which === 13 || e.which === 32) { // Enter o Espacio
292                $(this).click();
293            }
294        });
295        
296        // Manejar clics en números para mostrar su significado en un tooltip
297        $(document).on('click', '.numero-circulo', function() {
298            const numero = $(this).text().trim();
299            const esFireball = $(this).hasClass('numero-fireball');
300            const mensaje = esFireball ? 
301                `Fireball: ${numero}` : 
302                `Número: ${numero}`;
303            
304            // Crear tooltip temporal
305            const tooltip = $('<div class="numero-tooltip">' + mensaje + '</div>');
306            tooltip.css({
307                position: 'absolute',
308                background: '#333',
309                color: 'white',
310                padding: '5px 10px',
311                borderRadius: '4px',
312                fontSize: '12px',
313                zIndex: 1000,
314                opacity: 0
315            });
316            
317            $('body').append(tooltip);
318            
319            const offset = $(this).offset();
320            tooltip.css({
321                top: offset.top - tooltip.outerHeight() - 10,
322                left: offset.left + ($(this).outerWidth() / 2) - (tooltip.outerWidth() / 2)
323            }).animate({ opacity: 1 }, 200);
324            
325            setTimeout(function() {
326                tooltip.animate({ opacity: 0 }, 200, function() {
327                    tooltip.remove();
328                });
329            }, 2000);
330        });
331        
332        // Detectar cambios en el DOM para re-vincular eventos
333        const observer = new MutationObserver(function(mutations) {
334            mutations.forEach(function(mutation) {
335                if (mutation.type === 'childList') {
336                    // Re-vincular selectores de fecha si se agregaron nuevos elementos
337                    setTimeout(bindAllDateSelectors, 100);
338                }
339            });
340        });
341        
342        // Observar cambios en los contenedores de lotería
343        $('.loteria-container').each(function() {
344            observer.observe(this, { childList: true, subtree: true });
345        });
346        
347        // Función para verificar y mostrar mensaje si no hay resultados de hoy
348        function verificarResultadosHoy() {
349            $('.selector-fecha-loteria').each(function() {
350                const tipo = $(this).data('tipo');
351                const fechaSeleccionada = $(this).val();
352                const hoy = new Date().toISOString().split('T')[0];
353                
354                if (fechaSeleccionada === hoy && tipo) {
355                    const container = $('#loteria-' + tipo);
356                    const hayResultados = container.find('.loteria-numeros .numero-circulo').length > 0;
357                    
358                    if (!hayResultados) {
359                        console.log('No hay resultados de ' + tipo + ' para hoy, verificando ayer...');
360                        // El fallback ya está manejado en PHP
361                    }
362                }
363            });
364        }
365        
366        // Verificar al cargar la página
367        setTimeout(verificarResultadosHoy, 1000);
368        
369        // Agregar indicador de última actualización
370        function mostrarUltimaActualizacion() {
371            const ahora = new Date();
372            const hora = ahora.getHours().toString().padStart(2, '0');
373            const minutos = ahora.getMinutes().toString().padStart(2, '0');
374            const timeString = `${hora}:${minutos}`;
375            
376            $('.loteria-container').each(function() {
377                if (!$(this).find('.ultima-actualizacion').length) {
378                    const updateInfo = $('<div class="ultima-actualizacion" style="text-align: center; font-size: 11px; color: #999; margin-top: 10px;">Última actualización: ' + timeString + '</div>');
379                    $(this).append(updateInfo);
380                } else {
381                    $(this).find('.ultima-actualizacion').text('Última actualización: ' + timeString);
382                }
383            });
384        }
385        
386        // Mostrar última actualización al cargar
387        mostrarUltimaActualizacion();
388        
389        // Actualizar timestamp cuando se refresque
390        $(document).on('ajaxComplete', function(event, xhr, settings) {
391            if (settings.data && settings.data.includes('obtener_resultados_fecha')) {
392                mostrarUltimaActualizacion();
393            }
394        });
395        
396        console.log('Plugin de lotería v2.1 inicializado correctamente');
397    });
398    
399    // Función pública para uso externo
400    window.LoteriaPlugin = {
401        cambiarFecha: cambiarFecha,
402        refrescarResultados: refrescarResultados,
403        version: '2.1',
404        
405        // Nueva función para refrescar ambos sorteos
406        refrescarTodos: function() {
407            refrescarResultados('tarde');
408            refrescarResultados('noche');
409        },
410        
411        // Función para obtener el estado actual
412        obtenerEstado: function() {
413            const estado = {};
414            $('.selector-fecha-loteria').each(function() {
415                const tipo = $(this).data('tipo');
416                if (tipo) {
417                    estado[tipo] = {
418                        fecha: $(this).val(),
419                        hayResultados: $('#loteria-' + tipo).find('.loteria-numeros .numero-circulo').length > 0
420                    };
421                }
422            });
423            return estado;
424        }
425    };
426
427})(jQuery);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.