PageSourceSearch

https://www.cubelles.cat/front/view/js/functions.js?ver=1790937495

js cubelles.cat collected 2026-10-02 10:39:32 UTC 56,673 bytes, 1,908 lines download raw bytes

1"use strict";
2
3var Calendari = null;
4var CalendariId = null;
5var CalendariName = null;
6var CalendarType = 0;
7
8function isDesktop() {
9  if ($("body").width() < WIDTH_DESKTOPS) {
10    return true;
11  } else {
12    return false;
13  }
14}
15function isTablet() {
16  if ($("body").width() < WIDTH_TABLETS) {
17    return true;
18  } else {
19    return false;
20  }
21}
22function isSmartphone() {
23  if ($("body").width() < WIDTH_SMARTPHONES) {
24    return true;
25  } else {
26    return false;
27  }
28}
29function isPhone() {
30  if ($("body").width() < WIDTH_PHONES) {
31    return true;
32  } else {
33    return false;
34  }
35}
36function hideMsg() {
37  $(".messages").hide("slow");
38  $(".messages").html("");
39  $(".messages").show("fast");
40}
41	
42/**
43 * Normalize 'pag' query parameter in the URL without reloading the page.
44 * Ensures 'pag' is between 1 and 1000 and replaces the URL via history.replaceState.
45 */
46function normalizeSearchPag() {
47  try {
48    if (typeof URL === 'undefined') { return; }
49    var u = new URL(window.location);
50    var orig = u.searchParams.get('pag');
51    if (orig === null) { return; }
52    var pag = parseInt(orig, 10);
53    var san = Number.isInteger(pag) ? Math.max(1, Math.min(1000, pag)) : 1;
54    if (String(san) !== orig) {
55      u.searchParams.set('pag', san);
56      window.history.replaceState(null, '', u.toString());
57    }
58  } catch(e) {
59  }
60}
61function getDateInfo(date, wantsClassName) {
62  var articleId = $(this)[0].id;
63  var as_number = Calendar.dateToInt(date);
64  return DATE_INFO[articleId][as_number];
65}
66function initPestanyesTabs() {
67  $(".o-tabs").each(function () {
68    var $tabs = $(this);
69    if ($tabs.data("pestanyes-init")) {
70      return;
71    }
72    $tabs.data("pestanyes-init", true);
73    var $buttons = $tabs.find("> .o-tabs__nav .o-tabs__tab");
74    var $panels = $tabs.find("> .o-tabs__panels > .o-tabs__panel");
75
76    function activate($btn) {
77      var targetSel = $btn.attr("data-tab-target");
78      $buttons.removeClass("is-active").attr("aria-selected", "false").attr("tabindex", "-1");
79      $buttons.parent().removeClass("is-active");
80      $panels.removeClass("is-active").attr("hidden", "hidden");
81      $btn.addClass("is-active").attr("aria-selected", "true").attr("tabindex", "0");
82      $btn.parent().addClass("is-active");
83      $tabs.find(targetSel).addClass("is-active").removeAttr("hidden");
84    }
85
86    $buttons.on("click", function (e) {
87      e.preventDefault();
88      activate($(this));
89    });
90    $buttons.on("keydown", function (e) {
91      var idx = $buttons.index(this);
92      var newIdx = null;
93      if (e.key === "ArrowRight" || e.keyCode === 39) {
94        newIdx = (idx + 1) % $buttons.length;
95      } else if (e.key === "ArrowLeft" || e.keyCode === 37) {
96        newIdx = (idx - 1 + $buttons.length) % $buttons.length;
97      } else if (e.key === "Home" || e.keyCode === 36) {
98        newIdx = 0;
99      } else if (e.key === "End" || e.keyCode === 35) {
100        newIdx = $buttons.length - 1;
101      }
102      if (newIdx !== null) {
103        e.preventDefault();
104        var $next = $buttons.eq(newIdx);
105        activate($next);
106        $next.trigger("focus");
107      }
108    });
109  });
110}
111
112function start() {
113  // show menu if resize from table width
114  window.addEventListener("resize", resizeMainMenu);
115
116  // Inicialitzar pestanyes dels contenidors
117  initPestanyesTabs();
118
119  // resize columns
120  setEqualContentColumns();
121  window.addEventListener("resize", setEqualContentColumns);
122
123  // resize logo
124  checkResizeLogo();
125  window.addEventListener("resize", checkResizeLogo);
126
127  // resize footer Sitemap
128  resizeFooterSitemap();
129  window.addEventListener("resize", resizeFooterSitemap);
130
131  var watchMasonryGroup = [];
132  window.addEventListener("resize", function () {
133    resizeMasonry(watchMasonryGroup);
134    setTimeout(function () {
135      resizeMasonry(watchMasonryGroup);
136    }, 100);
137    setTimeout(function () {
138      resizeMasonry(watchMasonryGroup);
139    }, 500);
140  });
141
142  // Footer featureds slider
143  $(".highlights .bxslider, .o-widget--footer .highlights .bxslider").bxSlider({
144    infiniteLoop: false,
145    adaptiveHeight: true,
146    hideControlOnEnd: true,
147    minSlides: 1,
148    maxSlides: 7,
149    slideWidth: 130,
150    slideMargin: 0,
151    preventDefaultSwipeY: true,
152    nextText: "Següent",
153    prevText: "Anterior",
154    onSliderLoad: function () {
155      $(".highlights .bxslider, .o-widget--footer .highlights .bxslider").css(
156        "display",
157        "block"
158      );
159    },
160  });
161
162  // Meteocat slider
163  if (
164    $("#cm_meteocat .bxslider, .o-widget--footer .highlights .bxslider")
165      .length !== 0
166  ) {
167    $(
168      "#cm_meteocat .bxslider, .o-widget--footer .highlights .bxslider"
169    ).bxSlider({
170      infiniteLoop: false,
171      adaptiveHeight: true,
172      hideControlOnEnd: true,
173      preventDefaultSwipeY: true,
174      nextSelector: "#slider-next",
175      prevSelector: "#slider-prev",
176      nextText: "Següent",
177      prevText: "Anterior",
178      onSliderLoad: function () {
179        $(
180          "#cm_meteocat .bxslider, .o-widget--footer .highlights .bxslider"
181        ).css("display", "block");
182      },
183    });
184  }
185
186  // resize footer Plugins
187  resizeFooterPlugins();
188  window.addEventListener("resize", resizeFooterPlugins);
189
190  /* Subscripció Newsletter (Butlletí Digital) */
191  $('.NewsletterForm input:radio[name="group1"]').change(function () {
192    if (
193      $(".NewsletterForm input:radio[name=group1]:checked").val() == "Totes"
194    ) {
195      $("#CategoryList:visible").slideUp("slow", function () {
196        setEqualContentColumns();
197      });
198    } else {
199      $("#CategoryList:hidden").slideDown("slow", function () {
200        setEqualContentColumns();
201      });
202    }
203  });
204  $("INPUT[type='checkbox']").click(function () {
205    checkChildsNewsletterForm($(this).attr("id"));
206    checkParentsNewsletterForm($(this).parent().attr("id"), $(this).attr("id"));
207  });
208
209  /* Filter for carrerer */
210  if ($("body").hasClass("md_carrerer")) {
211    $(".conditional").click(function () {
212      var moduleFilterParent = $(this).closest("form#ModuleFilter");
213
214      if (moduleFilterParent.length === 0) {
215        checkChildsFilterCategories($(this).attr("id"));
216        checkParentsFilterCategories(
217          $(this).parent().parent().parent().attr("id"),
218          $(this).attr("id")
219        );
220      }
221      setEqualContentColumns();
222    });
223  }
224
225  /* Areas/Themes columnes */
226  if ($("body").hasClass("theme")) {
227    setEqualContentThemes();
228    window.addEventListener("resize", setEqualContentThemes);
229  }
230
231  /* External share buttons */
232  shareTwitter();
233  shareFacebook();
234
235  // Filtres
236  if ($("#ContentFilter").length !== 0) {
237    $("#all_selection").click(function () {
238      $("#" + $(this).attr("rel") + " INPUT[type='checkbox']").attr(
239        "checked",
240        true
241      );
242      return false;
243    });
244    $("#none_selection").click(function () {
245      $("#" + $(this).attr("rel") + " INPUT[type='checkbox']").attr(
246        "checked",
247        false
248      );
249      return false;
250    });
251    $("#invert_selection").click(function () {
252      $("#" + $(this).attr("rel") + " INPUT[type='checkbox']").each(
253        function () {
254          $(this).attr("checked", !$(this).attr("checked"));
255        }
256      );
257      return false;
258    });
259  }
260  // Forms
261  $(document).on("submit", "form", function (e) {
262    $(this)
263      .find("input[type=checkbox]")
264      .each(function () {
265        var checkbox = $(this);
266        // Afegirem un camp ocult amb el mateix nom (y valor NO) davant
267        // del checkbox sense marcar per a que es passi el valor sempre
268        if (!checkbox.prop("checked")) {
269          checkbox
270            .clone()
271            .prop("type", "hidden")
272            .val("No")
273            .insertBefore(checkbox);
274        }
275      });
276  });
277
278  	
279  // Normalize search pagination parameter before initializing widgets
280  normalizeSearchPag();
281  // Inicializa todos los sliders de widgets (incluido el de portada)
282  startWidgetSliders();
283  resizeMasonry(watchMasonryGroup);
284  equalHeightIconTime();
285  // 02-09-2021 - En el cas que es vulgui la mateixa alçada dels containers
286  //equalHeightWidgetContainerRow();
287  $(".carousel").each(function () {
288    initCarousel($(this).attr("data-bs-id"), $(this).attr("data-bs-interval"));
289  });
290}
291
292function reviewForm(formScope) {
293  // Limita la validació al formulari que fa submit; si no s'indica, valida tot el document.
294  var $scope = formScope && $(formScope).length ? $(formScope) : $(document);
295  var alertMessage = "";
296  var returnReview = true;
297  var errorSubmit = $("#errorSubmit");
298  $("#buttonSubmit").prop("disabled", true);
299  errorSubmit.empty();
300
301  // Neteja marcadors d'error anteriors
302  $(".is-invalid").removeAttr("aria-invalid").removeAttr("aria-describedby").removeClass("is-invalid");
303  $(".form-consent--invalid").removeClass("form-consent--invalid");
304  $(".form-field-error").remove();
305
306  // Construeix l'span d'error accessible (icona + role alert) i relaciona'l amb el camp via aria
307  function buildFieldError(field, message) {
308    var fieldId = field.attr("id");
309    var errorId = fieldId ? fieldId + "-error" : "";
310    field.attr("aria-invalid", "true");
311    if (errorId) {
312      field.attr("aria-describedby", errorId);
313    }
314    return '<span' + (errorId ? ' id="' + errorId + '"' : '') + ' class="form-field-error" role="alert">
314' +
315      '<i class="fa-solid fa-circle-exclamation" aria-hidden="true"></i> ' + message + '</span>';
316  }
317
318  // Valida camps obligatoris — error inline per camp
319  $scope.find("[required]").each(function () {
320    var field = $(this);
321    var isEmpty = field.is("input[type=checkbox]")
322      ? !field.prop("checked")
323      : !field.val() || !field.val().trim();
324
325    if (isEmpty) {
326      field.addClass("is-invalid");
327      var errorMessage = buildFieldError(field, "Camp obligatori.");
328      var consent = field.closest(".form-consent");
329      if (consent.length) {
330        consent.addClass("form-consent--invalid");
331        consent.after(errorMessage);
332      } else {
333        field.after(errorMessage);
334      }
335      returnReview = false;
336    }
337  });
338
339  // Valida format i confirmació d'emails — error inline per camp
340  $scope.find("input[type=email]").each(function () {
341    var field = $(this);
342    var nom = field.attr("name");
343    var email = field.val().trim();
344    var regexp = new RegExp("^copia_");
345
346    if (!regexp.test(nom) && email !== "" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
347      field.addClass("is-invalid");
348      field.after(buildFieldError(field, "Adreça de correu electrònic no vàlida."));
349      returnReview = false;
350    }
351
352    if (regexp.test(nom)) {
353      var nombis = nom.replace("copia_", "");
354      if ($scope.find("[name='" + nombis + "']").length > 0) {
355        if ($($scope.find("[name='" + nombis + "']").get(0)).val() !== $($scope.find("[name='" + nom + "']").get(0)).val()) {
356          field.addClass("is-invalid");
357          field.after(buildFieldError(field, "Els correus electrònics no coincideixen."));
358          returnReview = false;
359        }
360      }
361    }
362  });
363  $scope
364    .find("input[type=checkbox]")
365    .each(function () {
366      var checkbox = $(this);
367      // Afegirem un camp ocult amb el mateix nom (y valor NO) davant
368      // del checkbox sense marcar per a que es passi el valor sempre
369      if (!checkbox.prop("checked")) {
370        checkbox
371          .clone()
372          .prop("type", "hidden")
373          .val("No")
374          .insertBefore(checkbox);
375      }
376    });
377
378  var total = $("#total");
379  if (total.length) {
380    var formTotal = calculaTotal();
381    if (total.val() === 0 || formTotal === 0) {
382      alertMessage += "<li>El import de la compra ha de ser superior a 0.</li>";
383      returnReview = false;
384    }
385  }
386
387  if (alertMessage !== "") {
388    errorSubmit.append(
389      '<div class="alert alert-danger">\n' +
390        '  <h4 id="submitError">Atenció!</h4> \n' +
391        "  <ul>" +
392        alertMessage +
393        "</ul>" +
394        "</div>"
395    );
396    // This prevents the page from scrolling down to where it was previously.
397    if ("scrollRestoration" in history) {
398      history.scrollRestoration = "manual";
399    }
400    window.scrollTo(0, 0);
401    returnReview = false;
402  }
403
404  if (returnReview === false) {
405    $("#buttonSubmit").prop("disabled", false);
406    var firstInvalid = $(".is-invalid").first();
407    if (firstInvalid.length) {
408      var stickyOffset = ($('#site-header').outerHeight() || 0) + 24;
409      $("html, body").animate({ scrollTop: firstInvalid.offset().top - stickyOffset }, 300);
410      firstInvalid.focus({ preventScroll: true });
411    }
412  }
413
414  return returnReview;
415}
416
417function calculaTotal() {
418  var total = 0;
419  $("input[id$=_total]").each(function () {
420    let t;
421    const id_total = $(this).attr("id");
422    const id = id_total.replace("_total", "");
423    const id_quantitat = id_total.replace("_total", "_quantitat");
424    const id_percentatge = id_total.replace("_total", "_percentatge");
425    const id_preu = id_total.replace("_total", "_preu");
426    const id_select = id_total.replace("_total", "_select_field");
427    if ($("#" + id_quantitat).length) {
428      t =
429        parseFloat(
430          $("#" + id)
431            .val()
432            .replace(",", ".")
433        ) *
434        parseFloat(
435          $("#" + id_quantitat)
436            .val()
437            .replace(",", ".")
438        );
439    }
440    if ($("#" + id_preu).length) {
441      t =
442        parseFloat(
443          $("#" + id)
444            .val()
445            .replace(",", ".")
446        ) *
447        parseFloat(
448          $("#" + id_preu)
449            .val()
450            .replace(",", ".")
451        );
452    }
453    if ($("#" + id_percentatge).length) {
454      t =
455        (parseFloat(
456          $("#" + id)
457            .val()
458            .replace(",", ".")
459        ) *
460          parseFloat(
461            $("#" + id_percentatge)
462              .val()
463              .replace(",", ".")
464          )) /
465        100;
466    }
467    if ($("#" + id_select).length) {
468      t = parseFloat(
469        $("#" + id + "_total")
470          .val()
471          .replace(",", ".")
472      );
473    }
474    if (!isNaN(t)) {
475      total += t;
476    }
477  });
478  return total;
479}
480
481var currentRequest;
482var Calendari;
483var CalendariName;
484var CalendariId;
485var CalendarType;
486
487function buildCalendars() {
488  var item;
489  if (typeof calendars !== "undefined") {
490    for (var i = calendars.length - 1; i >= 0; i--) {
491      item = calendars[i];
492      buildCalendar(item.id, item.data);
493    }
494  }
495}
496function buildCalendar(id, data, type = 0, day = "") {
497  if (typeof id === "undefined") return false;
498
499  var cutId = id.split("dv_calendar_");
500  CalendariName = id;
501  CalendariId = cutId[1];
502  CalendarType = type;
503
504  if (type === 0) {
505    CalendarType = $("#dv_calendar_" + id).attr("data-type");
506  }
507
508  function getDateFromUrl() {
509    var params = new URLSearchParams(window.location.search);
510    var dateStr = params.get("date");
511    if (dateStr) {
512      var parts = dateStr.split("-");
513      return new Date(parts[0], parts[1] - 1, parts[2]);
514    }
515    return new Date();
516  }
517
518  var getDateInfo = function (date, wantsClassName) {
519    var as_number = Calendar.dateToInt(date);
520    return data[as_number];
521  };
522
523  var cal = Calendar.setup({
524    cont: id,
525    fdow: 1,
526    noScroll: true,
527    bottomBar: false,
528    animation: false,
529    titleFormat: "%B %Y",
530    dateInfo: getDateInfo,
531    date: getDateFromUrl(),
532  });
533
534  Calendari = cal;
535
536  if (day !== "") {
537    cal.moveTo(day);
538  }
539
540  setEqualContentColumns();
541
542  getDataCalendar(CalendariId);
543
544  if (CalendariId === "default") {
545    const idCalendar = CalendariId;
546    const category = $("#dv_calendar_" + idCalendar).attr("data-category");
547    const dataToFind = new Date(
548      $("#dv_calendar_" + idCalendar + " .DynarchCalendar-month").attr(
549        "data-date"
550      )
551    );
552    ajaxCalendar(idCalendar, dataToFind, category);
553  }
554}
555
556function setDataCalendar(id, calendar, type, selected = 0) {
557  var cutId = id.split("dv_calendar_");
558  CalendariName = id;
559  CalendariId = cutId[1];
560  CalendarType = type;
561  if (selected !== 0) {
562    Calendari.moveTo(selected);
563  }
564}
565
566function getInternalCalendar(id) {
567  var cutId = id.split("dv_calendar_");
568  Calendari = Calendar.refresh();
569  CalendariName = id;
570  CalendariId = cutId[1];
571
572  getDataCalendar(CalendariId);
573}
574
575function getParameterByName(name) {
576  name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
577  var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
578    results = regex.exec(location.search);
579  return results === null
580    ? ""
581    : decodeURIComponent(results[1].replace(/\+/g, " "));
582}
583
584function getDataCalendar(id) {
585  var monthDown = $(
586    "#dv_calendar_" +
587      id +
588      " div.DynarchCalendar-prevMonth.DynarchCalendar-navBtn"
589  );
590  var monthUp = $(
591    "#dv_calendar_" +
592      id +
593      " div.DynarchCalendar-nextMonth.DynarchCalendar-navBtn"
594  );
595  var dia = $("#dv_calendar_" + id + " div.DynarchCalendar-day.dia_marcat a");
596  var diaLliure = $(
597    "#dv_calendar_" + id + " div.DynarchCalendar-day.dia_lliure a"
598  );
599  var diaOcupat = $(
600    "#dv_calendar_" + id + " div.DynarchCalendar-day.dia_ocupat a"
601  );
602
603  dia
604    .add(diaLliure)
605    .add(diaOcupat)
606    .on("click", function () {
607      console.log("📅 Día clicado:", $(this).data("day"));
608    });
609
610  monthDown.attr({ "data-id": id, role: "button", tabindex: "0", "aria-label": "Mes anterior" });
611  monthUp.attr({ "data-id": id, role: "button", tabindex: "0", "aria-label": "Mes següent" });
612
613  monthDown.on("mousedown", function (e) {
614    var id = $(this).attr("data-id");
615    var category = $("#dv_calendar_" + id).attr("data-category");
616    setTimeout(function () {
617      var data = new Date(
618        $("#dv_calendar_" + id + " .DynarchCalendar-month").attr("data-date")
619      );
620      ajaxCalendar(id, data, category);
621    }, 0);
622  });
623
624  monthDown.on("keydown", function (e) {
625    if (e.key === "Enter" || e.key === " ") {
626      e.preventDefault();
627      this.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true }));
628    }
629  });
630
631  monthUp.on("mousedown", function (e) {
632    var id = $(this).attr("data-id");
633    var category = $("#dv_calendar_" + id).attr("data-category");
634    setTimeout(function () {
635      var data = new Date(
636        $("#dv_calendar_" + id + " .DynarchCalendar-month").attr("data-date")
637      );
638      ajaxCalendar(id, data, category);
639    }, 0);
640  });
641
642  monthUp.on("keydown", function (e) {
643    if (e.key === "Enter" || e.key === " ") {
644      e.preventDefault();
645      this.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true }));
646    }
647  });
648}
649
650function ajaxCalendar(id, cal, cat = 0) {
651  var month = (cal.getMonth() + 1).toString().padStart(2, "0");
652  var ajaxData;
653
654  if (id === "slot") {
655    ajaxData = {
656      id: $(".select2")[1].value,
657      params: cal.getFullYear() + "-" + month + "-01",
658      type: "slots",
659    };
660  } else {
661    ajaxData = {
662      id: id,
663      params: cal.getFullYear() + "-" + month + "-01",
664      type: $("#dv_calendar_" + id).attr("data-type"),
665      category: cat,
666    };
667  }
668
669  // Cancelar petición anterior
670  if (currentRequest) {
671    currentRequest.abort();
672  }
673
674  currentRequest = $.ajax({
675    cache: false,
676    type: "POST",
677    url: "/calendar",
678    data: ajaxData,
679    success: function (result) {
680      // console.log("Mes solicitado:", ajaxData.params);
681
682      if (result !== "") {
683        var obj = JSON.parse(result);
684
685        // Eliminar comprobación que ignora el mes por la primera clave
686        var requestedMonth = ajaxData.params.substring(0, 7).replace("-", "");
687
688        if (id === "slot") {
689          clearCalendar();
690        }
691
692        for (var k in obj) {
693          // Solo pintar los días del mes solicitado
694          if (k.substring(0, 6) !== requestedMonth) continue;
695
696          if (obj[k] instanceof Object) {
697            var calendarDay = $(
698              "#dv_calendar_" +
699                id +
700                ' .DynarchCalendar-day[dyc-date="' +
701                k +
702                '"]'
703            );
704            if (!calendarDay.length) continue;
705
706            calendarDay.removeAttr("dyc-type");
707            calendarDay.attr("orioldyc-type", "date");
708            calendarDay.addClass(obj[k]["klass"]);
709            calendarDay.html("");
710
711            var attributeData = "";
712            var onclick = "";
713            var link = "";
714            var diaMes = obj[k]["day"];
715
716            if (id === "slot") {
717              link = "javascript:void(0)";
718              attributeData = data;
719              onclick = 'onclick="showTimeSlots(' + k + ')"';
720            } else {
721              link = obj[k]["lin"];
722            }
723
724            calendarDay.append(
725              '<a href="' +
726                link +
727                '" class="day" data-selected ="' +
728                attributeData +
729                '" data-day="' +
730                k +
731                '" ' +
732                onclick +
733                ">" +
734                diaMes +
735                "</a>"
736            );
737          }
738        }
739      }
740    },
741    error: function (xhr, status, error) {
742      if (status !== "abort") {
743        console.error("❌ Error AJAX:", status, error);
744      }
745    },
746  });
747}
748
749function gotolink(url) {
750  window.location = url;
751}
752
753function shareTwitter() {
754    if (!TWITTER || $("body").hasClass("home")) {
755        return;
756    }
757    (function (d, s, id) {
758        var js, fjs = d.getElementsByTagName(s)[0];
759        if (d.getElementById(id)) return;
760        js = d.createElement(s);
761        js.id = id;
762        js.src = "//platform.twitter.com/widgets.js";
763        fjs.parentNode.insertBefore(js, fjs);
764    })(document, "script", "twitter-wjs");
765}
766
767function shareFacebook() {
768    if (!FACEBOOK || $("body").hasClass("home")) {
769        return;
770    }
771    (function (d, s, id) {
772        var js, fjs = d.getElementsByTagName(s)[0];
773        if (d.getElementById(id)) return;
774        js = d.createElement(s);
775        js.id = id;
776        js.src = "//connect.facebook.net/ca_ES/all.js#xfbml=1";
777        fjs.parentNode.insertBefore(js, fjs);
778    })(document, "script", "facebook-jssdk");
779}
780
781function resizeMainMenu() {
782  if (!isTablet()) {
783    $("#Principal").css("display", "block");
784  } else {
785    $("#Principal").css("display", "none");
786  }
787}
788function checkResizeLogo() {
789  var finalWidth;
790  if (isTablet() && $("#mainLogo").attr("width") > 250) {
791    finalWidth = 250;
792  } else {
793    finalWidth = $("#mainLogo").attr("width");
794  }
795  if (finalWidth != $("#mainLogo").width()) {
796    resizeLogo(finalWidth);
797  }
798}
799function resizeLogo(finalWidth) {
800  var currentWidth = $("#mainLogo").attr("width");
801  var currentHeight = $("#mainLogo").attr("height");
802  var ratio = finalWidth / currentWidth;
803  $("#mainLogo").width(currentWidth * ratio);
804  $("#mainLogo").height(currentHeight * ratio);
805}
806function openBlock(id) {
807  event.preventDefault();
808  $("#" + id).slideDown("fold", function () {
809    setEqualContentColumns();
810  });
811}
812function closeBlock(id) {
813  event.preventDefault();
814  $("#" + id).slideUp("fold", function () {
815    setEqualContentColumns();
816  });
817}
818function setEqualContentColumns() {
819  setEqualHeight($(".content .container > div.col"));
820}
821function setEqualContentThemes() {
822  setEqualHeight($(".content .container div.themeColumns > div.col"));
823}
824function setEqualHeight(columns) {
825  if (!isDesktop()) {
826    var currentHeight;
827    var tallestcolumn = 0;
828    columns.height("auto");
829    columns.each(function () {
830      currentHeight = $(this).outerHeight();
831      if (currentHeight > tallestcolumn) {
832        tallestcolumn = currentHeight;
833      }
834    });
835    columns.each(function () {
836      if ($(this).hasClass("responsiveHeight") && isTablet()) {
837        $(this).height("auto");
838      } else {
839        $(this).height(tallestcolumn);
840      }
841    });
842  } else {
843    columns.height("auto");
844  }
845}
846function removeBlankColumns() {
847  var columns = [];
848  var totalColumns = 0;
849  $(".content .columns > .col:visible").each(function (index) {
850    var html = $(this).html().replace(/\s/g, "").replace(" ", "");
851    if (html == "") {
852      $(this).remove();
853    } else {
854      if ($(this).hasClass("double")) {
855        columns[index] = 2;
856        totalColumns = totalColumns + 2;
857      } else if ($(this).hasClass("triple")) {
858        columns[index] = 3;
859        totalColumns = totalColumns + 3;
860      } else {
861        columns[index] = 1;
862        totalColumns = totalColumns + 1;
863      }
864    }
865  });
866}
867function startClock(servertime) {
868  var localtime = new Date().getTime();
869  localtime = Math.floor(localtime / 1000);
870  var dif = servertime - localtime;
871  updateClock(dif);
872}
873function updateClock(dif) {
874  var today = new Date();
875  if (dif > 0 || dif < 0) {
876    today.setSeconds(today.getSeconds() + dif);
877  }
878  var Y = today.getFullYear();
879  var M = today.getMonth() + 1;
880  var D = today.getDate();
881  var h = today.getHours();
882  var m = today.getMinutes();
883  h = checkTime(h);
884  m = checkTime(m);
885  M = checkTime(M);
886  D = checkTime(D);
887  $("#clock").html(D + "." + M + "." + Y + " | " + h + ":" + m);
888  var t = setTimeout(function () {
889    updateClock(dif);
890  }, 10000);
891}
892function checkTime(i) {
893  if (i < 10) {
894    i = "0" + i;
895  } // add zero in front of numbers < 10
896  return i;
897}
898function removeFocus(level) {
899  // Remove focus attribute of current level and childs
900  $("." + level).removeAttr("focus");
901  $("." + level + " *").removeAttr("focus");
902}
903function addFocus(object) {
904  // Add focus attribute of current level and parent
905  $(object).parents("li").attr("focus", true);
906  $(object).focus();
907}
908function setFocus(object) {
909  var classes = $(object).parent().attr("class");
910  var level = getLevelFromClasses(classes);
911  removeFocus(level);
912  addFocus(object);
913  return object;
914}
915function getLevelFromClasses(string) {
916  var level;
917  $.each(string.split(" "), function (key, value) {
918    if (value.substring(0, 5) == "level") {
919      level = value;
920    }
921  });
922  return level;
923}
924function ssl_check_and_redirect(url) {
925  $.ajax({
926    url: url,
927    dataType: "script",
928    success: function () {
929      window.location.replace(url);
930    },
931  });
932}
933function redirect(url, target) {
934  if (target === "_blank") {
935    window.open(url, "_blank");
936  } else {
937    window.location = url;
938  }
939}
940function checkParentsNewsletterForm(id, current) {
941  if (typeof id !== "undefined" && id != "CategoryList") {
942    var match = 0;
943    var total = 0;
944    $("#" + id)
945      .children("input[type='checkbox']")
946      .each(function (index) {
947        total = total + 1;
948        if (!$(this).is(":checked")) {
949          match = match + 1;
950        }
951      });
952    var parent_input = id.split("-");
953    if (match == total) {
954      $("#" + parent_input[1]).attr("checked", true);
955    } else {
956      $("#" + parent_input[1]).attr("checked", false);
957    }
958    checkParentsNewsletterForm(
959      $("#" + parent_input[1])
960        .parent()
961        .attr("id"),
962      $("#" + parent_input[1]).attr("id")
963    );
964  }
965}
966function checkChildsNewsletterForm(id) {
967  if (!$("#" + id).is(":checked")) {
968    $("#childs-" + id + " input[type='checkbox']").each(function (index) {
969      if ($(this).is("input[type='checkbox']")) {
970        $(this).attr("checked", false);
971      }
972    });
973  } else {
974    $("#childs-" + id + " input[type='checkbox']").each(function (index) {
975      if ($(this).is("input[type='checkbox']")) {
976        $(this).attr("checked", true);
977      }
978    });
979  }
980}
981function switchFilter(id) {
982  var obj = document.getElementById(id);
983  if (obj.className == "detallHide") {
984    obj.className = "";
985  } else {
986    obj.className = "detallHide";
987  }
988}
989function checkParentsFilterCategories(id, current) {
990  if ($("#" + current).is(":checked")) {
991    var match = 0;
992    $("#" + id + " input[type='checkbox']").each(function (index) {
993      if (!$(this).is(":checked")) {
994        match = match + 1;
995      }
996    });
997    var parent_input = id.split("-");
998    if (match > 0) {
999      $("#" + parent_input[1]).attr("checked", true);
1000    } else {
1001      $("#" + parent_input[1]).attr("checked", false);
1002    }
1003    checkParentsFilterCategories(
1004      $("#" + parent_input[1])
1005        .parent()
1006        .parent()
1007        .attr("id"),
1008      $("#" + parent_input[1]).attr("id")
1009    );
1010  }
1011}
1012function checkChildsFilterCategories(id) {
1013  if (!$("#" + id).is(":checked")) {
1014    $("#childs-" + id + " input[type='checkbox']").each(function (index) {
1015      if ($(this).is("input[type='checkbox']")) {
1016        $(this).attr("checked", false);
1017      }
1018    });
1019    $("#childs-" + id + "").hide();
1020    setEqualContentColumns();
1021  } else {
1022    $("#childs-" + id + " input[type='checkbox']").each(function (index) {
1023      if ($(this).is("input[type='checkbox']")) {
1024        $(this).attr("checked", true);
1025      }
1026    });
1027    $("#childs-" + id + "").show();
1028  }
1029}
1030function loadAjaxWidgets() {
1031  $(".js-widget[data-load='ajax']").each(function () {
1032    var id = $(this).attr("data-id");
1033    var idPage = $(this).attr("data-page") ?? 0;
1034    var widget = $(this);
1035    var widgetContent = widget.find(".js-widget__content");
1036    loadAjaxWidget(id, idPage, widget, widgetContent);
1037  });
1038}
1039function loadAjaxWidget(id, idPage, widget, widgetContent) {
1040  $.ajax({
1041    cache: false,
1042    type: "POST",
1043    url: "/widget",
1044    data: {
1045      id: id,
1046      idpage: idPage,
1047    },
1048    success: function (result) {
1049      if (result.trim().length) {
1050        widget.show();
1051        widgetContent.html(result);
1052        reloadWidgetFunctionalities();
1053      } else {
1054        widget.hide();
1055      }
1056    },
1057  });
1058}
1059
1060function reloadWidgetFunctionalities() {
1061  $(".js-widget__content img").each(function () {
1062    if (typeof this.load !== "undefined") {
1063      this.load();
1064    }
1065  });
1066
1067  if ($("#cm_meteocat ul.bxslider").length !== 0) {
1068    $("#cm_meteocat .bxslider").bxSlider({
1069      infiniteLoop: false,
1070      adaptiveHeight: true,
1071      hideControlOnEnd: true,
1072      preventDefaultSwipeY: true,
1073      nextSelector: "#slider-next",
1074      prevSelector: "#slider-prev",
1075      nextText: "Següent",
1076      prevText: "Anterior",
1077      onSliderLoad: function () {
1078        $("#cm_meteocat .bxslider").css("display", "block");
1079      },
1080    });
1081  }
1082}
1083function hideEmptyWidgets() {
1084  // Amagar widgets
1085  $(".o-widget > .o-widget-wrapper > .o-widget__content").each(function () {
1086    if (!$(this).html().trim()) {
1087      var currentWidgetElement = $(this).closest(".o-widget");
1088
1089      $(currentWidgetElement).hide();
1090      if (!$(currentWidgetElement).hasClass("empty-widget")) {
1091        $(this).closest(".o-widget").addClass("empty-widget");
1092      }
1093    }
1094  });
1095
1096  // Amagar contenidors
1097  $(".o-widget.o-widget-contenidor").each(function () {
1098    var currentContainer = $(this);
1099    var childWidgets = $(this).find(".o-widget");
1100    var totalChildWidgets = childWidgets.length;
1101    var hiddenWidgets = 0;
1102
1103    $(childWidgets).each(function () {
1104      if ($(this).hasClass("empty-widget")) {
1105        hiddenWidgets++;
1106        if (hiddenWidgets >= totalChildWidgets) {
1107          $(currentContainer).hide();
1108
1109          if (!$(currentContainer).hasClass("empty-widget")) {
1110            $(currentContainer).addClass("empty-widget");
1111          }
1112        }
1113      }
1114    });
1115  });
1116}
1117function checkPasswordStrength() {
1118  var accpetedStrengths = ["medium", "strong"];
1119  var passwordStrength = $("div[data-meter='password1']").attr("class");
1120  return $.inArray(passwordStrength, accpetedStrengths);
1121}
1122function readCookie(name) {
1123  var nameEQ = name + "=";
1124  var ca = document.cookie.split(";");
1125  for (var i = 0; i < ca.length; i++) {
1126    var c = ca[i];
1127    while (c.charAt(0) == " ") c = c.substring(1, c.length);
1128    if (c.indexOf(nameEQ) == 0) {
1129      return decodeURIComponent(c.substring(nameEQ.length, c.length));
1130    }
1131  }
1132  return null;
1133}
1134
1135function onBlurSelect(option) {
1136  window.open($("#code_" + option).data("url"), "_self");
1137}
1138
1139function handleSelect(element) {
1140  var isFirefox = navigator.userAgent.toLowerCase().indexOf("firefox") > -1;
1141  if ($("#code_" + element.value).is(":selected")) {
1142    if ($("#code_" + element.value).data("auto") === "auto") {
1143      if (isFirefox) {
1144        window.location = $("#code_" + element.value).data("url");
1145      } else {
1146        window.open($("#code_" + element.value).data("url"), "_self");
1147      }
1148    } else {
1149      window.location = $("#code_" + element.value).data("url");
1150    }
1151  }
1152}
1153function formGetParams() {
1154  $(".tplFilter form")
1155    .find(":input[type=text]")
1156    .filter(function () {
1157      if (this.value == "") {
1158        return true;
1159      }
1160    })
1161    .attr("disabled", "disabled");
1162  $(".tplFilter form")
1163    .find(":input[type=checkbox]")
1164    .filter(function () {
1165      if (this.checked == false) {
1166        return true;
1167      }
1168    })
1169    .attr("disabled", "disabled");
1170  $(".tplFilter form")
1171    .find("select")
1172    .filter(function () {
1173      if (this.value == -1) {
1174        return true;
1175      }
1176    })
1177    .attr("disabled", "disabled");
1178}
1179function startWidgetSliders() {
1180  if (isTablet) {
1181    $(".dinamic > .tplSliderBig .bxslider").css("display", "block");
1182    $(".dinamic > .tplSliderSmall .bxslider").css("display", "block");
1183  }
1184  var interval = parseInt(
1185    $(".dinamic > .tplSliderBig .bxslider").attr("data-interval")
1186  );
1187
1188  $(".dinamic > .tplSliderBig .bxslider").each(function () {
1189    var interval = $(this).data("interval");
1190    $(this).bxSlider({
1191      infiniteLoop: true,
1192      adaptiveHeight: true,
1193      hideControlOnEnd: true,
1194      preventDefaultSwipeX: true,
1195      auto: true,
1196      autoStart: true,
1197      pause: interval,
1198      nextText: "Següent",
1199      prevText: "Anterior",
1200      onSliderLoad: function () {
1201        $(".dinamic > .tplSliderBig .bxslider").css("display", "block");
1202      },
1203    });
1204  });
1205
1206  $(".dinamic > .tplSliderSmall .bxslider").bxSlider({
1207    infiniteLoop: false,
1208    adaptiveHeight: true,
1209    hideControlOnEnd: true,
1210    minSlides: 1,
1211    maxSlides: 7,
1212    slideWidth: 130,
1213    slideMargin: 0,
1214    preventDefaultSwipeY: true,
1215    nextText: "Següent",
1216    prevText: "Anterior",
1217    onSliderLoad: function () {
1218      $(".dinamic > .tplSliderSmall .bxslider").css("display", "block");
1219    },
1220  });
1221}
1222function equalizeHeights(parent, className) {
1223  $(parent).each(function () {
1224    var maximum = 0;
1225    $(this)
1226      .find(className)
1227      .each(function () {
1228        var value = parseFloat($(this).height());
1229        maximum = value > maximum ? value : maximum;
1230      });
1231    $(this).find(className).height(maximum);
1232  });
1233}
1234function resizeMasonry(clsGroup) {
1235  for (var clsI in clsGroup) {
1236    var cls = clsGroup[clsI];
1237    var clsCap = cls.charAt(0).toUpperCase() + cls.slice(1);
1238    if ($("." + cls).length) {
1239      $("." + cls).masonry({
1240        gutter: 10,
1241        stagger: 100,
1242        resize: false,
1243        horizontalOrder: true,
1244        percentPosition: false,
1245        itemSelector: ".tpl" + clsCap,
1246        columnWidth: ".tpl" + clsCap,
1247      });
1248    }
1249  }
1250}
1251function toggleRendiment() {
1252  $.ajax({
1253    cache: false,
1254    url: "/rendiment",
1255    complete: function () {
1256      location.reload();
1257    },
1258  });
1259}
1260function amagarBarra() {
1261  $(".topAlert").hide();
1262  document.cookie =
1263    "PHPSESSID=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
1264}
1265
1266/**
1267 * Fucionalitat pels modals de Imatges, Videos i PDF's per visor
1268 */
1269
1270// Imatge principal
1271function modalsImage() {
1272  // Get the modal Images
1273  // Get the image and insert it inside the modal - use its 'alt' text as a caption
1274  var img = $("#imageItem");
1275  img.on("click", function () {
1276    openGallery(0);
1277  });
1278}
1279
1280// Obrir modal per Id imatge
1281function openGallery(id) {
1282    id = String(id);
1283
1284    var $img;
1285    if (id === '0') {
1286        $img = $('#imgItem0');
1287        if (!$img || !$img.length) $img = $('#imageItem0').find('img').first();
1288    } else {
1289        $img = $('#imageGallery' + id);
1290    }
1291
1292    if (!$img || !$img.length) {
1293        console.warn('openGallery: imagen no encontrada para id', id);
1294        var $dl = $('#DownloadPrettyLink');
1295        if ($dl && $dl.length && $dl.attr('href')) {
1296            var srcDl = $dl.attr('href');
1297            $('#downloadImage').empty().append("<a id='DownloadPrettyLink' href='" + srcDl + "' download>Descarrega la imatge</a>");
1298            if ($('#imageCarousel0').length) $('#imageCarousel0').attr('src', srcDl);
1299            $('#ImageModal').modal('show');
1300            $('#closeModal').off('click.openGallery').on('click.openGallery', function () { $('#ImageModal').modal('hide'); });
1301        }
1302        return;
1303    }
1304
1305    // Leer atributos
1306    var src = $img.attr('src') || $img.attr('data-src') || $img.attr('data-action') || $img.attr('href') || '';
1307    var alt = $img.attr('alt') || '';
1308    var text = $img.attr('data-content') || $img.attr('data-title') || '';
1309
1310    // Actualizar UI
1311    $('#imageText').html(text || '');
1312    $('#downloadImage').empty().append("<a id='DownloadPrettyLink' href='" + src + "' download>Descarrega la imatge</a>");
1313
1314    // Mostrar modal
1315    $('#ImageModal').modal('show');
1316
1317    // Si hay carrusel, mover al slide que tenga la misma src
1318    var carouselEl = document.querySelector('#carouselControls');
1319    if (carouselEl) {
1320        var slides = carouselEl.querySelectorAll('.carousel-item img');
1321        var targetIndex = -1;
1322        for (var i = 0; i < slides.length; i++) {
1323            var slideSrc = slides[i].getAttribute('src') || '';
1324            if (slideSrc === src || (src && slideSrc && (slideSrc.endsWith(src) || src.endsWith(slideSrc)))) {
1325                targetIndex = i;
1326                break;
1327            }
1328        }
1329        var carousel = bootstrap.Carousel.getInstance(carouselEl) || new bootstrap.Carousel(carouselEl, { interval: false });
1330        if (targetIndex >= 0) {
1331            carousel.to(targetIndex);
1332            // Actualizar texto y enlace de descarga según el slide seleccionado
1333            try {
1334                var slideImg = slides[targetIndex];
1335                var newSrc = slideImg.getAttribute('src') || slideImg.getAttribute('data-src') || '';
1336                var newText = slideImg.getAttribute('data-title') || slideImg.getAttribute('data-content') || '';
1337                $('#imageText').html(newText);
1338                $('#downloadImage').empty().append("<a id='DownloadPrettyLink' href='" + newSrc + "' download>Descarrega la imatge</a>");
1339            } catch(e) { }
1340        } else {
1341            var activeImg = carouselEl.querySelector('.carousel-item.active img');
1342            if (activeImg) {
1343                activeImg.setAttribute('src', src);
1344                activeImg.setAttribute('alt', alt || '');
1345                $('#imageText').html(text || '');
1346                $('#downloadImage').empty().append("<a id='DownloadPrettyLink' href='" + src + "' download>Descarrega la imatge</a>");
1347            }
1348        }
1349    } else {
1350        if ($('#imageCarousel0').length) $('#imageCarousel0').attr('src', src).attr('alt', alt || '');
1351    }
1352
1353    // Evitar handlers duplicados
1354    $('#closeModal').off('click.openGallery').on('click.openGallery', function () { $('#ImageModal').modal('hide'); });
1355    // Actualizar texto y enlace cuando se cambia de slide dentro del modal
1356    $('#carouselControls').off('slide.bs.carousel.openGallery').on('slide.bs.carousel.openGallery', function (e) {
1357        var idSlide = e.to;
1358        var imgEl = document.querySelector('#imageGalleryModal' + idSlide) || document.querySelector('#photoImageGalleryModal' + idSlide) || document.querySelector('#imageGalleryModal' + idSlide);
1359        if (imgEl) {
1360            var title = imgEl.getAttribute('data-title') || imgEl.getAttribute('data-content') || '';
1361            var href = imgEl.getAttribute('src') || imgEl.getAttribute('data-src') || '';
1362            // No rellenar con filename ni con atributos del artículo — dejar en blanco si no hay título explícito
1363            $('#imageText').empty().append(title);
1364            $('#downloadImage').empty().append("<a id='DownloadPrettyLink' href='" + href + "' download>Descarrega la imatge</a>");
1365        }
1366    });
1367}
1368
1369
1370// Obrir modal per Id imatge
1371function openPhotoGallery(id) {
1372  var imgGallery =
1373    id === 0
1374      ? typeof $("#photoImageCarousel")[0] != "undefined"
1375        ? $("#photoImageCarousel")[0]
1376        : typeof $("#photoImageCarousel" + id)[0].src != "undefined"
1377        ? $("#photoImageCarousel" + id)[0]
1378        : $("#photoImageCarousel" + id)
1379      : typeof $("#photoImageCarousel" + id)[0].src != "undefined"
1380      ? $("#photoImageCarousel" + id)[0]
1381      : $("#photoImageCarousel" + id);
1382  var imgCarouselGallery = $("#photoImageCarousel" + id);
1383  var modalImgGallery = $("#photoImageModal");
1384  var sourceImage = $("#sourceImage");
1385  var close = $("#closeModalGallery");
1386  //var titleImg = $('.title-head');
1387  var download = $("#downloadImage");
1388  var imageText = $("#imageText");
1389  var $indicatorsGallery = $(".carousel-inner.gallery");
1390  if (id === 0) {
1391    imgCarouselGallery.attr("src", imgGallery.src);
1392  } else if (!imgCarouselGallery.hasOwnProperty("src")) {
1393    var imgCarousel = $("#photoImageCarousel0");
1394    imgCarouselGallery.attr("src", imgGallery.src);
1395  }
1396  $indicatorsGallery.find(".active").removeClass("active");
1397  sourceImage.attr("src", id === 0 ? imgGallery.src : imgGallery.src);
1398  download.empty();
1399  download.append(
1400    "<a id='DownloadPrettyLink' href='" +
1401      (id === 0 ? imgGallery.src : imgGallery.src) +
1402      "' download>Descarrega la imatge</a>"
1403  );
1404  imageText.empty();
1405  imageText.append(imgGallery.getAttribute("data-content"));
1406  //titleImg.append((id === 0) ? imgGallery.getAttribute('data-title') : imgGallery.getAttribute('data-title'));
1407  $("#imageText").empty();
1408  $("#imageText").append(imgGallery.getAttribute("alt"));
1409  imgCarouselGallery.attr("alt", imgGallery.getAttribute("alt"));
1410  $("#photoImageCarouselM" + id).addClass("active");
1411  modalImgGallery.modal("show");
1412
1413  close.on("click", function () {
1414    modalImgGallery.modal("hide");
1415  });
1416
1417  var myCarouselGallery = $("#carouselControls");
1418
1419 myCarouselGallery.on("slide.bs.carousel", function (e) {
1420    var id = e.to;
1421    var imgEl = document.querySelector('#imageGalleryModal' + id) || document.querySelector('#photoImageGalleryModal' + id);
1422    if (imgEl) {
1423        var title = imgEl.getAttribute('data-title') || imgEl.getAttribute('alt') || '';
1424        var href = imgEl.getAttribute('src') || imgEl.getAttribute('data-src') || '';
1425        $("#imageText").empty().append(title);
1426        $("#downloadImage").empty().append("<a id='DownloadPrettyLink' href='" + href + "' download>Descarrega la imatge</a>");
1427    }
1428  });
1429}
1430
1431function openVideo(id) {
1432  var video = $("#videoItem" + id);
1433  if (!video.length) return;
1434
1435  var type = (video.attr("data-type") || "").toUpperCase();
1436  var videoUrl = video.attr("data-src") || "";
1437  var videoTitle = video.attr("data-text") || "";
1438  var idVideo = video.attr("data-id") || "";
1439
1440  var modalVideo = $("#videoModal");
1441  var iframe = $("#iframeVideo");
1442  var title = $(".title-head");
1443  var titleVideo = $(".titleVideo");
1444  var tiktok = $(".tiktok-div-embed");
1445  var closeVideo = $("#closeModalVideo");
1446
1447  closeVideo.off("click").on("click", function (e) {
1448    e.preventDefault();
1449    modalVideo.modal("hide");
1450  });
1451
1452  modalVideo.off("hidden.bs.modal").on("hidden.bs.modal", function () {
1453    if (iframe.length) iframe.attr("src", "");
1454    if (tiktok.length) tiktok.empty().hide();
1455  });
1456
1457  if (title.length) title.empty();
1458  if (titleVideo.length) {
1459    titleVideo.empty();
1460    titleVideo.text(videoTitle);
1461  }
1462
1463  if (iframe.length) iframe.attr("src", "").hide();
1464  if (tiktok.length) tiktok.empty().hide();
1465
1466  modalVideo.modal("show");
1467
1468  if (type === "TIKTOK") {
1469    if (!idVideo) {
1470      if (tiktok.length) {
1471        tiktok.html('<a href="' + videoUrl + '" target="_blank" rel="noopener">Ver vídeo</a>').show();
1472      }
1473      return;
1474    }
1475    $.ajax({
1476      cache: false,
1477      type: "POST",
1478      url: "/requestvideo",
1479      data: { id: idVideo },
1480      success: function (result) {
1481        if (tiktok.length) {
1482          tiktok.empty();
1483          if (result && String(result).trim().length) {
1484            tiktok.html(result);
1485          }
1486          tiktok.show();
1487        }
1488      }
1489    });
1490  } else {
1491    if (iframe.length) iframe.attr("src", videoUrl).show();
1492  }
1493}
1494
1495function stopVideo(iframe, video) {
1496  iframe.attr("src", "");
1497  iframe.hide();
1498}
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534/**
1535 * Bloquea iframes "raw" (pegados en HTML) según KlaroConfig:
1536 * - Si el iframe pertenece a un servicio conocido por Klaro -> se gestiona por consentimiento.
1537 * - Si pertenece a un dominio no registrado (no existe servicio Klaro) -> se bloquea al 100%.
1538 *
1539 * Requiere:
1540 * - window.klaroConfig.services (array)
1541 * - window.klaro.getManager() (para lectura/escritura de consentimiento)
1542 */
1543var __consentSnapshotLast = null;
1544var __consentSnapshotTimer = null;
1545function openPdf(value) {
1546  var pdfItem = $("#pdfItem" + value);
1547  var iframe = $("#iframePdf");
1548  var modalPdf = $("#pdfModal");
1549  var title = $(".title-head");
1550  var titlePdf = $(".titlePdf");
1551  var closePdf = $("#closeModalPDF");
1552
1553  title.empty();
1554  iframe.attr("src", pdfItem.attr("data-action"));
1555  titlePdf.empty();
1556  titlePdf.append(pdfItem.attr("title"));
1557  modalPdf.modal("show");
1558
1559  closePdf.on("click", function () {
1560    modalPdf.modal("hide");
1561  });
1562}
1563
1564function modalsPdf() {
1565  // Get the modal Pdf
1566  var pdfItem = $("#pdfItem");
1567  var iframe = $("#iframePdf");
1568  var modalPdf = $("#pdfModal");
1569  var title = $(".title-head");
1570  var titlePdf = $(".titlePdf");
1571  var closePdf = $("#closeModalPDF");
1572
1573  pdfItem.on("click", function () {
1574    title.empty();
1575    iframe.attr("src", pdfItem.attr("data-action"));
1576    titlePdf.empty();
1577    titlePdf.append(this.title);
1578    modalPdf.modal("show");
1579  });
1580
1581  closePdf.on("click", function () {
1582    modalPdf.modal("hide");
1583  });
1584}
1585
1586function toSlideImage(event) {
1587  var to = event.to;
1588  var download = $("#downloadImage");
1589  var imgGallery = $("#imageGalleryModal" + to);
1590
1591  download.empty();
1592  download.append(
1593    "<a id='DownloadPrettyLink' href='" +
1594      imgGallery.attr("src") +
1595      "' download>Descarrega la imatge</a>"
1596  );
1597}
1598
1599/**
1600 *  Funcionalitat de filtes a Hemeroteca
1601 *  Data Dev : 27/08/2021
1602 */
1603
1604function filterCategories(
1605  categoriesArray,
1606  selectedType = 0,
1607  selectedCategory = 0
1608) {
1609  var comboCategory = $("#archive_category");
1610  var labelCategory = $("#label_archive_category");
1611  labelCategory.hide();
1612  comboCategory.hide();
1613  if (selectedType !== 0) {
1614    var val = selectedType;
1615
1616    if (categoriesArray[val].length > 0) {
1617      comboCategory.empty();
1618      comboCategory.append(
1619        $("<option></option>").val("").html("Tot")
1620      );
1621    }
1622    $.each(categoriesArray[val], function (key, value) {
1623      comboCategory.append(
1624        $("<option></option>").val(value.category).html(value.name)
1625      );
1626      if (selectedCategory === value.category) {
1627        comboCategory.val(value.category);
1628      }
1629    });
1630
1631    if (categoriesArray[val].length > 0) {
1632      labelCategory.show();
1633      comboCategory.show();
1634    } else {
1635      labelCategory.hide();
1636      comboCategory.hide();
1637    }
1638  }
1639
1640  $("#archive_type").on("change", function (key, value) {
1641    var val = $("#archive_type").val();
1642    if (categoriesArray[val].length > 0) {
1643      comboCategory.empty();
1644      comboCategory.append(
1645        $("<option></option>").val("").html("Tot")
1646      );
1647    }
1648    $.each(categoriesArray[val], function (key, value) {
1649      comboCategory.append(
1650        $("<option></option>").val(value.category).html(value.name)
1651      );
1652      if (selectedCategory === value.category) {
1653        comboCategory.val(value.category);
1654      }
1655    });
1656
1657    if (categoriesArray[val].length > 0) {
1658      labelCategory.show();
1659      comboCategory.show();
1660    } else {
1661      labelCategory.hide();
1662      comboCategory.hide();
1663    }
1664  });
1665}
1666
1667function equalHeightIconTime() {
1668  //$('.iconTime').each(function() {
1669  //    var maxHeight = 0;
1670  //    $(this).find('.tplIconTime').height('auto');
1671  //    $(this).find('.tplIconTime').each(function (index) {
1672  //        if ($(this).height() > maxHeight)
1673  //            maxHeight = $(this).height();
1674  //    });
1675  //    $(this).find('.tplIconTime').height(maxHeight);
1676  //});
1677}
1678
1679function equalHeightWidgetContainerRow() {
1680  $(".o-widget-container.row").each(function () {
1681    var maxHeight = 0;
1682    $(this).find(".o-widget-wrapper").height("auto");
1683    $(this)
1684      .find(".o-widget-wrapper")
1685      .each(function (index) {
1686        if ($(this).height() > maxHeight) maxHeight = $(this).height();
1687      });
1688    $(this).find(".backgroundColor-BX").height(maxHeight);
1689  });
1690}
1691
1692// datepicker inicialització
1693function datepickerInit() {
1694  !(function (a) {
1695    a.fn.datepicker.dates.ca = {
1696      days: [
1697        "Diumenge",
1698        "Dilluns",
1699        "Dimarts",
1700        "Dimecres",
1701        "Dijous",
1702        "Divendres",
1703        "Dissabte",
1704      ],
1705      daysShort: ["Diu", "Dil", "Dmt", "Dmc", "Dij", "Div", "Dis"],
1706      daysMin: ["dg", "dl", "dt", "dc", "dj", "dv", "ds"],
1707      months: [
1708        "Gener",
1709        "Febrer",
1710        "Març",
1711        "Abril",
1712        "Maig",
1713        "Juny",
1714        "Juliol",
1715        "Agost",
1716        "Setembre",
1717        "Octubre",
1718        "Novembre",
1719        "Desembre",
1720      ],
1721      monthsShort: [
1722        "Gen",
1723        "Feb",
1724        "Mar",
1725        "Abr",
1726        "Mai",
1727        "Jun",
1728        "Jul",
1729        "Ago",
1730        "Set",
1731        "Oct",
1732        "Nov",
1733        "Des",
1734      ],
1735      today: "Avui",
1736      monthsTitle: "Mesos",
1737      clear: "Esborrar",
1738      weekStart: 1,
1739      format: "dd-mm-yyyy",
1740    };
1741  })(jQuery);
1742
1743  $.fn.datepicker.defaults.format = "dd-mm-yyyy";
1744  $.fn.datepicker.defaults.autoclose = true;
1745  $.fn.datepicker.defaults.language = "ca";
1746  $(function () {
1747    $(".datepicker").datepicker();
1748  });
1749
1750  $(".del-ini").on("click", function () {
1751    $(".inputdateini").datepicker("setDate", null);
1752  });
1753  $(".del-fi").on("click", function () {
1754    $(".inputdatefi").datepicker("setDate", null);
1755  });
1756}
1757
1758function toSlideImage(event) {
1759  var to = event.to;
1760  var download = $("#downloadImage");
1761  var imgGallery = $("#imageGalleryModal" + to);
1762  var imageText = $("#imageText");
1763  download.empty();
1764  download.append(
1765    "<a id='DownloadPrettyLink' href='" +
1766      imgGallery.attr("src") +
1767      "' download>Descarrega la imatge</a>"
1768  );
1769  imageText.empty();
1770  imageText.append(imgGallery[0].getAttribute("data-title"));
1771}
1772
1773function carouselControlSmall() {
1774  $(".carousel-item.small").each(function () {
1775    var next = $(this).next();
1776    if (!next.length) {
1777      next = $(this).siblings(":first");
1778    }
1779  });
1780
1781  $(".carousel-control-prev.w-auto").on("click", function () {
1782    var content = parseInt(this.getAttribute("data-content"));
1783    var itemActiu = $(".carousel-item.content-" + content + ".small.active");
1784    var items = $(".carousel-item.content-" + content + ".small");
1785    var total = parseInt(this.getAttribute("data-end"));
1786    var posicioActual = parseInt(itemActiu.attr("data-id")) - 1;
1787    var posicioNova = 1;
1788    if (posicioActual < 0) {
1789      posicioNova = total;
1790    } else if (posicioActual >= 0) {
1791      posicioNova = posicioActual;
1792    }
1793    itemActiu.removeClass("active");
1794    items[posicioNova].classList.add("active");
1795  });
1796  $(".carousel-control-next.w-auto").on("click", function () {
1797    var content = parseInt(this.getAttribute("data-content"));
1798    var itemActiu = $(".carousel-item.content-" + content + ".small.active");
1799    var items = $(".carousel-item.content-" + content + ".small");
1800    var total = parseInt(this.getAttribute("data-end"));
1801    var posicioActual = parseInt(itemActiu.attr("data-id")) + 1;
1802    var posicioNova = 1;
1803    if (posicioActual > total) {
1804      posicioNova = 0;
1805    } else if (posicioActual <= total) {
1806      posicioNova = posicioActual;
1807    }
1808    itemActiu.removeClass("active");
1809    items[posicioNova].classList.add("active");
1810  });
1811
1812  $(".carousel-control-prev-mobile.w-auto").on("click", function () {
1813    var content = parseInt(this.getAttribute("data-content"));
1814    var itemMobileActiu = $(
1815      ".carousel-item.content-mobile-" + content + ".small.active"
1816    );
1817    var itemsMobile = $(".carousel-item.content-mobile-" + content + ".small");
1818    var total = parseInt(this.getAttribute("data-end"));
1819    var posicioMobileActual = parseInt(itemMobileActiu.attr("data-id")) - 1;
1820    var posicioNova = 1;
1821    if (posicioMobileActual < 0) {
1822      posicioNova = total;
1823    } else if (posicioMobileActual >= 0) {
1824      posicioNova = posicioMobileActual;
1825    }
1826    itemMobileActiu.removeClass("active");
1827    itemsMobile[posicioNova].classList.add("active");
1828  });
1829  $(".carousel-control-next-mobile.w-auto").on("click", function () {
1830    var content = parseInt(this.getAttribute("data-content"));
1831    var itemMobileActiu = $(
1832      ".carousel-item.content-mobile-" + content + ".small.active"
1833    );
1834    var itemsMobile = $(".carousel-item.content-mobile-" + content + ".small");
1835    var total = parseInt(this.getAttribute("data-end"));
1836    var posicioMobileActual = parseInt(itemMobileActiu.attr("data-id")) + 1;
1837    var posicioMobileNova = 1;
1838    if (posicioMobileActual > total) {
1839      posicioMobileNova = 0;
1840    } else if (posicioMobileActual <= total) {
1841      posicioMobileNova = posicioMobileActual;
1842    }
1843    itemMobileActiu.removeClass("active");
1844    itemsMobile[posicioMobileNova].classList.add("active");
1845  });
1846}
1847function getCookie(cname) {
1848  var name = cname + "=";
1849  var ca = document.cookie.split(";");
1850  for (var i = 0; i < ca.length; i++) {
1851    var c = ca[i];
1852    while (c.charAt(0) == " ") c = c.substring(1);
1853    if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
1854  }
1855  return "";
1856}
1857
1858// translate
1859function translateWeb() {
1860  var link = $(".link-language");
1861
1862  link.on("click", function (value) {
1863    window.location = value.currentTarget.getAttribute("data-target");
1864  });
1865}
1866
1867function playCarousel(id) {
1868  var carousel = "#carousel" + id + ".carousel";
1869  $("#carouselPause" + id).addClass("none");
1870  $("#carouselPlay" + id).removeClass("none");
1871  initCarousel(id, $(carousel).attr("data-bs-interval"));
1872}
1873
1874function pauseCarousel(id) {
1875  var carousel = "#carousel" + id + ".carousel";
1876  $("#carouselPlay" + id).addClass("none");
1877  $("#carouselPause" + id).removeClass("none");
1878  $(carousel).carousel("pause");
1879}
1880
1881function initCarousel(id, interval) {
1882  var carousel = "#carousel" + id + ".carousel";
1883  $(carousel).carousel({
1884    interval: parseInt(interval),
1885    cycle: true,
1886  });
1887}
1888
1889function addAttributesDivVcards() {
1890  var divVcards = $(".articlelist.vcards");
1891  var divVcards2 = $(".articlelist.vcards2");
1892}
1893
1894function removeEmptyParameters() {
1895  // Select all input fields in the form with a name attribute
1896  const inputs = document.querySelectorAll("input,select,textarea");
1897
1898  inputs.forEach((input) => {
1899    // If the field is empty, remove the name attribute (so it won't be sent)
1900    if (!input.classList.contains("datepicker")) {
1901      if (input.value.trim() === "" || input.value === "0") {
1902        input.removeAttribute("name");
1903      }
1904    }
1905  });
1906}
1907
1908

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.