PageSourceSearch

https://static.eltribuno.com/js/functions.445adb6.js

js eltribuno.com collected 2026-09-24 09:45:28 UTC 77,249 bytes, 2,148 lines download raw bytes

1//import { try } from "bluebird";
2
3var actual = window.location.pathname;
4var stickyalert=true;
5var players =  [];
6var via_ajax = false;
7var request_render = false;
8var to_loading = null;
9
10jQuery.event.special.touchstart = {
11    setup: function (_, ns, handle) {
12        if (ns.includes("noPreventDefault")) {
13            this.addEventListener("touchstart", handle, { passive: false });
14        } else {
15            this.addEventListener("touchstart", handle, { passive: true });
16        }
17    }
18};
19
20window.mobilecheck = function() {
21    var check = false;
22    (function(a) {
23        if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true
24    })(navigator.userAgent || navigator.vendor || window.opera);
25return check;
26}
27
28var ismobile = mobilecheck();
29
30function getUrlParts(url) {
31    var a = document.createElement('a');
32    a.href = url;
33
34    return {
35        original: url,
36        href: a.href,
37        host: a.host,
38        hostname: a.hostname,
39        port: a.port,
40        pathname: a.pathname,
41        protocol: a.protocol,
42        hash: a.hash,
43        search: a.search
44    };
45}
46
47function primerocon_texto(){
48    var flag=false;
49    var posicion=0;
50    for (var i = 0; i < $(".cuerpo p").length; i++) {
51        if($(".cuerpo p").eq(i).text().length > 20 && !flag){
52            posicion=i;
53            flag=true;
54        }
55    }
56    return posicion
57}
58
59var playerYB = null;
60var playerYB_multimedia = null;
61
62var cookie = '';
63var vot = '';
64var id_encuesta = '';
65var token = '';
66var clase_e='';
67function init_encuesta(clase) {
68    cookie = get_cookies();
69    clase_e= clase;    
70    $("." + clase).each(function(index, el) {
71        var elemento = $(this);    
72        elemento.find('.cont_recaptcha').css('display', 'none');
73        if (elemento.hasClass('voto')) {            
74            var progres = elemento.find('.progress-bar');
75            progres.each(function() {
76                var width = (100 *  $(this).parent().attr('data-cont') /  $(this).parent().attr('data-votos')).toFixed(2) + "%";
77                if (width == 'NaN%')
78                    width = '0%';
79                $(this).css('width', width);
80                $(this).find('.valor').text(width).css('display', 'flex');
81                $(this).find('.opcion').css('color','#848484');
82            });
83        } else if (cookie["voto_" + elemento.attr('data-id')]) {            
84            elemento.addClass('voto');
85            var progres = elemento.find('.progress-bar');
86            progres.each(function() {
87                var width = (100 *  $(this).parent().attr('data-cont') /  $(this).parent().attr('data-votos')).toFixed(2) + "%";
88                if (width == 'NaN%')
89                    width = '0%';
90                $(this).css('width', width);
91                $(this).find('.valor').text(width).css('display', 'flex');
92                $(this).find('.opcion').css('color','#848484');
93            });        
94        } else{            
95            $.get('/get-recaptcha', { callback: "correctCaptcha_encuesta"}, function(data){                
96                elemento.find('.cont_recaptcha').html(data);
97            });  
98        }
99    });
100
101
102    $(document).on('click', '.progress', function(event) {
103        event.stopPropagation();
104        event.preventDefault();
105        if ($(this).parents('.' + clase).hasClass('voto')) {
106            return '';
107        } else {
108            cookie = $(this).attr("data-cookie");
109            vot = $(this).attr("data-valor");
110            id_encuesta = $(this).attr("data-id");                  
111            $('.cont_recaptcha').css('display', 'flex');                   
112        }
113    });
114    
115} 
116
117function swiperBloqueShorts(){
118    const swiperElement = document.querySelector('.swiper-shorts'); 
119    if (swiperElement){
120        const swiper = new Swiper('.swiper-shorts', {
121            direction: 'horizontal',
122            loop: false,
123            slidesPerView: "auto",
124            spaceBetween: 25,
125            navigation: {
126                nextEl: '.swiper-button-next',
127                prevEl: '.swiper-button-prev',
128            },
129            breakpoints: {
130                320: {
131                  slidesPerView: "auto",
132                  spaceBetween: 25
133                }
134          
135            }
136        });
137    }
138}
139
140function onYouTubePlayerAPIReadyCB(ide_video , multimedia, mute,valor_autoplay) {
141    if(multimedia){
142        try {
143            playerYB_multimedia = new YT.Player(ide_video, {
144                videoId: ide_video,
145                events: {
146                    'onReady':function(e){
147                        try {
148                            if(playerYB &&  typeof playerYB != "undefined" && valor_autoplay){
149                                playerYB.pauseVideo();
150                            }
151                        }
152                        catch (e) {
153                                console.log("FIX ",e)
154
155                        }
156
157                        if( playerYB_multimedia &&  typeof playerYB_multimedia != "undefined" && via_ajax )
158                            playerYB_multimedia.playVideo();
159                        else
160                            console.log("onYouTubePlayerAPIReadyCB SIN YT!!")
161                        if(mute && valor_autoplay && !via_ajax){
162                            e.target.mute();
163                        }
164
165                    },
166                    'onStateChange': Multimedia_onPlayerStateChange
167                },
168                playerVars: {'playsinline':'1','theme':'light','color':'white','modestbranding':1,'rel':0}
169            });
170        }catch (e) {
171            setTimeout(function() {  onYouTubePlayerAPIReadyCB(ide_video , multimedia, mute,valor_autoplay) }, 500);
172        }
173    }
174    else{
175        try {
176            playerYB = new YT.Player(ide_video, {
177                videoId: ide_video,
178                events: {
179                    'onReady':function(e){
180                        if(playerYB && valor_autoplay){
181                            playerYB.playVideo();
182                        }
183                        if(mute && valor_autoplay){
184                            e.target.mute();
185                        }
186                    },
187                    'onStateChange': onPlayerStateChange
188                },
189                playerVars: {'playsinline':'1', 'theme':'light','color':'white','modestbranding':1,'rel':0}
190            });
191        }catch (e) {
192            console.log("onYouTubePlayerAPIReadyCB SIN YT!! ")
193            setTimeout(function() {  onYouTubePlayerAPIReadyCB(ide_video , multimedia, mute,valor_autoplay) }, 500);
194        }
195    }
196}
197
198function onPlayerReady(){
199    if(playerYB){
200        console.log(playerYB)
201        playerYB.playVideo();
202    }
203    else
204        console.log("onYouTubePlayerAPIReadyCB SIN YT!!")
205}
206
207function onPlayerStateChange(event) {
208    if (event.data == YT.PlayerState.PLAYING && playerYB_multimedia && window.location.pathname.indexOf("/multimedia") == -1){
209        playerYB_multimedia.pauseVideo();
210    }
211}
212
213function Multimedia_onPlayerStateChange(event) {
214    console.log("Video Multimedia inicializado")
215    if (event.data == YT.PlayerState.PLAYING && playerYB)
216            playerYB.pauseVideo();
217}
218
219function video_encuerpo(){
220    if ( ismobile && $(".trending_notapage.video_vivo_nota").length ) {
221        if($(".cuerpo ").children('p').length > 1){
222           $(".trending_notapage.video_vivo_nota").insertAfter($(".cuerpo p").eq(primerocon_texto()));
223        }
224    }
225}
226
227function animatethis(targetElement, speed) {
228    var scrollWidth = $(targetElement).get(0).scrollWidth;
229    var clientWidth = $(targetElement).get(0).clientWidth;
230    $(targetElement).animate({ scrollLeft: scrollWidth - clientWidth },
231    {
232        duration: speed,
233        complete: function () {
234            targetElement.animate({ scrollLeft: 0 },
235            {
236                duration: speed,
237                complete: function () {
238                    animatethis(targetElement, speed);
239                }
240            });
241        }
242    });
243};
244
245var to_general = null;
246var estado_rep = ''; 
247var timer_video = 0;
248
249function reload() {
250    if (to_general)
251        clearTimeout(to_general);
252    
253    to_general = setTimeout(function () {
254        var esMultimedia = location.href.indexOf("/multimedia") != -1;
255        var vivoAudio = typeof playerYB == "object" && playerYB && typeof playerYB.isMuted == "function" && !playerYB.isMuted();
256
257        var videoJS=false;
258        if( $(".video-js").length ){
259            $(".video-js").each(function (index, element) {
260                try {
261                    var idefind=$(this).attr("id");
262                    var video_inicializado=videojs(idefind)
263                    if (video_inicializado && typeof video_inicializado == "object" && typeof video_inicializado.muted == "function" &&  !video_inicializado.paused() &&  !video_inicializado.muted() ){
264                        videoJS=true;
265                    }
266                }
267                catch(e) {
268                    console.log("ERROR videojs busqueda pausa", e)
269                }
270            })
271        }
272
273        if (esMultimedia || esRadio || vivoAudio || videoJS )
274            timer_video++;
275        else
276            timer_video = 0;
277
278        var loc_reload = timer_video>=40 || timer_video==0;
279        console.log('reload!!!! timer_video: ' + timer_video + " | loc_reload: " + loc_reload + " | multimedia: " + esMultimedia + " | radio: " + esRadio + " | vivoAudio: " + vivoAudio+ " | videoJS: " + videoJS);
280
281        if (loc_reload) {
282            location.reload(true);    
283        } else {
284            reload();   
285            sendGa();
286        } 
287    }, time_to);
288}
289
290// reload();
291
292function prevent() {
293    $(document).on('click', 'a', function(event) {
294        if ($(this).attr("target") == "_blank" || $(this).hasClass("bx-prev") || $(this).hasClass("bx-next") || $(this).hasClass("galleryDiarios") || $(this).hasClass("tab-link") || $(this).hasClass("tabh-link") || $(this).parents().hasClass("datepick-popup") || $(this).hasClass("noAjax") || $(this).hasClass("close-modal") || $(this).hasClass("link-modal")   )
295            return;
296        var link = $(this).attr('href');
297
298        if (link && link.indexOf("/suscripcion/") != -1) 
299            return;
300
301        if ($(this).is('.externo') || event.ctrlKey || event.metaKey) {
302            event.preventDefault();
303            event.stopPropagation();
304            window.open(link, '_blank');
305            return;
306        }
307        
308        if (link) {
309            link = getUrlParts(link)
310
311            if ((link.hostname == "plus.google.com" && link.pathname == "/share") || (link.hostname == "twitter.com" && link.pathname == "/intent/tweet"))
312                return;
313            if (link.original[0] == "/" || link.hostname == "www.reduno.com.bo" || link.hostname == "reduno.com.bo")
314                render(link.pathname);
315            else
316                window.open(link.href, '_blank');
317            event.preventDefault();
318            event.stopPropagation();
319        }
320    });
321}
322
323function get_cookies() {
324    cookies = {};
325    if (typeof document.cookie != 'undefined' && document.cookie.length > 0)
326        document.cookie.split(';').forEach(function(cookie) {
327            var parts = cookie.match(/(.*?)=(.*)$/)
328            cookies[parts[1].trim()] = (parts[2] || '').trim();
329        });
330    return cookies;
331}
332
333function createCookie(name, value, days) {
334    if (days) {
335        var date = new Date();
336        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
337        var expires = "; expires=" + date.toUTCString();
338    } else var expires = "";
339    document.cookie = name + "=" + value + expires + "; path=/";
340}
341
342function readCookie(name) {
343    var nameEQ = name + "=";
344    var ca = document.cookie.split(';');
345    for (var i = 0; i < ca.length; i++) {
346        var c = ca[i];
347        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
348        if (c.indexOf(nameEQ) == 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
349    }
350    return null;
351}
352
353function eraseCookie(name) {
354    createCookie(encodeURIComponent(name), "", -1);
355}
356
357function buttonCMS(id) {
358    var cookies = get_cookies();
359    if (cookies && cookies.login_mustang) {
360        $(".cont_boton_editar").remove();
361        $(".detalle--nota").prepend(
362            '<a class="cont_boton_editar" href="' + cookies.login_mustang + '/edit/notas/' + id + '" target="_blank">' +
363            '<div class="boton_editar">Editar</div>' +
364            "</a>");
365    }
366}
367
368// function sendGa() {
369//     try {
370//         var datos = $(".datos_ubicacion");
371//         if (datos.data("id")) {
372//             var toSend = {
373//                 //page: location.pathname,
374//                 //title: document ? document.title : ""
375//             }
376//             toSend.dimension1 = datos.data("id") || "";
377//             toSend.dimension2 = datos.data("titulo") || "";
378//             toSend.dimension3 = datos.data("ucreador") || "";
379//             toSend.dimension4 = datos.data("fecha_c") || "";
380
381//             console.log("sendGa", toSend)
382//             ga('set', toSend);
383//         }
384//     }
385//     catch(e) {
386//         console.log("ERROR GA SET JS!", e)
387//     }
388
389//     try {
390//         var path = location.pathname;
391
392//         ga('send', 'pageview', path);
393//     }
394//     catch(e) {
395//         console.log("ERROR GA SET JS 2!", e)
396//     }
397
398//     try {
399//         self.COMSCORE && COMSCORE.beacon({ c1: "2", c2: "26661861" });
400//     }
401//     catch(e) {
402//         console.log("ERROR COMSCORE!", e)
403//     }    
404// }
405
406function sendGa() {
407    var toSend = {}
408    try {
409        var datos = $(".datos_ubicacion");
410
411        if (datos.data("id")) {
412            toSend.cd1 = datos.data("id") || "";
413            toSend.cd2 = datos.data("titulo") || "";
414            toSend.cd3 = datos.data("ucreador") || "";
415            toSend.cd4 = datos.data("fecha_c") || "";
416            toSend.cd5 = datos.data("seccion") || "";
417        }
418        if (typeof window.isAppMobile === 'function' && window.isAppMobile()) {
419            toSend.appMobile = "true";
420        } else if (typeof window.isAppMobile === 'function') {
421            console.log("sendGa - isAppMobile retornó false");
422        } else {
423            console.log("sendGa - window.isAppMobile no está definido");
424        }
425        console.log("sendGa", toSend)
426        gtag('set', toSend);
427    }
428    catch (e) {
429        console.log("ERROR GA SET JS!", e)
430    }
431
432    try {
433        gtag('event', 'page_view', toSend)
434    }
435    catch (e) {
436        console.log("ERROR GA SET JS 2!", e)
437    }
438}
439
440function myPopup(url) {
441    window.open(url, "_blank", "status=1,height=368,width=775,resizable=0,menubar=0,toolbar=0,scrollbars=0")
442    return false;
443}
444
445function initEncuesta(){
446    if(!$('.estatico_encuesta').length){ //no hay encuestas
447        return;
448    }
449
450    $('.estatico_encuesta').each(function(){ //consulto si las encuestas ya fueron votadas por el usuario
451        const encuestaId = $(this).data('encuesta-id');
452        if(readCookie(`voto_${encuestaId}`)){
453            $(this).find('.ee-opciones').hide();
454            $(this).find('.ee-respuestas').css('display', 'grid');
455        }else{
456            $(this).find('.ee-respuestas').hide();
457            $(this).find('.ee-opciones').css('display', 'grid');
458        }
459    })
460
461    if(!$('.ee-opcion').length){ //no hay opciones significa que no hay encuestas
462        return;
463    }
464
465    $('.ee-opcion').click(function(){ //al apretar en una respuesta
466        const respuestaId = $(this).data('vot')
467        const encuestaId = $(this).data('encuesta-id')
468
469        const urlToFetch = `${window.location.origin}/encuesta`
470
471        fetch(urlToFetch, {
472            method: 'POST',
473            body: JSON.stringify({encuestaId: encuestaId ,respuestaId: respuestaId}),
474            headers: {
475                'Content-Type': 'application/json'
476        }
477        }).then(response => {
478            if(!response.ok){ //si no es status 200 no hace nada
479                return;
480            }
481            try{
482                response.json().then(data => { //traemos la data
483                    if(data.err) return; //verificamos nuevamente que no haya error en la data
484
485                    let {encuesta} = data;
486                    if(!encuesta || !encuesta.r) return;
487            
488                    encuesta = getPorcentajesEncuesta(encuesta); //asignamos porcentajes
489                    const html = getHtmlRespuestasEncuesta(encuesta); //traemos el html de las respuestas
490
491                    $('.estatico_encuesta').each(function(){ //hago este each para encontrar el contenedor de la encuesta
492                        const encuestaIdAux = $(this).data('encuesta-id');
493
494                        if(encuestaId == encuestaIdAux){ //si lo encuentro entonces oculto las opciones, muestro las opciones y actualizo los votos
495                            $(this).find('.ee-opciones').hide();
496                            $(this).find('.ee-respuestas').html(html);
497                            $(this).find('.ee-respuestas').css('display', 'grid');
498                            $(this).find('.ee-respuesta-background').addClass('ee-respuesta-background-nowidth');
499                            setTimeout(()=> {
500                                $(this).find('.ee-respuesta-background').removeClass('ee-respuesta-background-nowidth')
501                            }, 200)
502                            $(this).find('.ee-votos-text').text(`CANTIDAD DE VOTOS: ${encuesta.votos}`);
503                        }
504                    })
505                });
506            }catch(e){
507                console.log("error: ",e);
508                return;
509            }
510        })
511    })
512}
513
514function getPorcentajesEncuesta(encuesta){
515    if(!encuesta || !encuesta.r || !encuesta.r.length) return el;
516
517    encuesta.r.map(el =>{
518      if(encuesta.votos <= 0){
519        el.porcentaje = 0;
520      }else{
521        el.porcentaje = ((el.contador / encuesta.votos) * 100).toFixed(2);
522      }
523    })
524    return encuesta;
525}
526
527function getHtmlRespuestasEncuesta(encuesta){
528    let html = ""
529
530    encuesta.r.forEach(el =>{
531        html += `
532        <div class="ee-respuesta">
533            <span class="ee-respuesta-text">${el.label}</span>
534            <span class="ee-respuesta-porc">${el.porcentaje} %</span>
535            <div class="ee-respuesta-background" style="width: ${el.porcentaje > 2 ? el.porcentaje : "2"}%;"></div>
536        </div>
537        `
538    })
539    return html;
540}
541function cbIniciarLogin() {
542
543    //evitar que te mande al login si es bot
544    if (readCookie("isBot") == "true") return;
545
546    if (location.pathname == "/login" ) {
547        //$(".bs-example-modal-lg").modal('show');
548        history.replaceState({ url: "/" }, "/", "/");
549    }
550
551    if (readCookie('user_id') && readCookie('user')) {
552        var user = JSON.parse(readCookie("user"));
553        renderLogin(user);
554    } else {
555        eraseCookie("userToken");
556        eraseCookie("userName");
557        eraseCookie("userLastName");
558        $.post("/cerrar-sesion-ok")
559        if (location.pathname == "/suscripcion" ) {
560            console.log("cbIniciarLogin 1", location.pathname)
561            window.location.href = (window.__staticHost || "") + "/suscripcion_web/login-susc";
562        }
563    }
564}
565
566function cerrarSesion_web() {
567    if(readCookie("user")) {
568        eraseCookie("user");
569        eraseCookie("user_id");
570        eraseCookie("user_name");
571        eraseCookie("userId_s");
572    }
573    cbIniciarLogin();
574    $('#cerrarSesionWebContainer').removeClass('disable')
575    $('#iconSesionWebContainer').addClass('disable')
576    window.location.href = ("/");
577}
578
579function swiperBloqueOpinion() {
580    if (document.querySelector('.swiper_bloque_opinion')){
581        const swiper = new Swiper('.swiper_bloque_opinion', {
582        
583            direction: 'horizontal',
584            loop: false,
585            spaceBetween: 25,
586       
587            navigation: {
588                nextEl: '.swiper-button-next',
589                prevEl: '.swiper-button-prev',
590            },
591
592            slidesPerView: 'auto',
593            
594        });
595    }
596}
597
598function swiperEstaticoObituarios() {
599    if (document.querySelector('.swiper_estatico_obituarios')){
600        const swiper = new Swiper('.swiper_estatico_obituarios', {
601        
602            direction: 'horizontal',
603            loop: false,
604            spaceBetween: 35,       
605            navigation: {
606                nextEl: '.swiper-button-next',
607                prevEl: '.swiper-button-prev',
608            },
609
610            slidesPerView: 'auto',
611            
612        });
613    }
614}
615
616function swiperBloque9() {
617    if (document.querySelector('.swiper_bloque_9')){
618        const swiper = new Swiper('.swiper_bloque_9', {
619        
620            direction: 'horizontal',
621            loop: false,
622            spaceBetween: 25,
623       
624            navigation: {
625                nextEl: '.swiper-button-next',
626                prevEl: '.swiper-button-prev',
627            },
628
629            slidesPerView: 'auto',
630
631        });
632    }
633}
634
635$(document).ready(function() {
636
637    initHeaderButtons();
638
639    $(document).on('click','#cerrarSesionWeb', cerrarSesion_web); //al apretar en cerrar sesión
640    
641
642
643    initEncuesta();
644
645    swiperBloque9();
646    swiperBloqueOpinion();
647    swiperEstaticoObituarios();
648    swiperBloqueShorts()
649
650    $(document).on('click', '.reglamento', showReglamentoClub)
651
652    initEstaticoTombola();
653    initEstaticoClima();
654
655    hideMarkRecaptcha();
656
657    // MC-19579: aislar la inicializacion de publicidad (GPT) del resto del ready.
658    // Si googletag/ads falla, NO debe abortar los handlers posteriores de document.ready
659    // (p.ej. la inicializacion del formulario de medio de pago / getIdentificationTypes).
660    try { initPublisByGPT(); } catch (e) { if (window.console && console.warn) console.warn('initPublisByGPT() fallo (ads), se continua', e); }
661
662    sendGa();
663
664    initColorBtnBloqueSlider();
665
666    inicializarNota();
667    inicializarMAMHome();
668    inicializarMAMNotapage()
669    initBtnPressReader()
670
671    // MC-19892: aislar Ad Preview del resto del ready, misma lógica que initPublisByGPT.
672    try { initAdPreview(); } catch (e) { if (window.console && console.warn) console.warn('initAdPreview() fallo, se continua', e); }
673
674});
675
676// MC-19892: Ad Preview — adaptado de front-destape public/js/functions.js:69-178
677// (initInterstitialPublis). Simplificado porque acá el server ya renderiza un
678// único spot por página, ya filtrado por dispositivo vía el parámetro `tipo`.
679// Usa el namespace ad-preview-* (no interstitial-*) para no chocar con el JS
680// legacy de Edición Impresa (functionsForPapel.js), que maneja ese otro nombre
681// con selectores sin scope ($(".interstitial-container"), $('.interstitial-active')).
682function setearCookieAdPreview(minutes, pos) {
683    var now = new Date();
684    var expireTime = now.getTime() + minutes * 60 * 1000;
685    now.setTime(expireTime);
686    document.cookie = pos + '=ok;expires=' + now.toGMTString() + ';path=/';
687}
688
689function scrollToSubheaderAdPreview() {
690    // MC-19892: frena en el borde superior del subheader (no en la altura del
691    // contenedor propio) para que quede como si el Ad Preview nunca se hubiera
692    // renderizado. Se resta la altura del .header (position:sticky, top:0) porque
693    // si no, el header pegajoso tapa la parte de arriba del subheader al llegar.
694    var target = $('#subheader');
695    var header = $('.header').first();
696    var headerHeight = header.length ? header.outerHeight() : 0;
697    var scrollTarget = target.length ? Math.max(0, target.offset().top - headerHeight) : 0;
698    $('html, body').animate({ scrollTop: scrollTarget }, 800);
699}
700
701function activateAdPreviewScripts(publi, onDone) {
702    // MC-19892 fix: helpers.js neutraliza los <script> de la creatividad como
703    // type="text/plain" para que el ad de GPT no se pida al parsear el HTML
704    // (necesario porque esta página se sirve desde un CDN compartido entre
705    // usuarios, así que el server no puede cortar mirando la cookie de cap sin
706    // pegarle esa decisión al cache para todo el mundo). Sólo llegan acá
707    // (recreados como <script> reales) los usuarios NO capeados.
708    var inertes = publi.find('script[data-ad-preview-inert]').get();
709
710    // MC-19892 fix: se reactivan de a uno, en cadena, imitando el orden del parser: un
711    // externo SIN async bloquea a los que siguen (se espera su load/error antes de
712    // insertar el próximo), un externo CON async no bloquea, y un inline ejecuta
713    // sincrónicamente al insertarlo. Insertarlos todos en una tanda no alcanzaba: un
714    // <script src> insertado por DOM es async por defecto, así que el inline que usa esa
715    // lib ejecutaba antes de que terminara de cargar (ReferenceError). async=false no
716    // arregla ese caso - sólo ordena los externos entre sí, no al inline respecto del
717    // externo, que es justo el patrón "<script src=lib.js> + <script>lib.init()</script>"
718    // que rompía.
719
720    // onDone avisa que toda la cadena terminó (ver initAdPreview: de ahí cuelga el
721    // countdown de close_time). Se llama una sola vez, y sincrónicamente si no hubo
722    // ningún script bloqueante.
723    var terminado = false;
724    function terminar() {
725        if (terminado) return;
726        terminado = true;
727        if (typeof onDone === 'function') onDone();
728    }
729
730    // Presupuesto de espera GLOBAL, no por script: el contenedor ya está visible y es
731    // un position:fixed blanco a pantalla completa, así que N externos colgados no
732    // pueden sumar N*10s de blanco antes de que siquiera arranque el countdown de
733    // close_time. Pasado el deadline la cadena sigue insertando sin esperar: se pierde
734    // el orden garantizado (vuelve el riesgo de ReferenceError en un inline dependiente),
735    // que es el mal menor frente a dejar el overlay tapando el sitio indefinidamente.
736    //
737    // 10s y no 3s: si el corte le gana a una lib que todavía está cargando (GPT/prebid
738    // en móvil pasan 3s sin problema) reaparece justamente ese ReferenceError. Esperar
739    // de más sólo demora el ad en el caso adblock, donde onerror dispara casi siempre
740    // y rápido - el deadline es la red para el request que cuelga, no para el que falla.
741    var deadline = (new Date()).getTime() + 10000;
742
743    function activarSiguiente(i) {
744        if (i >= inertes.length) {
745            terminar();
746            return;
747        }
748
749        var oldScript = inertes[i];
750        // Una creatividad ya ejecutada puede haber reescrito su contenedor y dejado a
751        // este nodo fuera del DOM; saltearlo en vez de cortar la cadena.
752        if (!oldScript.parentNode) {
753            activarSiguiente(i + 1);
754            return;
755        }
756
757        var newScript = document.createElement('script');
758        for (var j = 0; j < oldScript.attributes.length; j++) {
759            var attr = oldScript.attributes[j];
760            if (attr.name === 'type' || attr.name === 'data-ad-preview-inert') continue;
761            // MC-19892 fix: helpers.js renombra el type original a data-ad-preview-type
762            // porque el type="text/plain" que inertiza el script quedaba duplicado con
763            // el de la creatividad y el parser descarta el segundo. Sin restaurarlo, un
764            // <script type="application/json"> (config de wrappers/prebid) o un
765            // type="module" se recreaba como JS clásico y tiraba SyntaxError.
766            if (attr.name === 'data-ad-preview-type') {
767                newScript.setAttribute('type', attr.value);
768                continue;
769            }
770            newScript.setAttribute(attr.name, attr.value);
771        }
772        newScript.text = oldScript.text;
773
774        // Un externo con async explícito no bloquea, igual que en el parser. El resto sí,
775        // y ahí async=false los mantiene además ordenados entre ellos. `defer` cae en la
776        // rama que bloquea: en un script insertado por DOM el navegador lo ignora, y como
777        // esto corre después del ready, ejecutarlo en orden es la mejor aproximación.
778        //
779        // Se mira el ATRIBUTO src y no la propiedad newScript.src: la propiedad resuelve
780        // contra el documento, así que un src="" devuelve la URL de la página (no vacío)
781        // y el tag entraba en la rama bloqueante, esperando a que el navegador se baje el
782        // HTML entero de la nota como si fuera JS.
783        var srcAttr = oldScript.getAttribute('src');
784        var bloquea = !!(srcAttr && srcAttr.replace(/^\s+|\s+$/g, '')) && !newScript.hasAttribute('async');
785        var restante = bloquea ? deadline - (new Date()).getTime() : 0;
786        // Fuera del if a propósito: si el deadline ya venció la cadena deja de esperar,
787        // pero async=false sigue manteniendo ordenados entre sí a los externos que
788        // queden. Es lo único del orden original que se puede salvar en esa ruta.
789        if (bloquea) newScript.async = false;
790
791        if (bloquea && restante > 0) {
792            // Se sigue con load o con error, y con lo que quede del deadline global como
793            // última instancia: un adblock que corta la lib no debe dejar el resto de la
794            // creatividad sin ejecutar por esperar un evento que no va a llegar.
795            var seguido = false;
796            var seguir = function () {
797                if (seguido) return;
798                seguido = true;
799                activarSiguiente(i + 1);
800            };
801            newScript.onload = seguir;
802            newScript.onerror = seguir;
803            setTimeout(seguir, restante);
804            oldScript.parentNode.replaceChild(newScript, oldScript);
805            return;
806        }
807
808        oldScript.parentNode.replaceChild(newScript, oldScript);
809        activarSiguiente(i + 1);
810    }
811
812    activarSiguiente(0);
813}
814
815function initAdPreview() {
816    var publi = $('.ad-preview-container').first();
817    if (!publi.length) return;
818
819    var spot = publi.data('spot');
820    var pos = publi.data('pos');
821    var close_time_seconds = parseInt(publi.data('close_time'), 10) || 0;
822    var cookie_expire_minutes = parseInt(publi.data('cookie_time'), 10) || 0;
823
824    if (document.cookie.indexOf(pos + '_' + spot) !== -1) return;
825
826    // MC-19892 fix: primero se muestra el contenedor y después se reactivan los
827    // scripts. Al revés, el googletag.display() de la creatividad ejecutaba con el
828    // contenedor todavía en display:none y GPT medía el slot en 0x0 — justo lo que
829    // este ticket busca evitar.
830    //
831    // La aparición se anima por opacity y no con fadeIn(): .ad-preview-active ya pone
832    // display:flex (adpreview.scss), así que para cuando corría el fadeIn jQuery veía
833    // el elemento visible, salteaba la animación y no hacía nada. Además opacity no
834    // afecta el layout, o sea que el slot mide bien desde el frame cero aunque todavía
835    // no se vea - que es la condición que necesita GPT.
836    publi.css('opacity', 0).addClass('ad-preview-active');
837
838    // Delegado sobre el contenedor y no bindeado al nodo: si la creatividad reescribe
839    // el innerHTML de .ad-preview-inner al ejecutar, el .ad-preview-next original
840    // desaparece con su handler y el usuario se queda sin forma de cerrar el overlay.
841    // Con delegación el click sigue funcionando sobre el nodo que haya en ese momento.
842    publi.on('click', '.ad-preview-next', function () {
843        publi.addClass('ad-preview-close');
844        publi.removeClass('ad-preview-active');
845        scrollToSubheaderAdPreview();
846    });
847
848    publi.animate({ opacity: 1 }, 350);
849
850    // MC-19892 fix: el countdown de close_time arranca cuando terminó la cadena de
851    // scripts, no al completar el fadeIn. activateAdPreviewScripts() retorna enseguida
852    // (un externo bloqueante sigue por load/error), así que colgar el timer del fadeIn
853    // lo largaba con la creatividad todavía sin renderizar: una lib lenta se comía parte
854    // de la exposición y el preview podía cerrarse antes de que el ad se viera - justo
855    // la viewability que este ticket busca. La cadena tiene un tope global de 10s, así
856    // que el countdown arranca sí o sí dentro de ese margen.
857    activateAdPreviewScripts(publi, function () {
858        if (close_time_seconds <= 0) return;
859        setTimeout(function () {
860            if (publi.hasClass('ad-preview-active') && !publi.hasClass('ad-preview-close')) {
861                publi.addClass('ad-preview-close');
862                publi.removeClass('ad-preview-active');
863                scrollToSubheaderAdPreview();
864            }
865        }, close_time_seconds * 1000);
866    });
867
868    if (cookie_expire_minutes > 0) {
869        setearCookieAdPreview(cookie_expire_minutes, pos + '_' + spot);
870    }
871
872    var scrollinit = $(window).scrollTop();
873    setTimeout(function () {
874        $(window).on('scroll.adPreview', function () {
875            if (publi.hasClass('ad-preview-active') && $(window).scrollTop() - scrollinit > 400) {
876                publi.addClass('ad-preview-close');
877                publi.removeClass('ad-preview-active');
878            }
879        });
880    }, 1000);
881}
882
883function initBtnPressReader(){
884    if(!readCookie('user') || !$('.link_edicion_pdf').length) return;
885    const user = JSON.parse(decodeURIComponent(readCookie('user')))
886
887    var time= new Date().getTime();
888    if(user.token_press_valid > time){
889        $('.link_edicion_pdf').each(function() {
890            $(this).attr('href', "http://edicionpdf.eltribuno.com?token="+user.token_press)
891        })
892    }
893}
894
895function inicializarMAMNotapage(){
896    if(!$("#detalle_minuto").length){
897        return;
898    }
899
900    var id_partido = $("#detalle_minuto").attr("data-id");
901
902    if(!id_partido){
903        return;
904    }
905
906    // console.log("YENDO A BUSCAR PARTIDO")
907
908    (function actualizaDetalleMinuto(){
909        $.ajax({
910            url: (window.__staticHost || '') + '/service/minuto_a_minuto_futbol_new/2/'+id_partido + "?" + new Date().getTime(),
911            method: 'GET',
912            dataType: 'html',
913            success: function(data) {
914                if($("#detalle_minuto."+id_partido).length){
915                    $("#detalle_minuto."+id_partido).html(data);
916                    setTimeout(actualizaDetalleMinuto, (window.__MAM_POLL_SEC || 90) * 1000);
917                }
918            }
919        })
920    })(); 
921}
922
923function initHeaderButtons(){
924    if(window.location.pathname.indexOf('/suscripcion_web') != -1){
925        if (readCookie("user")) { //verifica si esta logueado o no para mostrar los botones correspondientes
926            $('#cerrarSesionWebContainer').removeClass('disable')
927            $('#iconSesionWebContainer').removeClass('disable')
928            $('#iniciarSesionWebContainer').addClass('disable')
929        }
930        else{
931            $('#cerrarSesionWebContainer').addClass('disable')
932            $('#iconSesionWebContainer').addClass('disable')
933            $('#iniciarSesionWebContainer').removeClass('disable')
934        }
935    }
936}
937
938function initPublisByGPT(){
939    if(typeof loadGPT == 'function'){
940        loadGPT();
941    }
942
943    $(document).on('lazybeforeunveil', '.gpt-load', function(event, elem) {
944        lazyPpp(event, elem || this);
945    });
946}
947
948function hideMarkRecaptcha(){
949    var recaptcha = document.getElementsByClassName('grecaptcha-badge'); //para remover el icono del recaptcha en el borde inferior derecho
950    if(recaptcha && recaptcha.length > 0){ //si existe lo hago invisible
951        recaptcha[0].style.visibility = 'hidden'
952    }
953}
954
955function showReglamentoClub(){
956    $("#modal_reglamento").modal({
957        clickClose: true,
958        fadeDuration: 1000,
959        fadeDelay: .75
960    });
961}
962
963function inicializarMAMHome(){
964    if(!$('[data-id-futbol]').length){
965        return;
966    }
967
968    $('[data-id-futbol]').each(function(index,partido){
969        
970        var id_partido = $(partido).attr('data-id-futbol');
971
972        if(!id_partido){
973            return;
974        }
975
976        (function actualizaMinuto(){
977            $.ajax({
978                url: (window.__staticHost || '') + '/service/minuto_a_minuto_futbol_new/1/'+id_partido + "?" + new Date().getTime(),
979                method: 'GET',
980                dataType: 'json',
981                success: function(data) {
982                    function resolveLogoUrl(proxy, url) {
983                        if (!url) return '';
984                        if (/^https?:\/\/|^\/\//.test(url)) return url;
985                        return proxy + '/' + url;
986                    }
987                    $(`#nota_mam_${id_partido} .cont-mam_hora`).text(data.fecha_hora_partido);
988                    $(`#nota_mam_${id_partido} .cont-mam_estado`).text(data.estado_partido);
989                    $(`#nota_mam_${id_partido} .cont-mam_body_resultado_text`).text(data.resultado_global);
990                    $(`#nota_mam_${id_partido} .cont-mam_body_eq1`).html(`
991                    <img src="${resolveLogoUrl(data.url_escudo, data.url_escudo_equipo_local)}"/>
992                    `);
993                    $(`#nota_mam_${id_partido} .cont-mam_body_eq2`).html(`
994                    <img src="${resolveLogoUrl(data.url_escudo, data.url_escudo_equipo_visitante)}"/>
995                    `);
996                }
997            })
998            .error(function (err) {
999                console.log("[LOG] mam error: ",err);
1000            });
1001        })(); 
1002        
1003    });
1004}
1005
1006function initColorBtnBloqueSlider(){
1007    $('.bloque.bloque-slider.container').each(function(index, ele){
1008        const id = $(this).attr('id');
1009        if(!id) return;
1010
1011        const colorBloque = id.replace('bloque_slider_', '');
1012        $(ele).find('.amp-carousel-button').css('background-color', `${colorBloque}`);
1013    })
1014}
1015// MC-19579: garantizar googletag.cmd aunque googletag ya exista sin .cmd
1016// (race con el gpt.js async de Google). Evita "Cannot read properties of undefined (reading 'push')".
1017var googletag = googletag || {};
1018googletag.cmd = googletag.cmd || [];
1019var nextSlotId = 1;
1020function generateNextSlotName() {
1021    var id = nextSlotId++;
1022    return 'pppSlot' + id;
1023}
1024
1025var DFP_INICIADO = DFP_INICIADO || false
1026function defer(method) {
1027    if ((DFP_INICIADO ?? false) === true && (googletag.pubadsReady ?? false) === true) {
1028        method();
1029    } else {
1030        setTimeout(function() { defer(method) }, 500);
1031    }
1032}
1033
1034window.loadGPT = function(url) {
1035    defer(function() {
1036        loadGPTDeferer(url);
1037    })
1038}
1039
1040function loadGPTDeferer(url) {
1041    googletag.cmd = googletag.cmd || []; // MC-19579: guard ante race de carga de GPT
1042    googletag.cmd.push(function() {
1043        googletag.destroySlots();
1044
1045        $(".gpt-load").each(function() {
1046            $(this).addClass("lazyload");
1047        })
1048
1049        $(".gpt-load-now").each(function (event) {
1050            lazyPpp(event, this);
1051        })
1052    })
1053}
1054
1055window.lazyPpp = function(event, elem, noLazy) {
1056    googletag.cmd.push(function() {
1057        $(elem).removeClass("gpt-load");
1058        var gpt = $(elem).attr("data-gpt");
1059        var gpt_mobile = $(elem).attr("data-gpt-mobile");
1060        var gpt_tablet = $(elem).attr("data-gpt-tablet");
1061        var gpt_laptop = $(elem).attr("data-gpt-laptop");
1062        var size = $(elem).attr("data-size");
1063        var size_mobile = $(elem).attr("data-size-mobile");
1064        var size_tablet = $(elem).attr("data-size-tablet");
1065        var size_laptop = $(elem).attr("data-size-laptop");
1066        var format = $(elem).attr("data-format");
1067        var format_mobile = $(elem).attr("data-format-mobile");
1068        var format_tablet = $(elem).attr("data-format-tablet");
1069        var format_laptop = $(elem).attr("data-format-laptop");
1070        var resize = $(elem).attr("data-resize");
1071
1072        if (gpt_mobile && screen.width < 767) {
1073            gpt = gpt_mobile;
1074            size = size_mobile;
1075            format = format_mobile;
1076        }
1077
1078        if (gpt_tablet && screen.width > 767 && screen.width < 1023) {
1079            gpt = gpt_tablet;
1080            size = size_tablet;
1081            format = format_tablet;
1082        }
1083
1084        if (gpt_laptop && screen.width > 1023 && screen.width < 1229) {
1085            gpt = gpt_laptop;
1086            size = size_laptop;
1087            format = format_laptop;
1088        }
1089
1090        if(!comprobarPubli($, elem)) { $(elem).hide(); return; }
1091
1092        if (gpt && size) {
1093            var slotName = generateNextSlotName();
1094            if (format) {
1095                $(elem).attr("id", slotName);   
1096            } else {
1097                $(elem).html("<div id='" + slotName + "'></div>");        
1098            }
1099
1100            size = JSON.parse(size);
1101
1102            if (resize === "false" && Array.isArray(size)) {
1103                var maxW = 0, maxH = 0;
1104                size.forEach(function(s) {
1105                    if (Array.isArray(s) && typeof s[0] === "number" && typeof s[1] === "number") {
1106                        if (s[0] > maxW) maxW = s[0];
1107                        if (s[1] > maxH) maxH = s[1];
1108                    }
1109                });
1110                if (maxW > 0) $(elem).css("min-width", maxW + "px");
1111                if (maxH > 0) $(elem).css("min-height", maxH + "px");
1112            }
1113
1114            var slot = googletag.defineSlot(gpt, size, slotName).addService(googletag.pubads());
1115
1116            googletag.pubads().refresh([slot], {changeCorrelator: false});
1117            // inicializarPackery()
1118        }
1119    });
1120}
1121
1122function comprobarPubli($, elem, gpt){
1123	const string = $(elem).data('media');
1124
1125	if(!string || typeof(string) != 'string') return true
1126
1127	const numeros = string.match(/\d+/g);
1128
1129	// sin ancho parseable no hay gate que podamos evaluar: no suprimimos inventario
1130	if(!numeros) return true
1131
1132	const px = parseInt(numeros[0], 10);
1133
1134	if(string.indexOf('min-width') !== -1 && px <= screen.width){
1135		return true
1136	}
1137
1138	// >= : en CSS (max-width: 767px) matchea con viewport 767. Con > quedaba una zona muerta
1139	// de 1px justo en el breakpoint donde no se mostraba ni la mobile ni la desktop.
1140	if(string.indexOf('max-width') !== -1 && px >= screen.width){
1141		return true
1142	}
1143
1144	return false
1145}
1146
1147
1148function myPopup(t){ //popup por ejem: compartir facebook
1149    return window.open(t,"_blank","status=1,height=368,width=775,resizable=0,menubar=0,toolbar=0,scrollbars=0"),!1
1150}
1151
1152function initEstaticoClima(){
1153    if(!$('.clima.container').length) return;
1154
1155    $('.clima #combo_clima').change(function(){
1156        const valueSelect = $(this).val();
1157        $('.clima .clima_item').each(function(){
1158            const idClimaItem = $(this).attr('id');
1159            if(idClimaItem == `clima_${valueSelect}`){
1160                $(this).addClass('clima_item_activo')
1161            }else{
1162                $(this).removeClass('clima_item_activo')
1163            }
1164        })
1165        $('.clima .clima_extendido_items').each(function(){
1166            const idClimaItem = $(this).attr('id');
1167            if(idClimaItem == `extendido_${valueSelect}`){
1168                $(this).addClass('clima_extendido_items_activo')
1169            }else{
1170                $(this).removeClass('clima_extendido_items_activo')
1171            }
1172        })
1173    })
1174}
1175
1176function initEstaticoTombola(){
1177    if(!$('.tombola.container').length) return;
1178
1179    $('.tombola_opciones .tombola_opcion').each(function(){
1180        $(this).click(function(e){
1181            $('.tombola_opciones .tombola_opcion').each(function(){
1182                $(this).removeClass('activo');
1183            })
1184            $(this).addClass('activo');
1185            const opcion_id = $(this).attr('id');
1186            $('.tombola_resultados .tombola_items').each(function(){
1187                const resultado_id = $(this).attr('id');
1188
1189                if(resultado_id == `tombola_items_${opcion_id}`){
1190                    $(this).css('display', 'grid');
1191                }else{
1192                    $(this).css('display', 'none');
1193                }
1194            })
1195        })
1196    })
1197}
1198
1199function doRender(url, html, scroll) {
1200    console.log("doRender: " + url)
1201
1202    //var sitio = html.substring(html.indexOf('<div id="sitio">')+16, html.indexOf('</div><span id="fin_sitio"></span>'));
1203    $(".video-js").each(function() {
1204        if (typeof videojs != "function")
1205            return console.log("FALTA LIBRERIA VIDEJS")
1206
1207        var id = $(this).attr("id");
1208        console.log("Dispose videojs ID: " + id)
1209        
1210        if( id && id.length){
1211            try{
1212                videojs(id).dispose();
1213            }
1214            catch(err){
1215                console.log("incializar video.js",err);
1216            }
1217        }
1218
1219    });
1220    var tempDom = $('<output>').append($(html));    
1221    $("head meta").remove();
1222    $("head").append(tempDom.find("meta"));
1223    $("#sitio").html(tempDom.find("#sitio").html()).show();
1224
1225    if (tempDom.find("#sitio .footer").length)
1226        console.log("ERROR CERRAR DIV !!!!!!!!!!!!!! ", tempDom.find("#sitio .footer").length)
1227
1228    //$("#sitio").html(tempDom.find("#sitio")).show();
1229    $("html, body").scrollTop(0);
1230
1231    var title = tempDom.find("title");
1232    if (title)
1233        document.title = title.text();
1234
1235    reload();
1236
1237    if (typeof scroll == 'undefined') {
1238        history.pushState({
1239            url: url
1240        }, url, url);
1241    } else {
1242         setTimeout(function () {
1243             $(window).scrollTop(scroll);                 
1244         }, 1000);            
1245        history.replaceState({
1246            url: url,
1247            scroll: scroll 
1248        }, url, url);
1249    }
1250
1251    if (typeof pSUPERFLY == "object") pSUPERFLY.virtualPage(url, document.title);  
1252    if (typeof cX == "object") cX.callQueue.push(['sendPageViewEvent']);
1253
1254    $('body').removeClass("noScroll");
1255    postRender();  
1256
1257    request_render = false;
1258}
1259
1260function doRenderAjax(scroll, url) {        
1261    $.ajax({
1262        url: url,
1263        type: "GET",
1264        beforeSend: function() {          
1265            $('.navbar-menu, .hamburger').removeClass("is-active");
1266            to_loading = setTimeout(function(){
1267                $(".loading").removeClass('hidden');
1268                // $("#sitio").hide();
1269                // $("#sitio,footer").hide();
1270            }, 500);
1271        }
1272    }).done(function(html) {      
1273        doRender(url, html, scroll);
1274    }).error(function(response) {
1275        doRender(url, response.responseText, scroll);
1276    }).always(function() { 
1277        clearTimeout(to_loading);
1278        $(".loading").addClass('hidden');
1279        $(".footer").show();
1280    });
1281}
1282
1283function render(url, scroll) {
1284    if (request_render)
1285        return;
1286
1287    request_render = true;
1288
1289    if (typeof timer_refresh == 'number')
1290        clearTimeout(timer_refresh);
1291
1292    var stateData = {
1293        url: actual,
1294        scroll: $(window).scrollTop()
1295    };
1296    history.replaceState(stateData, actual, actual);        
1297   
1298    actual = url;
1299    doRenderAjax(scroll, url);
1300}
1301
1302var GA_FIRST = true;
1303
1304function postRender(scroll) {
1305    $("div[id^='adLayer']").remove(); //Borra publicidad
1306        
1307    if (GA_FIRST)
1308        GA_FIRST = false;
1309    else
1310        sendGa();
1311
1312    initGenerico();
1313    initHome(actual);
1314    initSeccion(actual);
1315    initTag(actual);
1316    initAutor(actual);
1317    initBusqueda(actual);
1318    initNotapage(actual);  
1319    initMultimedia();
1320   
1321    if (typeof loadGPT == "function") loadGPT();
1322
1323    setTimeout(function() {  via_ajax=true; }, 5000);
1324   
1325    
1326}
1327
1328var flagVideo = true;
1329var n_scroll = 1;
1330var nextPenSlugs = [];
1331
1332function getPenPath() {        
1333    if(!nextPenSlugs[0]){
1334        $(".notas_slider [data-link]").each(function() {
1335            nextPenSlugs.push($(this).data('link'));
1336        });                  
1337    }
1338    var slug = nextPenSlugs[ this.loadCount ];
1339    if ( slug ) {
1340        return '/nota/'+slug;
1341    }
1342}
1343
1344function notasSlider() {
1345    $('.slick_g').lightGallery({
1346        thumbnail: true,
1347        animateThumb: false,
1348        showThumbByDefault: false
1349    });
1350
1351    $(".slick_vertical:not(.slick-initialized)").slick({
1352        slidesToScroll: 1,
1353        infinite: false,
1354        slidesToShow: 3,
1355        vertical: true,
1356        verticalSwiping: true,
1357        arrows: false
1358    });
1359
1360    $(".slick:not(.slick-initialized)").each(function() {
1361        $(this).on('init', function(){ 
1362           $(this).css("opacity","1");
1363        });
1364        $(this).slick({
1365            prevArrow: '<button class="PrevArrow"><svg class="icon icon-f_izq"><use xlink:href="#icon-f_izq"></use></svg></button>',
1366            nextArrow: '<button class="NextArrow"><svg class="icon icon-f_der"><use xlink:href="#icon-f_der"></use></svg></button>'
1367        });
1368    })
1369
1370    $(".slick_swiper:not(.slick-initialized)").slick({
1371        infinite: false,
1372        speed: 300,
1373        slidesToShow: 4,
1374        slidesToScroll: 1,
1375        arrows: false,
1376        swipe: true,
1377        dots: true,
1378        prevArrow: '<button class="PrevArrow"><</button>',
1379        nextArrow: '<button class="NextArrow">></button>',
1380        responsive: [{
1381                breakpoint: 1024,
1382                settings: {
1383                    slidesToShow: 3,
1384                    slidesToScroll: 3
1385                }
1386            },
1387            {
1388                breakpoint: 800,
1389                settings: {
1390                    slidesToShow: 2,
1391                    slidesToScroll: 2
1392                }
1393            },
1394            {
1395                breakpoint: 550,
1396                settings: {
1397                    slidesToShow: 2,
1398                    slidesToScroll: 1
1399                }
1400            }
1401
1402        ]
1403    });
1404    
1405}
1406
1407function jQueryTabs() {
1408    $(".tabs-content .tabs-panel:not(:first-child)").hide();
1409    $(".tabs").each(function() {
1410        var tab = $(this);
1411        tab.find(".tabs-panel").not(":first").hide(),
1412        tab.find("li").removeClass("active"),
1413        tab.find("li:first-child").addClass("active"),
1414        tab.find(".tabs-panel:first-child").show(),
1415        tab.find("li").click(function(t) {            
1416            var i = $("a",this).attr("href");
1417            if (i && i[0] == "/") return; 
1418            t.preventDefault();
1419            $(this).siblings().removeClass("active");
1420            $(this).addClass("active");
1421            $(i).hide();
1422            $(i).siblings().hide();
1423            $(i).fadeIn(400);
1424        })//, $(window).width() < 768 && $(".tabs-panel").show()
1425    })
1426
1427    $(".tabs li a").each(function() {
1428        var t = $(this).attr("href"),
1429            i = $(this).html();
1430        $(t + " .tab-title").prepend("<p><strong>" + i + "</strong></p>")
1431    })
1432}
1433
1434function jQueryTabs2() {
1435    $(".ntabscontent:not(:first-child)").hide();
1436    $(".ntabslink").removeClass('is-active');
1437    $(".ntabslink:first-child").addClass("is-active");
1438    $(".ntabscontent:first-child").css('display', 'block');
1439    $(".ntabslink").each(function() {
1440        var tab = $(this);
1441        tab.click(function(t) {                                
1442            t.stopPropagation();
1443            t.preventDefault();
1444            $(".ntabslink").removeClass('is-active')
1445            var i = $("a",this).attr("href");
1446            if (i && i[0] == "/") return; 
1447            $(this).addClass("is-active");                
1448            $(i).hide();
1449            $(i).siblings().hide();
1450            $(i).fadeIn(400);
1451        })
1452    })
1453}
1454
1455function jQueryTabsH() {
1456    $(".tabsh-content .tabsh-panel").hide();
1457    $(".tabsh").each(function() {
1458        var tab = $(this);
1459        tab.find(".tabsh-panel").hide(),
1460        tab.find("li").removeClass("active"),                        
1461        tab.find("li").click(function(t) {            
1462            var i = $("a",this).attr("href");
1463            if (i && i[0] == "/") return; 
1464            t.preventDefault();
1465            $(this).siblings().removeClass("active");
1466            $(this).addClass("active");
1467            $(i).hide();
1468            $(i).siblings().hide();
1469            $(i).fadeIn(50);
1470        })//, $(window).width() < 768 && $(".tabs-panel").show()
1471    })
1472
1473    $(".tabs li a").each(function() {
1474        var t = $(this).attr("href"),
1475            i = $(this).html();
1476        $(t + " .tab-title").prepend("<p><strong>" + i + "</strong></p>")
1477    })
1478}
1479
1480function menuSticky(){
1481    $('.navbar-menu-desktop li').removeClass('active');
1482    var header = $('header');
1483    var  sticky=header.height()
1484    var pos_scroll=$(window).scrollTop()
1485    
1486    if ($(window).scrollTop() > sticky ) {
1487        $('header, .navbar').addClass('is-sticky');
1488    } else {
1489        $('header, .navbar').removeClass('is-sticky');
1490    }
1491    alert_position(pos_scroll,ismobile,sticky);
1492    vivo_minimizado_position(pos_scroll,ismobile);
1493    if( !stickyalert ){
1494        $('.bloque_alerta ').remove()
1495    }
1496    $(window).scroll(function () {
1497        pos_scroll=$(window).scrollTop()
1498        if (pos_scroll > sticky) {
1499            $('header, .navbar').addClass('is-sticky');
1500        } else {
1501            $('header, .navbar').removeClass('is-sticky');
1502        }
1503        alert_position(pos_scroll,ismobile,sticky);
1504        vivo_minimizado_position(pos_scroll,ismobile);
1505    });
1506}   
1507
1508function getTitulo(id){
1509    var titulo = $('.detalle--nota[data-id="'+id+'"]').find('h1.titulo').text();
1510    document.title = titulo;    
1511}
1512
1513function getId(){        
1514    var nota_id = $('.detalle--nota').data('id');
1515    return nota_id;
1516}
1517
1518function getPenPath() {        
1519    if(!nextPenSlugs[0]){
1520        $(".notas_slider [data-link]").each(function() {
1521            nextPenSlugs.push($(this).data('link'));
1522        });                  
1523    }
1524    
1525    var slug = nextPenSlugs[ this.loadCount ];
1526    
1527    if ( slug ) {
1528        return '/nota/'+slug;
1529    }
1530}
1531
1532function comprobarCargamas(){
1533    if($('.m_false').length){
1534       $("#more").val('false');       
1535    }     
1536    if($("#more").val() != "true"){
1537          $(".btn--mas_noticias").remove();
1538    }  
1539}
1540
1541function cargamas(){
1542    $('.btn--mas_noticias').click(function(e) {
1543        e.stopPropagation();
1544        e.preventDefault();  
1545   
1546        // console.log('carga mas');
1547        var cant_notas = $('.nota_gen').length;    
1548        //console.log(cant_notas);    
1549        var url = $(this).attr('rel')+cant_notas;       
1550        var tipo = $(this).attr(' data-tipo');      
1551        $.ajax({
1552            url: url,
1553            type: "POST",
1554            beforeSend: function() {
1555                $(".btn--mas_noticias").prop('disabled', true);
1556            }
1557        }).done(function(notas) {
1558            if (!notas || notas.err) {
1559                $(".btn--mas_noticias").remove();
1560                
1561            } else {
1562                var $notas = $(notas);
1563                $(".notas_seccion_").append( $notas);
1564                if(tipo == 'seccion'){                    
1565                    $('.p_seccion.hidden_publicidad .item-12').each(function(index, item){                    
1566                        if(index == 0)
1567                            $(this).appendTo($(".notas_seccion_"));                          
1568                    });      
1569                }                
1570            }                
1571            $(".btn--mas_noticias").prop('disabled', false);
1572            comprobarCargamas();
1573        }).error(function(error) {
1574            $(".btn--mas_noticias").remove();                           
1575        }); 
1576    }); 
1577}
1578
1579function hitGA(eventCategory, action, eventLabel, value) {
1580    console.log("enviando hitGa " +eventCategory, action)
1581    gtag('event', action, {
1582        'event_category' : eventCategory,
1583        'event_label':eventLabel
1584    });
1585}
1586
1587function checkSuscripcion() {
1588    var url = location.pathname;
1589    var isNota = location.pathname.indexOf("/nota/") != -1;
1590
1591    if(!isNota) return;
1592
1593    var user_id_ = readCookie('user_id')
1594    var mostrar_Signwall = readCookie("mostrar_Signwall");
1595    var mostrar_Paywall = readCookie("mostrar_Paywall");
1596    var mostrar_NotaCerrada = readCookie("mostrar_NotaCerrada");
1597
1598    eraseCookie("mostrar_Signwall");
1599    eraseCookie("mostrar_Paywall");
1600    eraseCookie("mostrar_NotaCerrada");
1601
1602    if (mostrar_Signwall) {
1603        console.log("checkSuscripcion - mostrar_Signwall - ejecutando hitGA Bloqueo")
1604        hitGA("Bloqueo", "Singwall");
1605        createCookie("limitPaywall", url, "" ,10);
1606        window.location.replace((window.__staticHost || "") + "/suscripcion_web/login?publi=true")
1607    }
1608    if (mostrar_Paywall) {
1609        console.log("checkSuscripcion - mostrar_Paywall")
1610        hitGA("Bloqueo", "Paywall", readCookie("user_id"));
1611        window.location.replace((window.__staticHost || "") + "/suscripcion_web?publi=true")
1612    }
1613    if (mostrar_NotaCerrada) {
1614        console.log("checkSuscripcion -mostrar_NotaCerrada")
1615        if(!user_id_){
1616            window.location.replace((window.__staticHost || "") + "/suscripcion_web/login?publi=true")
1617        }else{
1618            window.location.replace((window.__staticHost || "") + "/suscripcion_web?publi=true")
1619        }
1620    }
1621}
1622
1623function inicializarNota() {
1624    console.log("INIT NOTA")
1625    if(!$("#nota").length) return;
1626
1627    var nota = getObject($('#nota'));
1628    var link = nota.link || window.location.pathname.replace("/nota/","");
1629    var url = nota.server_public_url+"/nota/"+link || window.location.href;
1630
1631    eventosMuroDePago()
1632    mostrarSuscripcionPaywall()
1633    // getShares(nota.id, url, nota.comentada, nota.share_fb, nota.comentada_fb);
1634}
1635
1636function mostrarSuscripcionPaywall() {
1637    var mSusPaywall = readCookie("mostrar_mSuscripcionPaywall");
1638    eraseCookie("mostrar_mSuscripcionPaywall");
1639    if (mSusPaywall) {
1640        const elemento = document.getElementById("mSusPaywallNotapage");
1641        const cuerpoNota = document.getElementById("cuerpoNotapage");
1642        const fComents = document.getElementById("facebookComents");
1643        if (elemento) {
1644            elemento.style.display = "block"; 
1645        }
1646        if( cuerpoNota ){
1647            cuerpoNota.style.display = "none"; 
1648        }
1649        if( fComents ){
1650            cuerpoNota.style.display = "none"; 
1651        }
1652    }
1653}
1654
1655function eventosMuroDePago() {
1656
1657    var mostrar_Muro10 = readCookie("mostrar_Muro10");
1658    var mostrar_Muro30 = readCookie("mostrar_Muro30");
1659    var mostrar_Paywall = readCookie("mostrar_Paywall");
1660    var notasLeidas = readCookie("notasLeidas");
1661    eraseCookie("mostrar_Paywall");
1662    eraseCookie("mostrar_Muro10");
1663    eraseCookie("mostrar_Muro30");
1664    if (mostrar_Muro10) {
1665        console.log("Eventos de muro de pago - El usuario llego a su 10ma 
1665nota leida")
1666        gtag('event', 'muro_10', {
1667            event_category: 'muro',
1668            event_label: 'Usuario alcanzó 10 notas',
1669            value: 10
1670        });
1671    }
1672    if (mostrar_Muro30) {
1673        console.log("Eventos de muro de pago - El usuario llego a su 30ma nota leida")
1674        gtag('event', 'muro_30', {
1675            event_category: 'muro',
1676            event_label: 'Usuario alcanzó 30 notas',
1677            value: 30
1678          });
1679    }
1680    if (mostrar_Paywall) {
1681        console.log("Eventos de muro de pago - Muro de pago visible")
1682        gtag('event', 'muro_mostrado', {
1683            event_category: 'muro',
1684            event_label: 'Muro de pago visible',
1685            motivo: 'limite alcanzado',
1686            notas_leidas: notasLeidas
1687        });
1688    }
1689}
1690
1691
1692function getObject(obj) {
1693    return obj[0].dataset;
1694}
1695
1696function getShares(id, url , _comentada, _share_fb, _comentada_fb) {
1697    var nota = getObject($('#nota'));
1698    $.post("/shares?js=true", {
1699        id: id,
1700        lectura: true,
1701        hash: nota.hash,
1702        isJs: true
1703    }, checkSuscripcion);
1704    $.ajax({
1705        url: "https://graph.facebook.com/"+ encodeURIComponent(url),
1706        dataType: 'jsonp',
1707    }).done(function(data) {
1708        if(!data.share) return;
1709        
1710        var share_fb = parseInt(data.share.share_count);
1711        var comentada_fb = parseInt(data.share.comment_count);
1712        var prev_share_fb = parseInt(_share_fb);
1713        var prev_comentada = parseInt(_comentada_fb);
1714        if (isNaN(share_fb)) share_fb = 0;
1715        if (isNaN(comentada_fb)) comentada_fb = 0;
1716        if (isNaN(prev_share_fb)) prev_share_fb = 0;
1717        if (isNaN(prev_comentada)) prev_comentada = 0;
1718
1719        if (prev_share_fb < share_fb || prev_comentada < comentada_fb) {
1720            $.post("/shares?js=true", {
1721                id: id,
1722                comentada_fb: comentada_fb,
1723                share_fb: share_fb,
1724                isJs: true
1725            });
1726        }
1727    });
1728}
1729
1730function initGenerico(){
1731   
1732
1733    $(".video-js").each(function () {
1734        $(this).addClass("lazyload").attr("data-expand", "300");
1735    })
1736
1737    //searchBtn.addEventListener("click", expand);
1738   
1739    comprobarCargamas(); 
1740    jQueryTabs2(); 
1741    menuSticky();
1742    publicidadStickyFooter();
1743    
1744
1745    $(".hamburger").removeClass("is-active");   
1746   
1747
1748    $(".video-thumbnail").click(function () {
1749        $(".video-thumbnail").removeClass('is-active');
1750        $(this).addClass('is-active');
1751
1752        var video = $(this).data("video");
1753        console.log(video);
1754        
1755       
1756        videojs('#video-js-carga').dispose();
1757       
1758        var html = videoHTML(video);
1759
1760        $('.video-carga').html(html);
1761
1762        player = videojs('#video-js-carga');
1763        window.setTimeout('player.play()', 1500);
1764    });
1765
1766    $(".slick_generico:not(.slick-initialized)").slick({
1767        infinite: false,
1768        speed: 300,
1769        slidesToShow: 4,
1770        slidesToScroll: 1,
1771        arrows: true,
1772        swipe: true,
1773        dots: false,
1774        prevArrow: '<button class="PrevArrow"><</button>',
1775        nextArrow: '<button class="NextArrow">></button>',
1776        responsive: [{
1777                breakpoint: 1024,
1778                settings: {
1779                    slidesToShow: 3,
1780                    slidesToScroll: 3
1781                }
1782            },
1783            {
1784                breakpoint: 800,
1785                settings: {
1786                    slidesToShow: 2,
1787                    slidesToScroll: 2
1788                }
1789            },
1790            {
1791                breakpoint: 550,
1792                settings: {
1793                    slidesToShow: 2,
1794                    slidesToScroll: 1
1795                }
1796            }
1797
1798        ]
1799    });
1800}
1801
1802function videoHTML(videoNumber) {
1803    return '<video id="video-js-carga" class="video-js vjs-big-play-centered vjs-fluid" ' +
1804        'controls preload="auto" width="100%" ' +
1805        'data-setup=\'{"example_option":true, "youtube": { "iv_load_policy": 3 }}\'>' +
1806        '\t<source src="' + videoNumber + '" type="video/youtube" /> \n' +
1807        '</video>';
1808}
1809
1810function videoHTML_o(video) {             
1811    return '<video id="video-js-carga" class="video-js vjs-big-play-centered vjs-fluid" ' +
1812        'playsindivne width="100%" ' +
1813        'data-src="'+video+'">'+
1814        '</video>';
1815}
1816
1817function alert_position(scroll, celu, more_top) {
1818    if ( ($('.bloque_alerta ').length > 0)  && (stickyalert==true) ) {
1819        var scrolldesder = 450;
1820        var topp="100px"
1821        if (celu) {
1822            topp="113px"
1823            scrolldesder = 300;
1824        }
1825        if (scroll > scrolldesder) {
1826            if(celu && more_top < scroll)
1827                topp="72px"
1828            $('.bloque_alerta ').css({
1829                "position": "fixed",
1830                "top": topp,
1831                "z-index": "222",
1832                "width": "100%",
1833                "margin": "0 ",
1834                "padding-bottom": " 5px"
1835
1836            });
1837        } else {
1838            $('.bloque_alerta ').css({
1839                "position": "relative",
1840                "top": "initial",
1841                "z-index": "0",
1842                "margin": "10px 0",
1843                "width": "100%",
1844                "padding-bottom": " 0"
1845            });
1846        }
1847
1848    }
1849
1850}
1851
1852
1853function initHome(url){        
1854    if (url == "/"){
1855        console.log('Home');
1856        notasSlider();
1857        jQueryTabs();
1858        if(  $("#cotizaciones").length && ismobile )
1859            animatethis($('#cotizaciones'), 15000);         
1860
1861        $(".um_close").click(function(event) {
1862            $('.ultimo-momento').fadeOut( "slow", function(){
1863                $('.espaciador_um').hide(); 
1864                $(this).remove();
1865            });
1866        }); 
1867    }
1868}
1869
1870function publicidadStickyFooter(){   
1871    $(document).on('click', '.close_sticky', function (event) {
1872        $(this).parents(".publicidad_footer_sticky").find($(".contenedor__publicidad")).remove();
1873    });
1874}
1875
1876function initMultimedia(  ){
1877    if ($('#multimedia').length ){
1878       notasSlider();
1879    }  
1880
1881    if (  $(".multimedia_video").length ){
1882       var ide=$(".multimedia_video_principal").attr("id");
1883       onYouTubePlayerAPIReadyCB(ide,true,ismobile,autoplay_variable)
1884    }
1885};
1886
1887var SCRIPTS_LOADED = false;
1888
1889function initNotapage(url){
1890    if (url.indexOf("/nota/") != -1 || url.indexOf("/embed/") != -1){
1891        console.log('Nota');
1892
1893
1894        var datos = $(".datos_ubicacion");
1895        // if (datos.data("id")) getShares(datos.data("id"));
1896        notasSlider();
1897        jQueryTabs();
1898        jQueryTabsH();   
1899        buttonCMS(getId());
1900        video_encuerpo();
1901
1902        if (!SCRIPTS_LOADED) {
1903            loadScript("//cdn.playbuzz.com/widget/feed.js");
1904            loadScript("//platform.twitter.com/widgets.js");
1905            loadScript("//www.instagram.com/embed.js");
1906            loadScript("//public.flourish.studio/resources/embed.js");
1907            SCRIPTS_LOADED = true;
1908        }
1909
1910        if (typeof FB == 'object')
1911            FB.XFBML.parse();
1912        if (typeof twttr == 'object')
1913            twttr.widgets.load();
1914
1915        $( ".cuerpo p img" ).each(function( done ) {        
1916            var link_img = $( this ).attr('src');         
1917            var me = this;
1918            $( me ).replaceWith( "<img src='"+link_img+"'>" );            
1919        });
1920        var base_s=150;
1921
1922        //Inicializamos sticky redes sociales notapage
1923        if( $(window).width() > 775){
1924            if($('.detalle--nota.nota-de-investigacion').length ){
1925                $(".redes_wrapper .redes").stick_in_parent({offset_top  : base_s, parent:".detalle--nota"});
1926            }else{
1927                $(".redes_wrapper .redes").stick_in_parent({offset_top  : base_s, parent:".cont-wrapper"});
1928            }
1929        }
1930
1931        //Agregar publicidad en cuerpo de nota
1932        if($('.detalle--nota .cuerpo > p').length ){
1933            var destino = $(".detalle--nota .cuerpo:not(.publicitado) > p")
1934            var cantparrafos = destino.length;
1935            for (var i = 1; i < cantparrafos; i++) {                
1936                if(i == 1)
1937                    $('.publicidad_cuerpo .contenedor__publicidad').clone().appendTo(destino.eq(i));
1938                var resto = i % 3;
1939                if(resto==0){                    
1940                    $('.publicidad_cuerpo .contenedor__publicidad').clone().appendTo(destino.eq(i));                    
1941                }
1942            }
1943            $(".detalle--nota .cuerpo:not(.publicitado)").addClass('publicitado');
1944        }
1945        if (!ismobile){
1946            //Agregar publicidad sticky cuerpo de nota
1947            $(".publi_sticky").stick_in_parent({spacer: false});
1948        }
1949
1950    }        
1951}
1952
1953
1954function getYoutubeId(url) {
1955    if(!url)
1956        return;
1957    var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
1958    var match = url.match(regExp);
1959
1960    if (match && match[2].length == 11) {
1961        return match[2];
1962    } else {
1963        return 'error';
1964    }
1965}
1966
1967
1968function initSeccion(url){
1969    if ($('#seccion').length){
1970        console.log('Seccion');
1971        cargamas();
1972        notasSlider();
1973        var seccion = $('#seccion').val();
1974        $(".menu_").removeClass('is-active')
1975        $(".menu_"+seccion).addClass('is-active');
1976    }
1977}
1978
1979function initTag(url){
1980    if ($('#tag').length){
1981        console.log('Tags');
1982        cargamas();
1983        var userId = readCookie("userId");
1984        if(userId){
1985            var userTags = readCookie("userTags");                   
1986            var actualTag = $('#tag').val();
1987            var tagId = $('#tagId').val();
1988            userTags = userTags.replace('j:', '');
1989            userTags = JSON.parse(userTags);              
1990            if(userTags && userTags != ''){
1991                if (Object.values(userTags).indexOf(tagId) > -1) {
1992                    $('.seguir_tag').text('SIGUIENDO');  
1993                    $('.seguir_tag').attr('rel', 'dejar-seguir');
1994                }                                        
1995            }
1996        }
1997
1998        $('.seguir_tag').click(function(event) {
1999            if(userId){
2000                event.preventDefault();
2001                event.stopPropagation();
2002                var rel = $(this).attr('rel');
2003                var url = '/'+rel;
2004                var data = {
2005                    'userId': userId,
2006                    'actualTag':actualTag,
2007                    'tagId':tagId,
2008                    'tipo': 'tag'
2009                }
2010                
2011                $.ajax({
2012                    url: url,
2013                    data: data,
2014                    type: 'POST',
2015                }).done(function(res) { 
2016                    userTags = readCookie("userTags");                     
2017                    if(rel == 'seguir'){
2018                        $('.seguir_tag').text('SIGUIENDO');     
2019                        $('.seguir_tag').attr('rel', 'dejar-seguir');                               
2020                    }
2021                    else{
2022                        $('.seguir_tag').text('SEGUIR');    
2023                        $('.seguir_tag').attr('rel', 'seguir');                                
2024                    }
2025                }).error(function(res) {                                                               
2026                    console.log(res);                          
2027                }); 
2028            }
2029            else{
2030                $('#login_modal').modal('show');
2031                event.preventDefault();
2032                event.stopPropagation();  
2033            }
2034
2035        });
2036    }
2037}
2038
2039function initAutor(url){
2040    if ($('#autor').length){
2041        console.log('Autor');
2042        cargamas();
2043        var userId = readCookie("userId");
2044        if(userId){
2045            var userAutor = readCookie("userAutor");                   
2046            var autorId = $('#autorId').val();
2047            userAutor = userAutor.replace('j:', '');
2048            userAutor = JSON.parse(userAutor);                                
2049            if(userAutor && userAutor != ''){
2050                if (Object.values(userAutor).indexOf(autorId) > -1) {
2051                    $('.seguir_autor').text('SIGUIENDO');  
2052                    $('.seguir_autor').attr('rel', 'dejar-seguir');
2053                }                                        
2054            }
2055        }
2056        $('.seguir_autor').click(function(event) {
2057            if(userId){
2058                event.preventDefault();
2059                event.stopPropagation();
2060                var rel = $(this).attr('rel');
2061                var url = '/'+rel;
2062                var data = {
2063                    'userId': userId,                    
2064                    'autorId':autorId,
2065                    'tipo': 'autor'
2066                }
2067                
2068                $.ajax({
2069                    url: url,
2070                    data: data,
2071                    type: 'POST',
2072                }).done(function(res) { 
2073                    userTags = readCookie("userTags");                     
2074                    if(rel == 'seguir'){
2075                        $('.seguir_autor').text('SIGUIENDO');     
2076                        $('.seguir_autor').attr('rel', 'dejar-seguir');                               
2077                    }
2078                    else{
2079                        $('.seguir_autor').text('SEGUIR');    
2080                        $('.seguir_autor').attr('rel', 'seguir');                                
2081                    }
2082                }).error(function(res) {                                                               
2083                    console.log(res);                          
2084                }); 
2085            }
2086            else{
2087                $('#login_modal').modal('show');
2088                event.preventDefault();
2089                event.stopPropagation();  
2090            }
2091
2092        });
2093    }
2094}
2095
2096function initBusqueda(url){
2097    if ($('#busqueda').length){
2098        console.log('Busqueda');
2099        cargamas();
2100    }
2101}
2102
2103function initVideojs() {
2104    if (typeof videojs != "function")
2105        return console.log("FALTA LIBRERIA VIDEJS")
2106    var id = $(this).attr("id");
2107    var src = $(this).data("src");
2108    var poster = $(this).data("poster");
2109    var autoplay = $(this).data("autoplay") && autoplay_variable;
2110    var mute = $(this).data("mute") && autoplay_variable;
2111    var options = {
2112        autoplay: false,
2113        muted: mute,
2114        controls: true,
2115        fluid: true,
2116        aspectRatio: "16:9",
2117        youtube: { "iv_load_policy": 3 },
2118        poster: poster,
2119        sources: [{
2120            src: src
2121        }],
2122        preload: false
2123    };
2124
2125    if (options.sources[0].src.indexOf("youtube") != -1 || options.sources[0].src.indexOf("youtu.be") != -1) {
2126        options.techOrder = ['youtube'],
2127            options.sources[0].type = "video/youtube";
2128    }
2129    if (options.sources[0].src.indexOf(".m3u8") != -1)
2130        options.sources[0].type = "application/x-mpegURL";
2131    if (options.sources[0].src.indexOf(".mp4") != -1)
2132        options.sources[0].type = "video/mp4";
2133    var player = videojs(id, options);
2134    if (autoplay) {
2135        player.ready(function () {
2136            var promise = player.play();
2137
2138
2139            if (promise !== undefined) {
2140                promise.then(function () {
2141                    // Autoplay started!
2142                }).catch(function (error) {
2143                    // Autoplay was prevented.
2144                });
2145            }
2146        });
2147    }
2148}

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.