PageSourceSearch

https://lojahusqvarna.pt/src/themes/picostrap5-child-base/js/analytics.js?ver=3.1.0.1787732140

js lojahusqvarna.pt collected 2026-10-04 13:28:03 UTC 46,678 bytes, 1,532 lines download raw bytes

1//user.lastPurchase
2//user.userId
3//user.lastLogin
4//user.firstLogin
5if (typeof breadcrumb !== "undefined") {
6  let breadcrumb = {
7    value: undefined,
8  };
9}
10if (typeof user !== "undefined") {
11  let user = {
12    userId: undefined,
13    lastLogin: undefined,
14    firstLogin: undefined,
15    lastPurchase: undefined,
16  };
17}
18/*
19 * ------------------------------------------------
20 * Evento envio de newsletter
21 * ------------------------------------------------
22 */
23
24const form = document.getElementById("gform_1");
25if (form) {
26  form.addEventListener("submit", gtag_report_conversion_newsletter);
27}
28function gtag_report_conversion_newsletter() {
29  var callback = function () {
30    if (typeof url != "undefined") {
31      window.location = url;
32    }
33  };
34  gtag("event", "conversion", {
35    send_to: "AW-691985440/bOKACNnJzPkBEKC4-8kC",
36    event_callback: callback,
37  });
38  if (document.documentElement.lang !== "pt-PT") {
39    pintrk("track", "lead", {
40      lead_type: "Newsletter",
41    });
42  }
43  return false;
44}
45/*
46 * ------------------------------------------------
47 * Selectores de datos
48 * ------------------------------------------------
49 */
50//Seleccinamos los datos de un producto en base a su id
51function getProductDataById(itemKey, type = "analytic-product") {
52  let products = document.querySelectorAll(
53    "[data-" + type + '-id="' + itemKey + '"]',
54  );
55  if (products.length < 1) {
56    return;
57  }
58  let product = products[0];
59  if (type === "analytic-product") {
60    return {
61      name: product.dataset.analyticProductName,
62      id: product.dataset.analyticProductId,
63      price: product.dataset.analyticProductPrice,
64      category: product.dataset.analyticProductCategory,
65      variant: product.dataset.analyticProductCategories,
66      quantity: product.dataset.analyticProductQuantity,
67      position: product.dataset.analyticProductPosition,
68      list: undefined,
69    };
70  } else {
71    return {
72      name: product.dataset.analyticCartProductName,
73      id: product.dataset.analyticCartProductId,
74      price: product.dataset.analyticCartProductPrice,
75      category: product.dataset.analyticCartProductCategory,
76      variant: product.dataset.analyticCartProductCategories,
77      quantity: product.dataset.analyticCartProductQuantity,
78      position: product.dataset.analyticCartProductPosition,
79      list: undefined,
80    };
81  }
82}
83
84//Convertimos los datos de producto que provienen del checkout a un producto a enviar a analytics. Solo se utiliza en el checkout
85function getProductData(product) {
86  return {
87    name: product.name,
88    id: product.id,
89    price: product.price,
90    category: product.category,
91    variant: product.categories,
92    quantity: product.quantity,
93    list: undefined,
94    position: undefined,
95  };
96}
97
98function getListHomeProductByList(list) {
99  let products = [];
100  let listProducts = document.querySelectorAll(".slick-active .ficha-producto");
101  if (listProducts) {
102    for (var i = 0; i < listProducts.length; i++) {
103      var product = getProductDataById(
104        listProducts[i].dataset.analyticProductId,
105      );
106      if (product) {
107        product.list = "home - " + list;
108        products.push(product);
109      }
110    }
111  }
112  return products;
113}
114
115/*
116 * ------------------------------------------------
117 * Enventos para analytics
118 * ------------------------------------------------
119 */
120
121/*
122 * Se lanza cuando carga la home
123 */
124function eventLoadHome() {
125  let ofertas = getListHomeProductByList("#ofertas");
126  let motosierras = getListHomeProductByList("motosierras");
127  let cortacespedes = getListHomeProductByList("cortacéspedes");
128  let desbrozadoras = getListHomeProductByList("desbrozadoras");
129  var event = {
130    event: "eventoEC",
131    eventCat: "ecommerce",
132    eventAct: "productImpresion",
133    eventLbl: "home",
134    noInteraction: "true",
135    ecommerce: {
136      currencyCode: "EUR",
137      impressions: [
138        ...ofertas,
139        ...motosierras,
140        ...cortacespedes,
141        ...desbrozadoras,
142      ],
143    },
144  };
145  window.dataLayer.push(event);
146}
147
148/*
149 * Se lanza cuando carga un pagina de un product
150 */
151function eventLoadProductPage() {
152  if (typeof product !== "undefined") {
153    let event = {
154      event: "eventoEC",
155      eventCat: "ecommerce",
156      eventAct: "detail",
157      eventLbl: product.name,
158      noInteraction: true,
159      ecommerce: {
160        currencyCode: "EUR",
161        detail: {
162          actionField: { list: breadcrumb.value },
163          products: [
164            {
165              name: product.name,
166              id: product.id,
167              price: product.price,
168              brand: "Husqvarna",
169              category: product.category,
170              variant: product.categories,
171            },
172          ],
173        },
174      },
175    };
176    window.dataLayer.push(event);
177    if (document.documentElement.lang !== "pt-PT") {
178      if (typeof fbq !== "undefined") {
179        fbq("track", "ViewContent", {
180          value: product.price,
181          currency: "EUR",
182          content_ids: product.id,
183          content_type: product.category,
184        });
185      }
186    }
187  }
188}
189
190/*
191 * Se lanza cuando carga una categoria de productos
192 */
193function eventLoadCategoryPage(config) {
194  let listProducts = document.getElementsByClassName("ficha-producto");
195  let products = [];
196  let list = "";
197  if (listProducts) {
198    if (config.order) {
199      list += "Ordenar " + config.order;
200    }
201    if (config.price) {
202      list += " Filtro precio ";
203    }
204    if (config.search) {
205      list += "Busqueda interna " + config.search + " ";
206    }
207    if (config.categories.length > 0) {
208      list += config.categories.join(" - ");
209    } else {
210      list += breadcrumb.value;
211    }
212
213    for (var i = 0; i < listProducts.length; i++) {
214      var product = getProductDataById(
215        listProducts[i].dataset.analyticProductId,
216      );
217      if (product) {
218        product.list = list;
219        products.push(product);
220      }
221    }
222  }
223
224  let event = {
225    event: "eventoEC",
226    eventCat: "ecommerce",
227    eventAct: "productImpresion",
228    eventLbl: breadcrumb.value,
229    noInteraction: "true",
230    ecommerce: {
231      currencyCode: "EUR",
232      impressions: products,
233    },
234  };
235  window.dataLayer.push(event);
236
237  if (config.search && document.documentElement.lang !== "pt-PT") {
238    if (typeof fbq !== "undefined") {
239      fbq("track", "Search");
240    }
241  }
242  if (config.search) {
243    var callback = function () {
244      ("gtag buscador");
245      if (typeof url != "undefined") {
246        window.location = url;
247      }
248    };
249    gtag("event", "conversion", {
250      send_to: "AW-691985440/FTs3CJ3GzPkBEKC4-8kC",
251      event_callback: callback,
252    });
253  }
254  ("eventLoadCategoryPage", event);
255}
256
257/*
258 * Se lanza cuando carga la pagina de finalizar compra
259 */
260function eventLoadCheckoutPage() {
261  let productsList = [];
262  if (typeof products !== "undefined") {
263    for (var i = 0; i < products.length; i++) {
264      productsList.push(getProductData(products[i]));
265    }
266    let event = {
267      event: "eventoEC",
268      eventCat: "ecommerce",
269      eventAct: "checkout-2",
270      eventLbl: "datos de facturacion",
271      noInteraction: "true",
272      ecommerce: {
273        currencyCode: "EUR",
274        checkout: {
275          actionField: { step: 2 },
276          products: productsList,
277        },
278      },
279    };
280    ("eventLoadCheckoutPage", event);
281    window.dataLayer.push(event);
282  }
283}
284
285/*
286 * Se lanza cuando se hace click en un producto para visualizarlo
287 */
288function eventClickProduct(product, position) {
289  let event = {
290    event: "eventoEC",
291    eventCat: "ecommerce",
292    eventAct: "productClick",
293    eventLbl: breadcrumb.value,
294    ecommerce: {
295      click: {
296        actionField: {
297          list: breadcrumb.value,
298        },
299        products: [
300          {
301            name: product.name,
302            id: product.id,
303            price: product.price,
304            brand: "Husqvarna",
305            category: product.category,
306            variant: product.categories,
307            list: breadcrumb.value,
308            position: position,
309          },
310        ],
311      },
312    },
313  };
314  ("eventClickProduct", event);
315  window.dataLayer.push(event);
316}
317
318/*
319 * Se lanza cuando carga se hace click en el boton de añadir a carrito
320 */
321function eventClickAddCart(product, position, quantity, dimension6) {
322  let event = {
323    event: "eventoEC",
324    eventCat: "ecommerce",
325    eventAct: "addToCart",
326    eventLbl: product.name,
327    ecommerce: {
328      currencyCode: "EUR",
329      add: {
330        products: [
331          {
332            name: product.name,
333            id: product.id,
334            price: product.price,
335            brand: "Husqvarna",
336            category: product.category,
337            variant: product.categories,
338            dimension6: dimension6,
339            quantity: quantity,
340            list: breadcrumb.value,
341            position: product.position ? product.position : position,
342          },
343        ],
344      },
345    },
346  };
347  if (document.documentElement.lang !== "pt-PT") {
348    pintrk("track", "addtocart", {
349      value: product.price,
350      order_quantity: quantity,
351      currency: "USD",
352    });
353    if (typeof fbq !== "undefined") {
354      fbq("track", "AddToCart", {
355        value: product.price,
356        currency: "EUR",
357        contents: [
358          {
359            id: product.id,
360            quantity: quantity,
361          },
362        ],
363        content_ids: product.id,
364      });
365    }
366  }
367  window._adftrack = Array.isArray(window._adftrack)
368    ? window._adftrack
369    : window._adftrack
370      ? [window._adftrack]
371      : [];
372  window._adftrack.push({
373    HttpHost: "track.adform.net",
374    pm: 2316232,
375    divider: encodeURIComponent("|"),
376    pagename: encodeURIComponent("Añadir al carro"),
377    order: {
378      sales: product.price,
379      orderid: product.id,
380      itms: [
381        {
382          categoryname: product.category,
383          productname: product.name,
384          productid: product.id,
385          productcount: quantity,
386          productsales: product.price,
387        },
388      ],
389    },
390  });
391  (function () {
392    var s = document.createElement("script");
393    s.type = "text/javascript";
394    s.async = true;
395    s.src = "https://s2.adform.net/banners/scripts/st/trackpoint-async.js";
396    var x = document.getElementsByTagName("script")[0];
397    x.parentNode.insertBefore(s, x);
398  })();
399  ("eventClickAddCart", event);
400  window.dataLayer.push(event);
401  var callbackAdd = function () {
402    ("gtag add to cart");
403    if (typeof url != "undefined") {
404      window.location = url;
405    }
406  };
407  gtag("event", "conversion", {
408    send_to: "AW-691985440/m_TWCNiQ7_kBEKC4-8kC",
409    event_callback: callbackAdd,
410  });
411
412  return false;
413}
414
415/*
416 * Se lanza cuando se elimina un producto del mini cart
417 */
418function eventClickRemoveCart(product, position, quantity, dimension6) {
419  let event = {
420    event: "eventoEC",
421    eventCat: "ecommerce",
422    eventAct: "removeFromCart",
423    eventLbl: product.name,
424    ecommerce: {
425      currencyCode: "EUR",
426      remove: {
427        products: [
428          {
429            name: product.name,
430            id: product.id,
431            price: product.price,
432            brand: "Husqvarna",
433            category: product.category,
434            variant: product.categories,
435            dimension6: dimension6,
436            quantity: quantity,
437            list: breadcrumb.value,
438          },
439        ],
440      },
441    },
442  };
443  ("eventClickRemoveCart", event);
444  window.dataLayer.push(event);
445}
446
447/*
448 * Se lanza cuando carga el mini cart
449 */
450function eventLoadMiniCartPage() {
451  let listProducts = document.getElementsByClassName("mini-cart-item");
452
453  let products = [];
454  let list = breadcrumb.value;
455  if (listProducts) {
456    for (var i = 0; i < listProducts.length; i++) {
457      var product = getProductDataById(
458        listProducts[i].dataset.analyticProductId,
459      );
460      if (product) {
461        product.list = list;
462        products.push(product);
463      }
464    }
465  }
466
467  let event = {
468    event: "eventoEC",
469    eventCat: "ecommerce",
470    eventAct: "checkout-1",
471    eventLbl: "carrito",
472    noInteraction: "true",
473    ecommerce: {
474      currencyCode: "EUR",
475      checkout: {
476        actionField: { step: 1 },
477        products: products,
478      },
479    },
480  };
481  ("eventLoadMiniCartPage", event);
482  window.dataLayer.push(event);
483}
484
485/*
486 * Se lanza cuando un usuacion hacer click sobre logout
487 */
488function gtag_report_conversion_logout(url) {
489  var callback = function () {
490    ("gtag logout");
491    if (typeof url != "undefined") {
492      window.location = url;
493    }
494  };
495  gtag("event", "conversion", {
496    send_to: "AW-691985440/FMImCPrYzPkBEKC4-8kC",
497    event_callback: callback,
498  });
499  return false;
500}
501function eventLogoutUser() {
502  let event = {
503    event: "evento",
504    eventCat: "privateArea",
505    eventAct: "logout",
506    eventLbl: "ok",
507    userId: user.userId,
508    lastLogin: user.lastLogin,
509    firstLogin: user.firstLogin,
510    lastPurchase: user.lastPurchase,
511  };
512  if (document.documentElement.lang !== "pt-PT") {
513    if (typeof fbq !== "undefined") {
514      fbq("track", "SubmitApplication");
515    }
516  }
517  ("eventLogoutUser", event);
518  window.dataLayer.push(event);
519  gtag_report_conversion_logout();
520}
521
522/*
523 * Se lanza cuando un usuario hace login
524 */
525function eventLogintUser(user) {
526  let event = {
527    event: "evento",
528    eventCat: "privateArea",
529    eventAct: "login",
530    eventLbl: "ok",
531    userId: user.userId,
532    lastLogin: user.lastLogin,
533    firstLogin: user.firstLogin,
534    lastPurchase: user.lastPurchase,
535  };
536  ("eventLogintUser", event);
537  window.dataLayer.push(event);
538}
539
540/*
541 * Se lanza cuando un usuario se registra
542 */
543//GTag event
544function gtag_report_conversion_register(url) {
545  ("event", "gtag_report_conversion");
546  var callback = function () {
547    if (typeof url != "undefined") {
548      window.location = url;
549    }
550  };
551  gtag("event", "conversion", {
552    send_to: "AW-691985440/E-kSCJCe4_kBEKC4-8kC",
553    event_callback: callback,
554  });
555  return false;
556}
557// function eventRegisterUser() { ... } // comentado intencionalmente en PT
558
559/*
560 *----------------------------------------------------------------------
561 *  Funciones que recorren el DOM para localizar clases a las que asignar los eventos
562 *----------------------------------------------------------------------
563 */
564function loopProductSheet() {
565  let productSheet = document.getElementsByClassName("ficha-producto");
566  if (productSheet && productSheet.length > 0) {
567    let clickProduct = function (event) {
568      if (this.dataset.analyticProductId) {
569        let position = 1;
570        if (this.parentElement.parentElement.dataset.slickIndex) {
571          position =
572            parseInt(this.parentElement.parentElement.dataset.slickIndex) + 1;
573        } else if (this.dataset.slickIndex) {
574          position = this.dataset.slickIndex;
575        }
576        eventClickProduct(
577          getProductDataById(this.dataset.analyticProductId),
578          position,
579        );
580      }
581    };
582    for (let i = 0; i < productSheet.length; i++) {
583      productSheet[i].addEventListener("click", clickProduct, false);
584    }
585  }
586}
587
588function loopUserLogout() {
589  let logoutClick = document.getElementsByClassName(
590    "woocommerce-MyAccount-navigation-link--customer-logout",
591  );
592  if (logoutClick && logoutClick.length > 0) {
593    let addLogoutClick = function (event) {
594      eventLogoutUser();
595    };
596    for (var i = 0; i < logoutClick.length; i++) {
597      logoutClick[i].addEventListener("click", addLogoutClick, false);
598    }
599  }
600}
601
602function loopOpenCart() {
603  var clickShowMiniCart = document.getElementsByClassName(
604    "desplegable-desplegar",
605  );
606  if (clickShowMiniCart && clickShowMiniCart.length > 0) {
607    let clickMiniCart = function (event) {
608      eventLoadMiniCartPage();
609    };
610
611    for (var i = 0; i < clickShowMiniCart.length; i++) {
612      if (clickShowMiniCart[i].dataset.obj === "#mini-cart") {
613        clickShowMiniCart[i].addEventListener("click", clickMiniCart, false);
614      }
615    }
616  }
617}
618
619jQuery(document).ready(function () {
620  if (page.name === "home") {
621    eventLoadHome();
622  }
623  if (
624    document.body.classList.contains("single-product") ||
625    page.name === "product"
626  ) {
627    eventLoadProductPage();
628  }
629  if (page.name === "checkout") {
630    eventLoadCheckoutPage();
631  }
632
633  if (
634    window.location.search.substr(1) === "new-register" &&
635    page.name === "my-account"
636  ) {
637    // eventRegisterUser(); // comentado intencionalmente en PT
638  }
639
640  loopProductSheet();
641  loopUserLogout();
642  loopOpenCart();
643
644  /* Init event products order */
645  var $orderElement = jQuery(".woocommerce-ordering select");
646  if ($orderElement.length) {
647    var stringToAnalyticsOrder = {
648      popularity: "popularidad",
649      date: "útlimos",
650      price: "precio bajo a precio alto",
651      "price-desc": "precio alto a precio bajo",
652    };
653    $orderElement.on("change", function () {
654      var valueOrder = jQuery(this).val();
655      if (valueOrder && stringToAnalyticsOrder.hasOwnProperty(valueOrder)) {
656        var eventOrder = {
657          event: "evento",
658          eventCat: "filtro",
659          eventAct: "ordenar",
660          eventLbl: stringToAnalyticsOrder[valueOrder],
661        };
662        ("eventOrder", eventOrder);
663        window.dataLayer.push(eventOrder);
664      }
665    });
666  }
667  /* / event products order */
668
669  /**
670   * Escucha el evento que carga los productos
671   */
672  jQuery(document).on("facetwp-loaded", function () {
673    let config = {
674      price: false,
675      order: false,
676      search: false,
677      categories: [],
678    };
679    let categories = [];
680    if (FWP.facets.categora_hidrolimpiadoras) {
681      FWP.facets.categora_hidrolimpiadoras.forEach((element) =>
682        categories.push(element),
683      );
684    }
685    if (FWP.facets.categora_soplanieves) {
686      FWP.facets.categora_soplanieves.forEach((element) =>
687        categories.push(element),
688      );
689    }
690    if (FWP.facets.categoria_aceites_y_gasolinas) {
691      FWP.facets.categoria_aceites_y_gasolinas.forEach((element) =>
692        categories.push(element),
693      );
694    }
695    if (FWP.facets.categoria_automower) {
696      FWP.facets.categoria_automower.forEach((element) =>
697        categories.push(element),
698      );
699    }
700    if (FWP.facets.categoria_aspiradoras) {
701      FWP.facets.categoria_aspiradoras.forEach((element) =>
702        categories.push(element),
703      );
704    }
705    if (FWP.facets.categoria_cortacespedes) {
706      FWP.facets.categoria_cortacespedes.forEach((element) =>
707        categories.push(element),
708      );
709    }
710    if (FWP.facets.categoria_cortasetos) {
711      FWP.facets.categoria_cortasetos.forEach((element) =>
712        categories.push(element),
713      );
714    }
715    if (FWP.facets.categoria_desbrozadoras) {
716      FWP.facets.categoria_desbrozadoras.forEach((element) =>
717        categories.push(element),
718      );
719    }
720    if (FWP.facets.categoria_escarificadores_cesped) {
721      FWP.facets.categoria_escarificadores_cesped.forEach((element) =>
722        categories.push(element),
723      );
724    }
725    if (FWP.facets.categoria_herramientas_forestales) {
726      FWP.facets.categoria_herramientas_forestales.forEach((element) =>
727        categories.push(element),
728      );
729    }
730    if (FWP.facets.categoria_juguetes) {
731      FWP.facets.categoria_juguetes.forEach((element) =>
732        categories.push(element),
733      );
734    }
735    if (FWP.facets.categoria_merchandising) {
736      FWP.facets.categoria_merchandising.forEach((element) =>
737        categories.push(element),
738      );
739    }
740    if (FWP.facets.categoria_motoazada) {
741      FWP.facets.categoria_motoazada.forEach((element) =>
742        categories.push(element),
743      );
744    }
745    if (FWP.facets.categoria_motosierras) {
746      FWP.facets.categoria_motosierras.forEach((element) =>
747        categories.push(element),
748      );
749    }
750    if (FWP.facets.categoria_ropa) {
751      FWP.facets.categoria_ropa.forEach((element) => categories.push(element));
752    }
753    if (FWP.facets.categoria_sopladores) {
754      FWP.facets.categoria_sopladores.forEach((element) =>
755        categories.push(element),
756      );
757    }
758    config.categories = categories;
759    if (FWP.facets.price_range.length > 0) {
760      config.price = FWP.facets.price_range;
761    }
762
763    if (FWP.facets.buscador_productos !== "") {
764      config.search = FWP.facets.buscador_productos;
765    }
766    if (FWP_HTTP.get.orderby) {
767      config.order = FWP_HTTP.get.orderby;
768    }
769    eventLoadCategoryPage(config);
770  });
771  jQuery(document).on("facetwp-refresh", function () {
772    let config = {
773      price: false,
774      order: false,
775      search: false,
776      categories: [],
777    };
778    let categories = [];
779    if (FWP.facets.categora_hidrolimpiadoras) {
780      FWP.facets.categora_hidrolimpiadoras.forEach((element) =>
781        categories.push(element),
782      );
783    }
784    if (FWP.facets.categora_soplanieves) {
785      FWP.facets.categora_soplanieves.forEach((element) =>
786        categories.push(element),
787      );
788    }
789    if (FWP.facets.categoria_aceites_y_gasolinas) {
790      FWP.facets.categoria_aceites_y_gasolinas.forEach((element) =>
791        categories.push(element),
792      );
793    }
794    if (FWP.facets.categoria_automower) {
795      FWP.facets.categoria_automower.forEach((element) =>
796        categories.push(element),
797      );
798    }
799    if (FWP.facets.categoria_aspiradoras) {
800      FWP.facets.categoria_aspiradoras.forEach((element) =>
801        categories.push(element),
802      );
803    }
804    if (FWP.facets.categoria_cortacespedes) {
805      FWP.facets.categoria_cortacespedes.forEach((element) =>
806        categories.push(element),
807      );
808    }
809    if (FWP.facets.categoria_cortasetos) {
810      FWP.facets.categoria_cortasetos.forEach((element) =>
811        categories.push(element),
812      );
813    }
814    if (FWP.facets.categoria_desbrozadoras) {
815      FWP.facets.categoria_desbrozadoras.forEach((element) =>
816        categories.push(element),
817      );
818    }
819    if (FWP.facets.categoria_escarificadores_cesped) {
820      FWP.facets.categoria_escarificadores_cesped.forEach((element) =>
821        categories.push(element),
822      );
823    }
824    if (FWP.facets.categoria_herramientas_forestales) {
825      FWP.facets.categoria_herramientas_forestales.forEach((element) =>
826        categories.push(element),
827      );
828    }
829    if (FWP.facets.categoria_juguetes) {
830      FWP.facets.categoria_juguetes.forEach((element) =>
831        categories.push(element),
832      );
833    }
834    if (FWP.facets.categoria_merchandising) {
835      FWP.facets.categoria_merchandising.forEach((element) =>
836        categories.push(element),
837      );
838    }
839    if (FWP.facets.categoria_motoazada) {
840      FWP.facets.categoria_motoazada.forEach((element) =>
841        categories.push(element),
842      );
843    }
844    if (FWP.facets.categoria_motosierras) {
845      FWP.facets.categoria_motosierras.forEach((element) =>
846        categories.push(element),
847      );
848    }
849    if (FWP.facets.categoria_ropa) {
850      FWP.facets.categoria_ropa.forEach((element) => categories.push(element));
851    }
852    if (FWP.facets.categoria_sopladores) {
853      FWP.facets.categoria_sopladores.forEach((element) =>
854        categories.push(element),
855      );
856    }
857    config.categories = categories;
858    if (FWP.facets.price_range.length > 0) {
859      config.price = FWP.facets.price_range;
860      let min_price = 0;
861      let max_price = 0;
862      if (config.price.length > 0) {
863        for (let i = 0; i < config.price.length; i++) {
864          if (i === 0) {
865            min_price = parseInt(config.price[0]);
866          }
867          if (i === 1) {
868            max_price = parseInt(config.price[1]);
869          }
870        }
871      }
872      let eventPrice = {
873        event: "evento",
874        eventCat: "filtro",
875        eventAct: "precio",
876        eventLbl: min_price + " - " + max_price,
877      };
878      ("eventPrice", eventPrice);
879      window.dataLayer.push(eventPrice);
880    }
881
882    if (FWP.facets.buscador_productos !== "") {
883    }
884    if (FWP_HTTP.get.orderby) {
885    }
886    if (
887      FWP.facets.superficie_jardn &&
888      FWP.facets.superficie_jardn !== "" &&
889      FWP.facets.superficie_jardn.length > 0
890    ) {
891      let eventSuperf = {
892        event: "evento",
893        eventCat: "filtro",
894        eventAct: "superficie",
895        eventLbl: FWP.facets.superficie_jardn.join(" - "),
896      };
897      ("eventSuperf", eventSuperf);
898      window.dataLayer.push(eventSuperf);
899    }
900
901    if (categories.length > 0) {
902      let eventCategories = {
903        event: "evento",
904        eventCat: "filtro",
905        eventAct: "subcategorias",
906        eventLbl: categories.join(" - "),
907      };
908      ("eventCategories", eventCategories);
909      window.dataLayer.push(eventCategories);
910    }
911  });
912  /* Init payment method event */
913  var classPaymentMethod = ".wc_payment_method";
914  var $inputPaymentMethod = jQuery(classPaymentMethod);
915  if ($inputPaymentMethod.length) {
916    var $childsMethods;
917    var paymentMethodUpdate = function () {
918      var $inputs = jQuery('input[name="payment_method"]', $inputPaymentMethod);
919      var $selectedElement = jQuery(
920        'input:radio[name="payment_method"]:checked',
921      );
922      var financingType;
923      var selectedIndex = 1;
924      for (var i = 0; i < $inputs.length; i++) {
925        if ($inputs[i].id === $selectedElement.attr("id")) {
926          selectedIndex = i + 1;
927        }
928      }
929      var $childsSelected = $selectedElement
930        .parent()
931        .find("fieldset input:checked");
932      if ($childsSelected.length) {
933        if (!$childsMethods) {
934          $childsMethods = $selectedElement.parent().find("fieldset input");
935          $childsMethods.on("change", function () {
936            paymentMethodUpdate();
937          });
938        }
939        financingType = $childsSelected.next().text();
940      }
941      var event = {
942        event: "eventoEC",
943        eventCat: "ecommerce",
944        eventAct: "checkout-2",
945        eventLbl: "paymentType",
946        noInteraction: true,
947        ecommerce: {
948          checkout_option: {
949            actionField: {
950              step: selectedIndex,
951              option: $selectedElement.val(),
952              financingType: financingType,
953            },
954          },
955        },
956      };
957      ("eventPaymentMethod", event);
958      window.dataLayer.push(event);
959    };
960
961    jQuery("body").on("payment_method_selected", function () {
962      paymentMethodUpdate();
963    });
964  }
965  /* / payment method event */
966
967  // Evento expand content - btn ver más en PDP
968  if (page.name === "product" && typeof product !== "undefined") {
969    jQuery(document).on("click", ".btn-ver-mas", function () {
970      const isExpanded = jQuery(this).data("expanded");
971      jQuery(this).data("expanded", !isExpanded);
972
973      if (!isExpanded) {
974        window.dataLayer.push({
975          event: "pdp_expand_content",
976          page_type: "pdp",
977          item_id: product.sku,
978          item_name: product.name,
979          item_category: product.category,
980          content_section: "description",
981        });
982      }
983    });
984  }
985  // Evento pdp_specs_open al abrir especificaciones de producto
986  if (page.name === "product" && typeof product !== "undefined") {
987    jQuery(document).on(
988      "click",
989      ".accordion-button[data-bs-target='#collapseEspecificaciones']",
990      function () {
991        const isCollapsed = jQuery(this).hasClass("collapsed");
992
993        if (!isCollapsed) {
994          window.dataLayer.push({
995            event: "pdp_specs_open",
996            page_type: "pdp",
997            item_id: product.sku,
998            item_name: product.name,
999            item_category: product.category,
1000          });
1001        }
1002      },
1003    );
1004  }
1005  // Evento pdp_tech_sheet_download al descargar ficha técnica
1006  if (page.name === "product" && typeof product !== "undefined") {
1007    jQuery(document).on("click", ".boton-producto .btn-cart", function () {
1008      window.dataLayer.push({
1009        event: "pdp_tech_sheet_download",
1010        page_type: "pdp",
1011        item_id: product.sku,
1012        item_name: product.name,
1013        item_category: product.category,
1014        file_url: jQuery(this).attr("href"),
1015      });
1016    });
1017  }
1018  // Evento pdp_financing_interaction para el módulo de aplázame
1019  if (page.name === "product" && typeof product !== "undefined") {
1020    const apzDiv = document.querySelector("[data-aplazame-widget-instalments]");
1021    if (apzDiv) {
1022      let apzEventFired = false;
1023      apzDiv.addEventListener("click", function () {
1024        if (!apzEventFired) {
1025          apzEventFired = true;
1026          window.dataLayer.push({
1027            event: "pdp_financing_interaction",
1028            page_type: "pdp",
1029            item_id: product.sku,
1030            item_name: product.name,
1031            item_category: product.category,
1032            financing_action: "open",
1033          });
1034        }
1035      });
1036    }
1037  }
1038  // Evento pdp_newsletter_subscribe cuando newsletter
1039  const form = document.getElementById("gform_1");
1040  if (form) {
1041    form.addEventListener("submit", gtag_report_conversion_newsletter);
1042
1043    if (
1044      form.closest(".single-product") &&
1045      page.name === "product" &&
1046      typeof product !== "undefined"
1047    ) {
1048      let newsletterEventFired = false;
1049      form.addEventListener("submit", function () {
1050        if (!newsletterEventFired) {
1051          newsletterEventFired = true;
1052          window.dataLayer.push({
1053            event: "pdp_newsletter_subscribe",
1054            page_type: "pdp",
1055            item_id: product.sku,
1056            item_name: product.name,
1057            item_category: product.category,
1058            newsletter_location: "pdp",
1059          });
1060        }
1061      });
1062    }
1063  }
1064  // Evento pdp_trust_info_open al hacer click en los bloques de confianza
1065  if (page.name === "product" && typeof product !== "undefined") {
1066    const trustTypeMap = {
1067      envio: "shipping",
1068      garantia: "warranty",
1069      devolucion: "returns",
1070      financiacion: "financing",
1071    };
1072
1073    jQuery(document).on("click", ".item-conditions", function () {
1074      const condition = jQuery(this).data("condition");
1075      const trustType = trustTypeMap[condition];
1076      if (!trustType) return;
1077
1078      window.dataLayer.push({
1079        event: "pdp_trust_info_open",
1080        trust_type: trustType,
1081        item_id: product.sku,
1082        item_name: product.name,
1083        item_category: product.category,
1084        page_type: "pdp",
1085        content_section: "trust_info",
1086      });
1087    });
1088  }
1089  if (page.name === "checkout") {
1090    let lastCouponEntered = null;
1091    let lastCouponFailKey = null;
1092    let lastErrorSetKey = null;
1093
1094    // -------------------------------------------------------
1095    // Evento checkout_error — centraliza todos los errores
1096    // de WooCommerce en un único push por intento de pedido
1097    // -------------------------------------------------------
1098    function classifyErrorGroup(messages) {
1099      const joined = messages.join(" ").toLowerCase();
1100      if (/cartão|pagamento|payment|card|cvv|validade|expirac/.test(joined))
1101        return "payment";
1102      if (/envio|envío|shipping|postal|postcode|destino|entrega/.test(joined))
1103        return "shipping";
1104      if (
1105        /obrigatório|obrigatorio|requerido|preencha|campo|email|telefone|nome|apelido/.test(
1106          joined,
1107        )
1108      )
1109        return "validation";
1110      if (/termos|condições|política|legal/.test(joined)) return "legal";
1111      return "technical";
1112    }
1113
1114    function pushCheckoutError() {
1115      const errorItems = jQuery(".woocommerce-error li");
1116      if (!errorItems.length) return;
1117
1118      const messages = [];
1119      errorItems.each(function () {
1120        const msg = jQuery(this).text().trim();
1121        if (msg) messages.push(msg);
1122      });
1123      if (!messages.length) return;
1124
1125      // Evita disparar si el set de errores es idéntico al intento anterior
1126      const errorSetKey = messages.join("|");
1127      if (errorSetKey === lastErrorSetKey) return;
1128      lastErrorSetKey = errorSetKey;
1129
1130      window.dataLayer = window.dataLayer || [];
1131      window.dataLayer.push({
1132        event: "checkout_error",
1133        page_type: "checkout",
1134        checkout_step: "checkout",
1135        errors_count: messages.length,
1136        error_message_primary: messages[0],
1137        error_messages_joined: messages.join(" | "),
1138        error_group: classifyErrorGroup(messages),
1139      });
1140    }
1141
1142    // Disparo principal: click en "Realizar pedido"
1143    jQuery(document).on("click", "#place_order", function () {
1144      // Reseteamos la clave para que un nuevo intento siempre pueda disparar
1145      lastErrorSetKey = null;
1146    });
1147
1148    // Escuchamos el evento nativo de WooCommerce que confirma que hubo errores
1149    jQuery(document.body).on("checkout_error", function () {
1150      pushCheckoutError();
1151    });
1152
1153    // Observer de respaldo por si los errores se inyectan sin disparar checkout_error
1154    const noticesWrapper = document.querySelector(
1155      ".woocommerce-notices-wrapper",
1156    );
1157    if (noticesWrapper) {
1158      const errorsObserver = new MutationObserver(function () {
1159        if (jQuery(".woocommerce-error li").length) {
1160          pushCheckoutError();
1161        }
1162      });
1163      errorsObserver.observe(noticesWrapper, {
1164        childList: true,
1165        subtree: true,
1166      });
1167    }
1168
1169    // -------------------------------------------------------
1170    // Eventos checkout_coupon_apply y checkout_coupon_fail
1171    // -------------------------------------------------------
1172    jQuery(document).on("click", 'button[name="apply_coupon"]', function () {
1173      const couponInput = jQuery("#coupon_code").val();
1174      if (!couponInput || !couponInput.trim()) return;
1175
1176      lastCouponEntered = couponInput.trim().toUpperCase();
1177
1178      window.dataLayer = window.dataLayer || [];
1179      window.dataLayer.push({
1180        event: "checkout_coupon_apply",
1181        page_type: "checkout",
1182        checkout_step: "review",
1183        coupon_entered: lastCouponEntered,
1184      });
1185
1186      const couponForm = document.querySelector(".checkout_coupon");
1187      if (!couponForm) return;
1188
1189      const couponObserver = new MutationObserver(function (mutations, obs) {
1190        const errorEl = couponForm.querySelector("#coupon-error-notice");
1191        if (!errorEl) return;
1192        const msg = errorEl.textContent.replace("X", "").trim();
1193        if (!msg) return;
1194
1195        obs.disconnect();
1196
1197        const failKey = lastCouponEntered + "|" + msg;
1198        if (failKey !== lastCouponFailKey) {
1199          lastCouponFailKey = failKey;
1200          window.dataLayer = window.dataLayer || [];
1201          window.dataLayer.push({
1202            event: "checkout_coupon_fail",
1203            page_type: "checkout",
1204            checkout_step: "review",
1205            coupon_entered: lastCouponEntered,
1206            fail_reason: "invalid_coupon",
1207            error_message: msg,
1208          });
1209        }
1210      });
1211
1212      couponObserver.observe(couponForm, {
1213        childList: true,
1214        subtree: true,
1215        characterData: true,
1216      });
1217    });
1218  }
1219});
1220// -------------------------------------------------------
1221// Evento menu_navigation_click
1222// -------------------------------------------------------
1223(function () {
1224  "use strict";
1225
1226  function normalizeLabel(str) {
1227    if (!str) return null;
1228    return str
1229      .trim()
1230      .toLowerCase()
1231      .normalize("NFD")
1232      .replace(/[\u0300-\u036f]/g, "")
1233      .replace(/[^a-z0-9\s_-]/g, "")
1234      .replace(/\s+/g, "_");
1235  }
1236
1237  function inferLinkType(url) {
1238    if (!url || url === "#" || url === "javascript:void(0)") return null;
1239    try {
1240      var path = new URL(url, window.location.origin).pathname;
1241      if (/\/(catalogo|folleto)(cat)?(\/|$)/.test(path)) return "catalog";
1242      if (/\/contacto(\/|$)/.test(path)) return "page";
1243      return "category";
1244    } catch (e) {}
1245    return null;
1246  }
1247
1248  function pushMenuEvent(params) {
1249    window.dataLayer = window.dataLayer || [];
1250    window.dataLayer.push({
1251      event: "menu_navigation_click",
1252      menu_location: params.menu_location,
1253      menu_level: params.menu_level,
1254      menu_item: params.menu_item,
1255      menu_parent: params.menu_parent || null,
1256      menu_grandparent: params.menu_grandparent || null,
1257      menu_url: params.menu_url || null,
1258      link_type: params.link_type || null,
1259      page_path: window.location.pathname,
1260    });
1261  }
1262
1263  // Lee el label limpio de un .megamenu-parent-item usando span.ms-16
1264  function getParentItemLabel(el) {
1265    if (!el) return null;
1266    var span = el.querySelector("span.ms-16");
1267    return normalizeLabel(span ? span.textContent : el.textContent);
1268  }
1269
1270  document.addEventListener("DOMContentLoaded", function () {
1271    // ── 1. NAVBAR ESTÁTICA ──────────────────────────────────
1272    // level_1: navbar-static-link (Productos, Ofertas, Accesorios, Husqvarna)
1273    var staticNav = document.querySelector(".navbar-static-links");
1274    if (staticNav) {
1275      // level_1
1276      staticNav.addEventListener("click", function (e) {
1277        var link = e.target.closest(".navbar-static-link");
1278        if (!link) return;
1279        // Ignorar si el click viene de dentro de un dropdown (es level_2)
1280        if (e.target.closest(".dropdown-menu")) return;
1281        var href = link.getAttribute("href");
1282        var url =
1283          !href || href === "#" || href === "javascript:void(0)" ? null : href;
1284        pushMenuEvent({
1285          menu_location: "main_menu",
1286          menu_level: "level_1",
1287          menu_item: normalizeLabel(link.textContent),
1288          menu_url: url,
1289          link_type: url ? inferLinkType(url) : null,
1290        });
1291      });
1292
1293      // level_2: hijos de dropdown (.dropdown-custom-link)
1294      staticNav.addEventListener("click", function (e) {
1295        var link = e.target.closest(".dropdown-custom-link");
1296        if (!link) return;
1297        var dropdownMenu = link.closest(".dropdown-menu");
1298        var parentLi = dropdownMenu ? dropdownMenu.closest(".nav-item") : null;
1299        var parentToggle = parentLi
1300          ? parentLi.querySelector(":scope > a.navbar-static-link")
1301          : null;
1302        var url = link.getAttribute("href");
1303        pushMenuEvent({
1304          menu_location: "main_menu",
1305          menu_level: "level_2",
1306          menu_item: normalizeLabel(
1307            link.querySelector("span.ms-16")
1308              ? link.querySelector("span.ms-16").textContent
1309              : link.textContent,
1310          ),
1311          menu_parent: parentToggle
1312            ? normalizeLabel(parentToggle.textContent)
1313            : null,
1314          menu_url: url,
1315          link_type: inferLinkType(url),
1316        });
1317      });
1318    }
1319
1320    // ── 2. MEGAMENÚ DESKTOP ─────────────────────────────────
1321    var megamenu = document.getElementById("offcanvasMegaMenu");
1322    if (megamenu) {
1323      megamenu.addEventListener("click", function (e) {
1324        // Capturamos el level_2 activo al inicio del handler,
1325        // antes de que el JS del menú pueda modificar is-active
1326        var activeLevel2 = megamenu.querySelector(
1327          ".megamenu-parent-item.is-active",
1328        );
1329        var activeLevel2Label = getParentItemLabel(activeLevel2);
1330
1331        // level_3: megamenu-child-item a (columna subcats)
1332        var childLink = e.target.closest(".megamenu-child-item a");
1333        if (childLink) {
1334          var url = childLink.getAttribute("href");
1335          pushMenuEvent({
1336            menu_location: "main_menu",
1337            menu_level: "level_3",
1338            menu_item: normalizeLabel(
1339              childLink.querySelector("span.ms-16")
1340                ? childLink.querySelector("span.ms-16").textContent
1341                : childLink.textContent,
1342            ),
1343            menu_parent: activeLevel2Label,
1344            menu_grandparent: "produtos",
1345            menu_url: url,
1346            link_type: inferLinkType(url),
1347          });
1348          return;
1349        }
1350
1351        // level_3: megamenu-popular-block a
1352        var popularLink = e.target.closest(".megamenu-popular-block a");
1353        if (popularLink) {
1354          var url = popularLink.getAttribute("href");
1355          pushMenuEvent({
1356            menu_location: "main_menu",
1357            menu_level: "level_3",
1358            menu_item: normalizeLabel(popularLink.textContent),
1359            menu_parent: activeLevel2Label,
1360            menu_grandparent: "produtos",
1361            menu_url: url,
1362            link_type: inferLinkType(url),
1363          });
1364          return;
1365        }
1366
1367        // level_2: megamenu-parent-item (columna cats)
1368        var parentItem = e.target.closest(".megamenu-parent-item");
1369        if (parentItem) {
1370          var url = parentItem.dataset.url || null;
1371          pushMenuEvent({
1372            menu_location: "main_menu",
1373            menu_level: "level_2",
1374            menu_item: getParentItemLabel(parentItem),
1375            menu_parent: "produtos",
1376            menu_url: url,
1377            link_type: url ? inferLinkType(url) : null,
1378          });
1379          return;
1380        }
1381      });
1382    }
1383
1384    // ── 3. MENÚ MÓVIL ───────────────────────────────────────
1385    var mobileMenu = document.getElementById("offcanvasMobileMenu");
1386    if (mobileMenu) {
1387      mobileMenu.addEventListener("click", function (e) {
1388        // level_3: popular block
1389        var popularLink = e.target.closest(".mobile-popular-block a");
1390        if (popularLink) {
1391          var backLabel = mobileMenu.querySelector("#mobileBackLabel");
1392          var url = popularLink.getAttribute("href");
1393          pushMenuEvent({
1394            menu_location: "mobile_menu",
1395            menu_level: "level_3",
1396            menu_item: normalizeLabel(popularLink.textContent),
1397            menu_parent: backLabel
1398              ? normalizeLabel(backLabel.textContent)
1399              : null,
1400            menu_grandparent: "produtos",
1401            menu_url: url,
1402            link_type: inferLinkType(url),
1403          });
1404          return;
1405        }
1406
1407        // level_3: subcategorías (pantalla 2)
1408        var subcatLink = e.target.closest(".mobile-subcats-list a");
1409        if (subcatLink) {
1410          var backLabel = mobileMenu.querySelector("#mobileBackLabel");
1411          var url = subcatLink.getAttribute("href");
1412          pushMenuEvent({
1413            menu_location: "mobile_menu",
1414            menu_level: "level_3",
1415            menu_item: normalizeLabel(
1416              subcatLink.querySelector("span.ms-16")
1417                ? subcatLink.querySelector("span.ms-16").textContent
1418                : subcatLink.textContent,
1419            ),
1420            menu_parent: backLabel
1421              ? normalizeLabel(backLabel.textContent)
1422              : null,
1423            menu_grandparent: "produtos",
1424            menu_url: url,
1425            link_type: inferLinkType(url),
1426          });
1427          return;
1428        }
1429
1430        // level_2: panels WP walker (Accesorios, Husqvarna…)
1431        var wpPanelLink = e.target.closest(".mobile-panel-item a");
1432        if (wpPanelLink) {
1433          var activeTab = mobileMenu.querySelector(
1434            ".mobile-menu-tab.is-active",
1435          );
1436          var url = wpPanelLink.getAttribute("href");
1437          pushMenuEvent({
1438            menu_location: "mobile_menu",
1439            menu_level: "level_2",
1440            menu_item: normalizeLabel(
1441              wpPanelLink.querySelector("span.ms-16")
1442                ? wpPanelLink.querySelector("span.ms-16").textContent
1443                : wpPanelLink.textContent,
1444            ),
1445            menu_parent: activeTab
1446              ? normalizeLabel(activeTab.textContent)
1447              : null,
1448            menu_url: url,
1449            link_type: inferLinkType(url),
1450          });
1451          return;
1452        }
1453
1454        // level_2: categorías producto (pantalla 1, abre pantalla 2)
1455        var catItem = e.target.closest(".mobile-panel-item--cat");
1456        if (catItem) {
1457          var url = catItem.dataset.url || null;
1458          pushMenuEvent({
1459            menu_location: "mobile_menu",
1460            menu_level: "level_2",
1461            menu_item: normalizeLabel(
1462              catItem.querySelector("span.ms-16")
1463                ? catItem.querySelector("span.ms-16").textContent
1464                : catItem.textContent,
1465            ),
1466            menu_parent: "produtos",
1467            menu_url: url,
1468            link_type: url ? inferLinkType(url) : null,
1469          });
1470          return;
1471        }
1472
1473        // level_1: tabs WP (Ofertas, Accesorios, Husqvarna…)
1474        var tab = e.target.closest(".mobile-menu-tab");
1475        if (tab) {
1476          pushMenuEvent({
1477            menu_location: "mobile_menu",
1478            menu_level: "level_1",
1479            menu_item: normalizeLabel(tab.textContent),
1480            menu_url: null,
1481            link_type: null,
1482          });
1483          return;
1484        }
1485      });
1486    }
1487  }); // DOMContentLoaded
1488})(); // IIFE
1489
1490/*
1491 * ─────────────────────────────────────────────────────────────────────────────
1492 * ADD_TO_CART Event Handler (FIX para GA4 PT — productos sin id/name)
1493 * ─────────────────────────────────────────────────────────────────────────────
1494 * Captura clicks en botones de "Adicionar ao carrinho" (ficha + listado)
1495 * y pushea el evento add_to_cart REAL al dataLayer con datos completos.
1496 */
1497document.addEventListener("click", function (e) {
1498  // Detectar clicks en botones de add_to_cart (ficha y listado)
1499  const btn = e.target.closest(
1500    ".single_add_to_cart_button, .boton-add-cart-ficha"
1501  );
1502  if (!btn) return;
1503
1504  // En la ficha de producto: usar el objeto global 'product' (inyectado por analytics.php)
1505  if (typeof product !== "undefined" && product.id && product.name) {
1506    const quantity =
1507      document.querySelector('input[name="quantity"]')?.value || 1;
1508    eventClickAddCart(product, 1, parseInt(quantity));
1509    return;
1510  }
1511
1512  // En el listado: obtener datos desde data-attributes del botón o su contenedor
1513  const productId = btn.dataset.product_id;
1514  if (!productId) return;
1515
1516  // Buscar el contenedor de datos del producto (data-analytic-product-id)
1517  const productContainer = document.querySelector(
1518    '[data-analytic-product-id="' + productId + '"]'
1519  );
1520  if (productContainer) {
1521    const productData = getProductDataById(productId, "analytic-product");
1522    if (productData && productData.id && productData.name) {
1523      // Asegurar que el precio es numérico decimal (no string ni en micros)
1524      productData.price = parseFloat(productData.price) || 0;
1525      eventClickAddCart(
1526        productData,
1527        productData.position || 1,
1528        parseInt(btn.dataset.quantity || 1)
1529      );
1530    }
1531  }
1532}, true); // capture phase: interceptar antes de que el formulario procese el click

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.