PageSourceSearch

https://www.lojaintt.com.br/stores/687/static/js/main.js?v=1

js lojaintt.com.br collected 2026-09-26 10:09:39 UTC 73,655 bytes, 2,564 lines download raw bytes

1var demo = [];
2
3if (typeof storeProducts == "undefined") {
4  storeProducts = [];
5  storeProducts.isLoaded = false;
6}
7
8if (typeof dealerGrid == "undefined") {
9  dealerGrid = [];
10  dealerGrid.isLoaded = false;
11}
12
13demo.cartHtml = {
14  quantity: ".new-header__client-area__cart .new-header__client-area__desktop",
15  quantityMobile:
16    ".new-header__client-area__cart .new-header__client-area__cart__info",
17  items: ".fastCartContent",
18  total: ".new-header__client-area__cart.hidden-sm .subtotal-fastcart",
19};
20
21demo.login = {
22  loginHtmlElement: ".new-header__client-area__login",
23  loginHtmlElementMobile: ".new-mobile-menu__header",
24  logoutButtons:
25    ".new-header__client-area__options, .out-login, .salesman-header-menu a, .salesman-header-menu.hidden-xs a",
26};
27
28demo.calculateFreightProduct = function () {
29  const fatherFormContainer = document.querySelector('.product-data__freight-container');
30  const form = document.getElementById('freteForm');
31
32  if (!fatherFormContainer || !form) return;
33
34  const loading = fatherFormContainer.querySelector('#loading-spinner__freight-product');
35
36  form.addEventListener('submit', function (e) {
37    e.preventDefault();
38
39    loading?.classList.remove('hidden');
40
41    const formData = new FormData(form);
42
43    const body = document.body;
44    const observer = new MutationObserver((mutationsList, observerInstance) => {
45      for (const mutation of mutationsList) {
46        if (
47          mutation.type === 'attributes' &&
48          mutation.attributeName === 'class' &&
49          body.classList.contains('modal-open')
50        ) {
51          loading?.classList.add('hidden');
52          observerInstance.disconnect();
53          break;
54        }
55      }
56    });
57
58    observer.observe(body, { attributes: true });
59
60    fetch(form.action, {
61      method: 'POST',
62      body: formData
63    })
64    .then(response => {
65      if (!response.ok) throw new Error('Erro ao calcular frete.');
66      return response.text();
67    })
68  });
69};
70
71demo.calculateFreightHeader = async function () {
72  var zipcode = $("#header-zipcode").val();
73  const messageContainer = document.querySelector(".freight-content__message");
74  const resultContainer = document.getElementById("freight-result");
75
76  if (messageContainer) {
77    messageContainer.classList.add("hidden");
78    messageContainer.classList.remove("freight-content__message-error");
79  }
80
81  if (zipcode.length === 8) {
82    zipcode = zipcode.substring(0, 5) + "-" + zipcode.substring(5);
83  }
84  if (!zipcode || zipcode.length < 9 || zipcode.charAt(5) !== "-") {
85    demo.displayFreightMessage("Por favor, insira um CEP válido.", true);
86    return;
87  }
88  var data = {
89    act: "listar",
90    cep: zipcode,
91    codigoPais: "BR",
92  };
93
94  var ajaxFrete = $("#urlsite").val() + "/ajax/checkout/frete.php";
95
96  try {
97    const response = await fetch(ajaxFrete, {
98      method: "POST",
99      headers: {
100        "Content-Type": "application/x-www-form-urlencoded",
101      },
102      body: new URLSearchParams(data),
103    });
104    const responseJSON = await response.json();
105    var _deliveries = responseJSON.data.length > 0 ? responseJSON.data : null;
106
107    if (_deliveries == null) {
108      demo.displayFreightMessage("Nenhum frete disponível para o CEP informado.", true);
109      resultContainer.classList.add("d-none");
110      return;
111    }
112    var freightListHtml = "";
113    const formatter = new Intl.NumberFormat("pt-BR", {
114      style: "currency",
115      currency: "BRL",
116    });
117
118    _deliveries.forEach(function (option) {
119      let displayPrice =
120        option.valor === 0
121          ? "Grátis"
122          : formatter.format(option.valor);
123      freightListHtml += "<p>" + option.nome + " - " + displayPrice + "</p>";
124    });
125
126    $("#freight-result").html(freightListHtml).removeClass("d-none");
127  } catch (error) {
128    console.error("Erro ao calcular o frete: ", error);
129    demo.displayFreightMessage("Erro ao calcular o frete. Tente novamente mais tarde.", true);
130    resultContainer.classList.add("d-none");
131  }
132};
133
134demo.displayFreightMessage = function (message, isError = false) {
135  const messageContainer = document.querySelector(".freight-content__message");
136
137  if (messageContainer) {
138    messageContainer.textContent = message;
139    messageContainer.classList.remove("hidden", "freight-content__message-error");
140
141    if (isError) {
142      messageContainer.classList.add("freight-content__message-error");
143    }
144
145    messageContainer.onclick = () => {
146      messageContainer.classList.add("hidden");
147    };
148  }
149};
150
151demo.applyCouponHeader = function () {
152  const couponValue = $("#header-coupon").val();
153  const messageContainer = document.querySelector(".coupon-content__message");
154
155  if (messageContainer) {
156    messageContainer.classList.add("hidden");
157    messageContainer.classList.remove("coupon-content__message-error");
158  }
159
160  if (!couponValue) {
161    demo.displayCouponMessage("Por favor, insira um cupom válido.", true);
162    return;
163  }
164
165  const url = $("#urlajax").val() + "/pedido.php?act=cupom&cupom=" + encodeURIComponent(couponValue);
166  X.get(url, "demo.handleCoupon");
167};
168
169demo.handleCoupon = function (response) {
170  const content = response?.data?.data;
171  const type = content?.type;
172  const data = content?.data;
173
174  if (type === "mix" && Array.isArray(data)) {
175    const statCupom = data.find(item => item?.data?.id === "statCupom" && typeof item?.data?.html === "string");
176
177    if (statCupom) {
178      const message = statCupom.data.html;
179      const isError = /cupom (n[aã]o encontrado|inv[aá]lido|expirado)|erro/i.test(message);
180      demo.displayCouponMessage(message, isError);
181    } else {
182      demo.displayCouponMessage("Cupom aplicado!", false);
183    }
184    return;
185  }
186
187  if (type === "updater" && typeof data?.html === "string") {
188    if (data.id === "finalizar") {
189      demo.displayCouponMessage("Cupom aplicado!", false);
190    } else {
191      const message = data.html;
192      const isError = /cupom (n[aã]o encontrado|inv[aá]lido|expirado)|erro/i.test(message);
193      demo.displayCouponMessage(message, isError);
194    }
195    return;
196  }
197
198  demo.displayCouponMessage("Não foi possível validar o cupom.", true);
199};
200
201demo.displayCouponMessage = function (message, isError = false) {
202  const messageContainer = document.querySelector(".coupon-content__message");
203
204  if (messageContainer) {
205    messageContainer.textContent = message;
206    messageContainer.classList.remove("hidden", "coupon-content__message-error");
207
208    if (isError) {
209      messageContainer.classList.add("coupon-content__message-error");
210    }
211
212    messageContainer.onclick = () => {
213      messageContainer.classList.add("hidden");
214    };
215  }
216};
217
218demo.checkStopwatchPromotion = function () {
219  $(".promotion-product-timer").each(function () {
220    if ($(this).find(".stopwatch-product-timer").length === 0) {
221      $(this).remove();
222    }
223  });
224
225  var promotionBanner = $(".promotion-banner");
226  var promotionBannerTimerContainer = promotionBanner.find(
227    ".promotion-product-timer"
228  );
229
230  if (promotionBannerTimerContainer.length === 0) {
231    promotionBanner.remove();
232    return;
233  }
234};
235
236demo.slideBackTop = function () {
237  var btnBack = $("#button-back");
238
239  $(window).on("scroll", function () {
240    var scrolltop = $(window).scrollTop();
241    var top = btnBack.outerHeight(true) + btnBack.outerHeight(true);
242
243    if (scrolltop >= top) {
244      btnBack.addClass("visible");
245    } else {
246      btnBack.removeClass("visible");
247    }
248  });
249
250  btnBack.find(".hide").on("click", function () {
251    btnBack.slideDown({
252      duration: 500,
253    });
254  });
255};
256
257demo.backTop = function () {
258  var btnTop = $(".btnTop");
259
260  btnTop.on("click", function (e) {
261    $("html, body").animate({ scrollTop: 0 }, "1000");
262  });
263};
264
265demo.openTrackingURL = function () {
266  $("[data-tracking]").on("submit", function (e) {
267    var trackingCode = $(this).find("[data-tracking-code]");
268    if (!trackingCode.length) {
269      console.error("Não há o elemento do código de rastreio");
270      return false;
271    } else if (!trackingCode.val().length) {
272      alert("Oops, você precisa digitar um código");
273      return false;
274    }
275
276    return true;
277  });
278};
279
280demo.equalizeColumns = function () {
281  var watch = $("[data-equalizer-watch]");
282  var columns = $("[data-equalizer]");
283
284  if (watch.length > 0) {
285    columns.height("auto");
286    var height = watch.outerHeight();
287
288    if (height > 1) columns.height(height);
289    else if (height == 1) setTimeout(demo.equalizeColumns, 300);
290  }
291};
292
293demo.startProductTip = function (isModal) {
294  if (isModal) {
295    $(".modal .product-content .tip").tooltip("hide");
296    $(".modal .product-content .tip").eq(0).tooltip("show");
297  } else {
298    $(".product-content .tip").tooltip("hide");
299    $(".product-content .tip").eq(0).tooltip("show");
300  }
301};
302
303demo.enableTooltip = function () {
304  $(".tip").tooltip({
305    placement: "top",
306    trigger: "manual",
307    title: function () {
308      var title = $(this).attr("data-title");
309      if (title) return title;
310
311      return;
312    },
313  });
314};
315
316demo.cartPanel = function () {
317  var clickerTop = $("#clicker-top");
318  var clicker = $("#clicker");
319  var clickerOff = $("#clicker-off");
320  var panelWrap = $(".panel-wrap");
321
322  clickerTop.on("click", function () {
323    panelWrap.css("transform", "translateX(0%)");
324  });
325
326  clicker.on("click", function () {
327    panelWrap.css("transform", "translateX(0%)");
328    demo.handleCartActions();
329  });
330
331  clickerOff.on("click", function () {
332    panelWrap.css("transform", "translateX(100%)");
333  });
334};
335
336demo.updateCart = function () {
337  X.get(
338    $("#urlajax").val() + "/pedido.php?act=carrinhorapido&show=list",
339    "demo.handleCartActions"
340  );
341};
342
343demo.handleCartActions = function () {
344  if (cartGamificationBanner != undefined) {
345    cartGamificationBanner.calculateBannerProgressBar();
346    cartGamificationBanner.calculateBannerProgressBar("OnCart");
347  }
348
349  if (storageCache.setCartSaved !== undefined) {
350    storageCache.setCartSaved();
351  }
352  
353  demo.verifyImageFastCart();
354};
355
356demo.goBackPage = function () {
357  $(".back-page").on("click", function () {
358    window.history.back();
359  });
360};
361
362function goToPage(url) {
363  window.location.replace(url);
364}
365
366demo.footerSectionsMobile = function () {
367  if ($(window).width() > 991) {
368    return;
369  }
370
371  var sections = $(".new-footer__column");
372
373  sections.each(function () {
374    var titleMobile = $(this).find(".new-footer__title--mobile");
375    var listMobile = $(this).find(".new-footer__list--mobile");
376    var angle = titleMobile.find(".fa");
377
378    titleMobile.on("click", function (e) {
379      if (listMobile.hasClass("new-footer--open")) {
380        listMobile.removeClass("new-footer--open");
381        angle.removeClass("fa-angle-up");
382        angle.addClass("fa-angle-down");
383      } else {
384        listMobile.addClass("new-footer--open");
385        angle.addClass("fa-angle-up");
386        angle.removeClass("fa-angle-down");
387      }
388
389      e.preventDefault();
390      return;
391    });
392  });
393};
394
395demo.gliderAutoPlay = (glider = null, element = null, delay = 5000, repeat = true) => {
396  if (!glider || !element) {
397    return
398  }
399
400  let autoplay = null;
401  const slidesCount = glider.track.childElementCount;
402  let nextIndex = 1;
403  let pause = true;
404
405  function slide() {
406      autoplay = setInterval(() => {
407          if (nextIndex >= slidesCount) {
408              if (!repeat) {
409                  clearInterval(autoplay);
410              } else {
411                  nextIndex = 0;
412              }
413          }
414          glider.scrollItem(nextIndex++);
415      }, delay);
416  }
417
418  slide();
419
420  element.addEventListener('mouseover', (event) => {
421      if (pause) {
422          clearInterval(autoplay);
423          pause = false;
424      }
425  }, 300);
426
427  element.addEventListener('mouseout', (event) => {
428      if (!pause) {
429          slide();
430          pause = true;
431      }
432  }, 300);
433}
434
435demo.gliderCloneSlider = (element, items, totalItems, minItems) => {
436  if (!element || !items || !totalItems || !minItems) {
437    return
438  }
439
440  while (totalItems < minItems) {
441    for (let i = 0; i < items.length; i++) {
442      if (totalItems >= minItems) break;
443      var clone = items[i].cloneNode(true);
444      element.appendChild(clone);
445      totalItems++;
446    }
447  }
448}
449
450demo.gliderFillElementSpace = (element, gap, slidesToShow, maxWidth) => {
451  if (!element || !slidesToShow) {
452    return
453  }
454  const parentWidth = element.clientWidth;
455
456  if (gap) {
457    const resultCalc = (parentWidth - gap) / slidesToShow;
458    return resultCalc;
459  }
460
461  if (maxWidth) {
462    const resultCalc = (maxWidth * slidesToShow - parentWidth) / (slidesToShow - 1);
463    const positiveGap = Math.max(0, Math.abs(resultCalc));
464    const gliderTrack = element.querySelector('.glider-track');
465    if (gliderTrack) {
466      gliderTrack.style.gap = `${positiveGap}px`;
467    }
468    return
469  }
470}
471
472demo.mainBanners = () => {
473  var mainBanner = document.querySelector(".main-banner");
474  if (!mainBanner) {
475    return;
476  }
477
478  var mainBannerLazyload = mainBanner.querySelector(".lazyload-banner");
479  if (mainBannerLazyload) {
480    mainBannerLazyload.remove();
481  }
482
483  var mainBannerCarousel = mainBanner.querySelector(".main-banner__slider");
484  if (!mainBannerCarousel) {
485    return;
486  }
487
488	var slider = new Glider(mainBannerCarousel, {
489		slidesToShow: 1,
490		slidesToScroll: 1,
491		draggable: true,
492		dots: '.main-carousel__dots',
493		duration: 0.2,
494		rewind: true,
495		arrows: {
496		  prev: mainBanner.querySelector('.arrows .arrow-left'),
497		  next: mainBanner.querySelector('.arrows .arrow-right')
498		}
499	});
500  demo.gliderAutoPlay(slider, mainBannerCarousel, 5000);
501};
502
503demo.mainBannersMobile = () => {
504  var mainBanner = document.querySelector(".main-banner-mobile");
505  if (!mainBanner) {
506    return;
507  }
508
509  var mainBannerLazyload = mainBanner.querySelector(".lazyload-banner-mobile");
510  if (mainBannerLazyload) {
511    mainBannerLazyload.remove();
512  }
513
514  var mainBannerCarousel = mainBanner.querySelector(".main-banner__slider-mobile");
515  if (!mainBannerCarousel) {
516    return;
517  }
518
519	var slider = new Glider(mainBannerCarousel, {
520		slidesToShow: 1,
521		slidesToScroll: 1,
522		draggable: true,
523		dots: '.main-carousel-mobile__dots',
524		duration: 0.2,
525		rewind: true,
526		arrows: {
527		  prev: mainBanner.querySelector('.arrows .arrow-left'),
528		  next: mainBanner.querySelector('.arrows .arrow-right')
529		}
530	});
531  demo.gliderAutoPlay(slider, mainBannerCarousel, 5000);
532};
533
534
535demo.benefitsCarousel = () => {
536  var benefitsContent = document.querySelector(".new-benefits-box");
537  if (!benefitsContent) {
538    return;
539  }
540  var benefitsCarousel = benefitsContent.querySelector(".benefits__slider");
541  if (!benefitsCarousel) {
542    return;
543  }
544
545	var slider = new Glider(benefitsCarousel, {
546		slidesToShow: 2,
547		slidesToScroll: 2,
548		draggable: true,
549		dots: false,
550		duration: 0.2,
551		rewind: true,
552		arrows: false,
553    responsive: [
554      {
555        breakpoint: 767,
556        settings: {
557          slidesToShow: 3,
558        }
559      },{
560        breakpoint: 1350,
561        settings: {
562          slidesToShow: 3.8,
563          draggable: false
564        }
565      },{
566        breakpoint: 1401,
567        settings: {
568          slidesToShow: 4,
569          draggable: false
570        }
571      }
572    ]
573	});
574
575  demo.gliderAutoPlay(slider, benefitsCarousel, 5000);
576};
577
578demo.initializeProductListCarousel = (autoplay) => {
579  var productListRelease = ".new-product-list--release";
580  demo.productListCarousel(productListRelease, autoplay);
581
582  var productListBestSellers = ".new-product-list--best-sellers";
583  demo.productListCarousel(productListBestSellers, autoplay);
584
585  var productListHighlights = ".new-product-list--highlights";
586  demo.productListCarousel(productListHighlights, autoplay);
587
588  var productListRelated = ".new-product-list--related-products";
589  demo.productListCarousel(productListRelated, autoplay);
590};
591
592demo.productListCarousel = (productList, autoplay) => {
593  var productListContainer = document.querySelector(productList);
594  if (!productListContainer) {
595    return;
596  }
597  var prodListCarousel = productListContainer.querySelector(".new-product-list__slider");
598  if (!prodListCarousel || prodListCarousel.glider) {
599    return
600  }
601
602  let maxWidth = 0;
603  let gapMaxWidth = 0;
604  let slidesToShow = 0;
605  const width = window.innerWidth;
606  
607  slidesToShow = 
608    width < 762 ? 2 :
609      width < 992 ? 3 :
610        width < 1700 ? 4 : 5;
611
612  if (width >= 500) {
613    maxWidth = width >= 1101 ? 250 : 220;
614  } else {
615    maxWidth = width >= 401 ? 190 : 170;
616  }
617
618  if (width >= 1101) {
619    const parentWidth = prodListCarousel.clientWidth;
620    const resultCalc = (maxWidth * slidesToShow - parentWidth) / (slidesToShow - 1);
621    const positiveGap = Math.max(0, Math.abs(resultCalc));
622    gapMaxWidth = (maxWidth + positiveGap).toFixed(2);
623  }
624
625  var slider = new Glider(prodListCarousel, {
626    slidesToShow: width >= 1101 ? slidesToShow : 'auto',
627    slidesToScroll: width >= 1101 ? slidesToShow : 'auto',
628    itemWidth: gapMaxWidth,
629    exactWidth: true,
630    scrollLock: true,
631    draggable: true,
632    dots: productListContainer.querySelector('.new-product-list__dots'),
633    arrows: {
634      prev: productListContainer.querySelector('.arrow-left'),
635      next: productListContainer.querySelector('.arrow-right'),
636    },
637    duration: 0.5,
638    rewind: true,
639  });
640
641  if (width >= 1101) {
642    productListContainer.querySelector('.arrow-right').addEventListener("click", function() {
643      const totalSlides = slider.slides.length;
644      const currentSlide = slider.getCurrentSlide() + (slidesToShow - 1);
645  
646      if (currentSlide >= totalSlides - 1) {
647        slider.scrollItem(0);
648      }
649    });
650  }
651
652  demo.gliderFillElementSpace(prodListCarousel, null, slidesToShow, maxWidth);
653  if (autoplay) {
654    demo.gliderAutoPlay(slider, productListContainer, 4000, true);
655  }
656}
657
658demo.bannersMiddle = () => {
659  var bannersMiddleContent = document.querySelector(".banner-middle");
660  if (!bannersMiddleContent) {
661    return;
662  }
663
664  var bannersMiddleCarousel = bannersMiddleContent.querySelector(".banner-middle__slider");
665  if (!bannersMiddleCarousel) {
666    return;
667  }
668
669  let items = bannersMiddleCarousel.children;
670  let totalItems = items.length;
671  if (totalItems < 1) {
672    bannersMiddleContent.classList.add("hidden");
673    return
674  }
675  let minItems = 4;
676  if (totalItems <= minItems) {
677    // demo.gliderCloneSlider(bannersMiddleCarousel, items, totalItems, minItems);
678    bannersMiddleContent.querySelector('.banner-middle__dots')?.classList.add('hidden');
679    bannersMiddleContent.querySelector('.arrows.no-select')?.classList.add('hidden');
680  }
681
682	var slider = new Glider(bannersMiddleCarousel, {
683		slidesToShow: 1,
684		slidesToScroll: 1,
685		draggable: true,
686		dots: '.banner-middle__dots',
687		duration: 0.2,
688		rewind: true,
689		arrows: {
690		  prev: bannersMiddleContent.querySelector('.arrows .arrow-left'),
691		  next: bannersMiddleContent.querySelector('.arrows .arrow-right')
692		}, responsive: [
693      {
694        breakpoint: 400,
695        settings: {
696          slidesToShow: 1.5,
697          slidesToScroll: 1.5,
698        }
699      },
700      {
701        breakpoint: 500,
702        settings: {
703          slidesToShow: 2,
704          slidesToScroll: 2,
705        }
706      },
707      {
708        breakpoint: 768,
709        settings: {
710          slidesToShow: 3,
711          slidesToScroll: 3,
712        }
713      },
714      {
715        breakpoint: 1700,
716        settings: {
717          slidesToShow: 4,
718          slidesToScroll: 4,
719        }
720      },
721    ]
722	});
723  demo.gliderAutoPlay(slider, bannersMiddleCarousel, 5000);
724};
725
726demo.bannersBottom = () => {
727  var bannersBottomContent = document.querySelector(".banner-bottom");
728  if (!bannersBottomContent) {
729    return;
730  }
731
732  var bannersBottomCarousel = bannersBottomContent.querySelector(".banner-bottom__slider");
733  if (!bannersBottomCarousel) {
734    return;
735  }
736
737  let items = bannersBottomCarousel.children;
738  let totalItems = items.length;
739  if (totalItems < 1) {
740    bannersBottomContent.classList.add("hidden");
741    return
742  }
743  let minItems = 2;
744  if (totalItems <= minItems) {
745    // demo.gliderCloneSlider(bannersBottomCarousel, items, totalItems, minItems);
746    bannersBottomContent.querySelector('.banner-bottom__dots')?.classList.add('hidden');
747    bannersBottomContent.querySelector('.arrows.no-select')?.classList.add('hidden');
748  }
749
750	var slider = new Glider(bannersBottomCarousel, {
751		slidesToShow: 1,
752		slidesToScroll: 1,
753		draggable: true,
754		dots: '.banner-bottom__dots',
755		duration: 0.2,
756		rewind: true,
757		arrows: {
758		  prev: bannersBottomContent.querySelector('.arrows .arrow-left'),
759		  next: bannersBottomContent.querySelector('.arrows .arrow-right')
760		}, responsive: [
761      {
762        breakpoint: 992,
763        settings: {
764          slidesToShow: 2,
765          slidesToScroll: 2,
766        }
767      },
768    ]
769	});
770  demo.gliderAutoPlay(slider, bannersBottomContent, 5000);
771};
772
773demo.promotionCarousel = () => {
774  var promotionBanner = document.querySelector(".promotion-banner");  
775  if (!promotionBanner) {
776    return;
777  }
778  var promotionBannerCarousel = promotionBanner.querySelector(".promotional-banner__slider");
779  if (!promotionBannerCarousel) {
780    return;
781  }
782
783  let items = promotionBannerCarousel.children;
784  let totalItems = items.length;
785  if (totalItems < 1) {
786    promotionBanner.classList.add("hidden")
787    return
788  }
789
790  let slidesToShow;
791  let gapMaxWidth = 0;
792  const width = window.innerWidth;
793
794  if (width >= 500) {
795    slidesToShow = width >= 750 ? 2 : 1.5;
796  } else {
797    slidesToShow = 1;
798  }
799
800  if (width >= 768) {
801    maxWidth = width >= 1700 ? 667.5 : 580;
802  } else {
803    maxWidth = 320;
804  }
805  if (width >= 1101) {
806    const parentWidth = promotionBannerCarousel.clientWidth;
807    const resultCalc = (maxWidth * slidesToShow - parentWidth) / (slidesToShow - 1);
808    const positiveGap = Math.max(0, Math.abs(resultCalc));
809    gapMaxWidth = (maxWidth + positiveGap).toFixed(2);
810  }
811
812  var slider = new Glider(promotionBannerCarousel, {
813    slidesToShow: width >= 1101 ? slidesToShow : 'auto',
814    slidesToScroll: width >= 1101 ? slidesToShow : 'auto',
815    exactWidth: true,
816    itemWidth: gapMaxWidth,
817    dots: promotionBanner.querySelector('.promotional-banner__dots'),
818    draggable: true,
819    arrows: {
820      prev: promotionBanner.querySelector(".arrow-left"),
821      next: promotionBanner.querySelector(".arrow-right"),
822    },
823		duration: 1,
824		rewind: true,
825  });
826
827  if (width >= 1101) {
828    promotionBanner.querySelector('.arrow-right').addEventListener("click", function() {
829      const totalSlides = slider.slides.length;
830      const currentSlide = slider.getCurrentSlide() + (slidesToShow - 1);
831
832      if (currentSlide >= totalSlides - 1) {
833        slider.scrollItem(0);
834      }
835    });
836  }
837  
838  demo.gliderFillElementSpace(promotionBannerCarousel, null, slidesToShow, maxWidth);
839  if (width >= 1101) demo.gliderAutoPlay(slider, promotionBanner, 8000);
840};
841
842demo.buyForBrandCarousel = () => {
843  var buyForBrand = document.querySelector(".new-buyforbrand");
844  if (!buyForBrand) {
845    return;
846  }
847
848  var buyBrandCarousel = buyForBrand.querySelector(".new-buyforbrand__slider");
849  if (!buyBrandCarousel) {
850    return;
851  }
852
853  let items = buyBrandCarousel.children;
854  let totalItems = items.length;
855  let minItems = 10;
856  if (totalItems < minItems) {
857    demo.gliderCloneSlider(buyBrandCarousel, items, totalItems, minItems);
858  }
859
860  var slider = new Glider(buyBrandCarousel, {
861    slidesToShow: 2.5,
862    slidesToScroll: 2.5,
863    draggable: true,
864    dots: buyForBrand.querySelector('.buyforbrand__dots'),
865    arrows: {
866      prev: buyForBrand.querySelector(".arrow-left"),
867      next: buyForBrand.querySelector(".arrow-right"),
868    },
869    duration: 0.5,
870    rewind: true,
871    responsive: [
872      {
873        breakpoint: 500,
874        settings: {
875          slidesToShow: 3,
876          slidesToScroll: 3,
877        }
878      },
879      {
880        breakpoint: 768,
881        settings: {
882          slidesToShow: 4,
883          slidesToScroll: 4,
884          draggable: false,
885        }
886      },
887      {
888        breakpoint: 991,
889        settings: {
890          slidesToShow: 9,
891          slidesToScroll: 9,
892        }
893      }
894    ]
895  });
896
897  demo.gliderAutoPlay(slider, buyBrandCarousel, 4000);
898};
899
900demo.showSuppliers = function () {
901  var suppliers = document.querySelectorAll(".special-suppliers");
902  if (!suppliers) {
903    return;
904  }
905
906  suppliers.forEach(function (supplier) {
907    supplier.addEventListener("click", function () {
908      var supplierId = supplier.querySelector(".special-supplier-id").textContent;
909
910      suppliers.forEach(function (s) {
911        var id = s.querySelector(".special-supplier-id").textContent;
912        var supplierElement = document.querySelector(".supplier-id-" + id);
913        if (supplierElement) {
914          supplierElement.classList.add("hide");
915        }
916        s.classList.remove("supplier-selected");
917      });
918
919      supplier.classList.add("supplier-selected");
920
921      var selectedSupplierElement = document.querySelector(".supplier-id-" + supplierId);
922      if (selectedSupplierElement) {
923        selectedSupplierElement.classList.remove("hide");
924      }
925    });
926  });
927
928  suppliers.forEach(function (supplier) {
929    if (supplier.classList.contains("active")) {
930      supplier.click();
931      return false;
932    }
933  });
934};
935
936demo.checkBuyBrandsSupplier = function () {
937  var buyForBrandContainer = $(".new-buyforbrand");
938  if (buyForBrandContainer.length < 1) {
939    return
940  }
941  var brandSupplier = buyForBrandContainer.find(".brands-suppliers .new-buyforbrand__slider");
942  var buyForBrandItem = buyForBrandContainer.find(".supplier .special-suppliers");
943
944  if (brandSupplier.length < 1 || buyForBrandItem.length < 1) {
945    buyForBrandContainer.addClass("hidden");
946  }
947}
948
949demo.productSuppliersCarousel = () => {
950  var productSupplier = document.querySelector(".supplier");
951  if (!productSupplier) {
952    return;
953  }
954  var supplierDivs = productSupplier.children;
955  Array.from(supplierDivs).forEach(function(supplierDiv, index) {
956  var supplierCarousel = supplierDiv.querySelector(".product-supplier__slider");
957    if (!supplierCarousel) {
958      return;
959    }
960
961    let items = supplierCarousel.children;
962    let totalItems = items.length;
963    let minItems = 4;
964    if (totalItems < minItems) {
965      demo.gliderCloneSlider(supplierCarousel, items, totalItems, minItems);
966    }
967
968    if (supplierCarousel.glider) {
969      supplierCarousel.glider.destroy();
970    }
971
972    var slider = new Glider(supplierCarousel, {
973      slidesToShow: 2,
974      slidesToScroll: 2,
975      draggable: true,
976      dots: supplierDiv.querySelector('.product-supplier__dots'),
977      arrows: {
978        prev: supplierDiv.querySelector(".arrow-left"),
979        next: supplierDiv.querySelector(".arrow-right"),
980      },
981      duration: 0.5,
982      rewind: true,
983      responsive: [
984        {
985          breakpoint: 480,
986          settings: {
987            slidesToShow: 2,
988            slidesToScroll: 2,
989          }
990        },
991        {
992          breakpoint: 1700,
993          settings: {
994            slidesToShow: 2.5,
995            slidesToScroll: 2.5,
996          }
997        }
998      ]
999    });
1000  });
1001};
1002
1003demo.categoryBanner = function () {
1004  var categoryBanners = $(".category-banners");
1005
1006  var owlCarousel = categoryBanners.find(".owl-carousel");
1007
1008  if (owlCarousel.length < 1) {
1009    return;
1010  }
1011
1012  owlCarousel.owlCarousel({
1013    lazyLoad: true,
1014    lazyLoadEager: true,
1015    responsiveClass: true,
1016    dots: true,
1017    mouseDrag: false,
1018    responsive: {
1019      0: {
1020        loop: true,
1021        items: 3,
1022      },
1023      500: {
1024        loop: true,
1025        items: 3,
1026      },
1027      768: {
1028        loop: true,
1029        items: 4,
1030      },
1031      991: {
1032        items: 4,
1033      },
1034      992: {
1035        items: 8,
1036      },
1037    },
1038  });
1039
1040  demo.productListArrows(".category-banners", categoryBanners, owlCarousel);
1041};
1042
1043demo.recentPostCarousel = () => {
1044  var recentPostContainer = document.querySelector(".recent-post");
1045  var recentPost = document.querySelector(".recent-post__container__blog");
1046  if (!recentPost) {
1047    return;
1048  }
1049
1050  var recentPostSlider = recentPost.querySelector(".recent-post__slider");
1051  if (!recentPostSlider) {
1052    return;
1053  }
1054
1055  let items = recentPostSlider.children;
1056  let totalItems = items.length;
1057  if (totalItems < 1) {
1058    recentPostContainer.classList.add("hidden");
1059    return
1060  }
1061  let minItems = 5;
1062  if (totalItems < minItems) {
1063    demo.gliderCloneSlider(recentPostSlider, items, totalItems, minItems);
1064  }
1065
1066  var glider = new Glider(recentPostSlider, {
1067    slidesToShow: 1,
1068    slidesToScroll: 1,
1069    draggable: true,
1070		dots: '.recent-post__dots',
1071    duration: 0.5,
1072    rewind: true,
1073    arrows: {
1074      prev: recentPost.querySelector(".arrow-left"),
1075      next: recentPost.querySelector(".arrow-right"),
1076    },
1077    responsive: [
1078      {
1079        breakpoint: 0,
1080        settings: {
1081          slidesToShow: 1,
1082        }
1083      },
1084      {
1085        breakpoint: 500,
1086        settings: {
1087          slidesToShow: 2,
1088        }
1089      },
1090      {
1091        breakpoint: 700,
1092        settings: {
1093          slidesToShow: 3,
1094        }
1095      },
1096      {
1097        breakpoint: 1350,
1098        settings: {
1099          slidesToShow: 3.2,
1100        }
1101      },
1102      {
1103        breakpoint: 1700,
1104        settings: {
1105          slidesToShow: 3.8,
1106        }
1107      },
1108    ]
1109  });
1110  if (glider) {
1111    demo.gliderAutoPlay(glider, recentPostSlider, 5000);
1112  }
1113};
1114
1115demo.instagramCarousel = () => {
1116  var instagramContainer = document.querySelector(".instagram-section");
1117  var instagramCarousel = document.querySelector(".instagram-section .instagram-carousel .instagram__slider");
1118  if (!instagramCarousel) {
1119    return;
1120  }
1121  if (instagramContainer) {
1122    var instagramItems = instagramCarousel.querySelectorAll("a.instagram");
1123    if (!instagramItems || instagramItems.length < 1) {
1124      instagramContainer.classList.add("hidden");
1125      return;
1126    }
1127
1128    let gap;
1129    let slidesToShow;
1130    const width = window.innerWidth;
1131
1132    gap = width >= 501 ? 20 : 10;
1133    if (width >= 501) {
1134      slidesToShow = width >= 768 ? 3 : 2;
1135    } else {
1136      slidesToShow = 1;
1137    }
1138
1139    var enableLoop = instagramItems.length > 3;
1140    const itemWidth = demo.gliderFillElementSpace(instagramCarousel, gap, slidesToShow);
1141
1142    var glider = new Glider(instagramCarousel, {
1143      slidesToShow: 'auto',
1144      slidesToScroll: 'auto',
1145      exactWidth: true,
1146      itemWidth: itemWidth,
1147      draggable: true,
1148      dots: false,
1149      duration: 0.2,
1150      rewind: enableLoop,
1151      arrows: false
1152    });
1153  }
1154};
1155
1156demo.menuMobile = function () {
1157  if ($(document).width() > 991) {
1158    return;
1159  }
1160
1161  var mobileMenu = $("[new-mobile-menu]");
1162  var menuButton = $("[new-mobile-menu-button]");
1163  var mobileBox = $("[new-mobile-box]");
1164  var headerOverlay = $(".header-overlay");
1165  var closeButton = $("[new-mobile-menu-button-close]");
1166  var menuCategories = $("[new-mobile-menu-categories]");
1167  var buttonMenuCategories = $("[new-mobile-menu-categories-button]");
1168  var menuSubCategories = $("[new-mobile-menu-subcategories-button]");
1169  var categoryButtonClass = "new-mobile-menu__body__content--categories";
1170  var categoryClass = "new-mobile-menu__body__categories";
1171  var closeSearchButton = $("[new-mobile-search-button-close]");
1172
1173  menuButton.on("click", function () {
1174    openMenu();
1175  });
1176
1177  closeButton.on("click", function () {
1178    closeMenu();
1179  });
1180
1181  buttonMenuCategories.on("click", function () {
1182    toggleMenuCategories();
1183  });
1184
1185  $("[show-search-mobile] img").on("click", function () {
1186    $("[show-search-mobile]").addClass("show-search-mobile");
1187  });
1188
1189  closeSearchButton.on("click", function () {
1190    $("[show-search-mobile]").removeClass("show-search-mobile");
1191  });
1192
1193  menuSubCategories.each(function () {
1194    let category = $(this);
1195    category.on("click", function (ev) {
1196      if ($(this).hasClass("new-mobile-menu__body__content")) {
1197        ev.preventDefault();
1198        if ($(ev.target).parents(".new-mobile-menu__body__title").length != 0) {
1199          window.location.href = $(this).attr("redirect");
1200          return;
1201        }
1202      }
1203      toggleMenuSubCategories(category);
1204    });
1205  });
1206
1207  var openMenu = function () {
1208    let titleMobileClient = $('.new-mobile-menu__header--title');
1209    mobileBox.addClass("new-mobile-box-open");
1210    mobileMenu.attr("new-mobile-menu", "true");
1211    mobileMenu.addClass("new-mobile-menu--open");
1212    titleMobileClient.addClass("new-mobile-menu__header--title--open");
1213    headerOverlay.addClass("header-overlay--active");
1214    closeButton.addClass("new-mobile-menu__close-button--open");
1215  };
1216
1217  var closeMenu = function () {
1218    let titleMobileClient = $('.new-mobile-menu__header--title');
1219    mobileBox.removeClass("new-mobile-box-open");
1220    mobileMenu.removeClass("new-mobile-menu--open");
1221    mobileMenu.attr("new-mobile-menu", "false");
1222    titleMobileClient.removeClass("new-mobile-menu__header--title--open");
1223    headerOverlay.removeClass("header-overlay--active");
1224    closeButton.removeClass("new-mobile-menu__close-button--open");
1225  };
1226
1227  var toggleMenuCategories = function () {
1228    menuCategories.toggleClass(`${categoryClass}--open`);
1229    buttonMenuCategories.find(".fa").toggleClass("fa-angle-up");
1230    buttonMenuCategories.find(".fa").toggleClass("fa-angle-down");
1231  };
1232
1233  var toggleMenuSubCategories = function (category) {
1234    let categoryName = category.attr("new-mobile-menu-subcategories-button");
1235    let subCategory = $(`[new-mobile-menu-subcategories=${categoryName}]`);
1236
1237    category.find(".fa").toggleClass("fa-angle-up");
1238    category.find(".fa").toggleClass("fa-angle-down");
1239
1240    category.toggleClass(`${categoryButtonClass}--open`);
1241    subCategory.toggleClass(`${categoryClass}--open`);
1242
1243    $("[new-mobile-menu-subcategories-button]").on("click", function () {
1244      let seeMoreSubCategories = $(this).find(".see-more-subcategories");
1245      if (subCategory.hasClass(`${categoryClass}--open`)) {
1246        seeMoreSubCategories.toggleClass("see-more-subcategories--open");
1247        if (seeMoreSubCategories.hasClass("see-more-subcategories--open")) {
1248          seeMoreSubCategories.text("-");
1249        } else {
1250          seeMoreSubCategories.text("+");
1251        }
1252      }
1253    });
1254  };
1255};
1256
1257demo.showcategorieDesktop = function () {
1258  const containers = document.querySelectorAll(".all-subcategories--content");
1259  if (!containers.length) return;
1260
1261  containers.forEach((container) => {
1262    let items = Array.from(container.children);
1263    if (!items.length) return;
1264
1265    let withGrandchild = items.filter((ul) => ul.querySelector("ul ul"));
1266    let normal = items.filter((ul) => !ul.querySelector("ul ul"));
1267
1268    container.innerHTML = "";
1269    [...normal, ...withGrandchild].forEach((el) =>
1270      container.appendChild(el)
1271    );
1272
1273    const totalItems =
1274      container.querySelectorAll(":scope > ul.hidden-xs.hidden-sm").length +
1275      container.querySelectorAll("li[data-id-categoria-filha]").length;
1276      console.log("totalItems: " + totalItems);
1277
1278    const estimatedHeight = totalItems * 25;
1279    let ulContainer = container.querySelectorAll(":scope > ul");
1280
1281    if (estimatedHeight > 270) {
1282      container.style.overflow = "visible";
1283      container.style.overflowX = "auto";
1284      container.style.display = "flex";
1285      container.style.flexWrap = "wrap";
1286      container.style.flexDirection = "column";
1287      ulContainer?.forEach((ul) => { ul.style.width = "50%"; })
1288    } else {
1289      container.style.overflow = "visible";
1290      container.style.gridTemplateColumns = "1fr";
1291      const parent = container.closest(".all-subcategories");
1292      if (parent) parent.style.width = "300px";
1293    }
1294  });
1295};
1296
1297demo.hoverOnCategoryDesktop = function () {
1298  if ($(document).width() < 992) {
1299    return;
1300  }
1301
1302  var all = $("li.new-menu__main-menu__menu__list");
1303  var list = $(".subcategories-list li.category-title");
1304
1305  all.on("mouseenter", function () {
1306    if ($(this).index() <= 9) {
1307      $(this).addClass("new-menu__main-menu__menu__list--hover");
1308
1309      $(this).find(list).css("background", "#fe3378");
1310      $(this).find(list).first().css("background", "#50133e");
1311
1312      $(this)
1313        .find(".new-menu__main-menu__menu__submenu__bottom__categories")
1314        .empty();
1315      let childSubcategories = $(this)
1316        .find(list)
1317        .first()
1318        .siblings(".subcategories-childrens")
1319        .html();
1320      var html = demo.cutCategories(childSubcategories);
1321      $(this)
1322        .parents()
1323        .find(".new-menu__main-menu__menu__submenu__bottom__categories")
1324        .append(html);
1325
1326      $(this)
1327        .find(".new-menu__main-menu__menu__submenu__bottom__image")
1328        .empty();
1329      let childSubcategoriesImage = $(this)
1330        .find(".subcategories-list")
1331        .first()
1332        .find(".category-image-destaque")
1333        .html();
1334      $(this)
1335        .find(".new-menu__main-menu__menu__submenu__bottom__image")
1336        .append(childSubcategoriesImage);
1337    }
1338  });
1339  all.on("mouseleave", function () {
1340    $(this).removeClass("new-menu__main-menu__menu__list--hover");
1341  });
1342
1343  list.on("mouseenter", function () {
1344    $(this)
1345      .parent(".subcategories-list")
1346      .parent()
1347      .find("ul li.category-title")
1348      .css("background", "#fe3378");
1349    $(this).css("background", "#50133e");
1350
1351    let childSubcategories = $(this)
1352      .siblings(".subcategories-childrens")
1353      .html();
1354    $(this)
1355      .parents()
1356      .find(".new-menu__main-menu__menu__submenu__bottom__categories")
1357      .empty();
1358    var html = demo.cutCategories(childSubcategories);
1359    $(this)
1360      .parents()
1361      .find(".new-menu__main-menu__menu__submenu__bottom__categories")
1362      .append(html);
1363
1364    $(this)
1365      .parents()
1366      .find(".new-menu__main-menu__menu__submenu__bottom__image")
1367      .empty();
1368    let childSubcategoriesImage = $(this)
1369      .parent(".subcategories-list")
1370      .find(".category-image-destaque")
1371      .html();
1372    $(this)
1373      .parents()
1374      .find(".new-menu__main-menu__menu__submenu__bottom__image")
1375      .append(childSubcategoriesImage);
1376  });
1377};
1378
1379demo.cutCategories = function (childSubcategories) {
1380  let contador = 0;
1381  let html = "";
1382
1383  $(childSubcategories)
1384    .find("a")
1385    .each(function () {
1386      if (contador == 0) {
1387        html += "<ul>";
1388      }
1389
1390      contador++;
1391      html += $(this)[0].outerHTML;
1392
1393      if (contador == 10) {
1394        contador = 0;
1395        html += "</ul>";
1396      }
1397    });
1398
1399  if (contador > 0) {
1400    html += "</ul>";
1401  }
1402
1403  return html;
1404};
1405
1406demo.addProductToCart = function (e) {
1407  var section = $(e.target).closest("[data-add-cart-section]");
1408  var uniqueUnit = section.find('[name="uniqUnit"]').val();
1409
1410  if (!uniqueUnit) {
1411    return;
1412  }
1413
1414  var action = $("#urlajax").val() + "/produto.php?act=carrinho";
1415  var product = section.find('[name="id"]').val();
1416  var quantity = section.find('[name="quantity"]').val();
1417  var url = action + "&produto=" + product + "&qtde=" + quantity;
1418
1419  X.get(url);
1420
1421  e.preventDefault();
1422  return;
1423};
1424
1425demo.addProductToCartEvent = function () {
1426  $("[data-add-product-to-cart]").on("click", demo.addProductToCart);
1427};
1428
1429demo.changeQuantity = function () {
1430  $(document).on("keyup blur change", ".quantity-adder .quantity", function () {
1431    var val = parseInt($(this).val());
1432    var dataMax = parseInt($(this).attr("data-max"));
1433    var frete = $("#qtdefrete").val(val);
1434    checkStock($(this), val, dataMax, frete);
1435  });
1436
1437  $(document).on("click", ".quantity-adder .add-action", function (e) {
1438    e.preventDefault();
1439    var input = $(this).closest(".quantity-adder").find("input");
1440
1441    var val = parseInt(input.val());
1442    var dataMax = parseInt(input.attr("data-max"));
1443
1444    if ($(this).hasClass("add-up")) {
1445      val = val + 1;
1446    } else if ($(this).hasClass("add-down") && val > 0) {
1447      val = val - 1;
1448    }
1449
1450    input.val(val);
1451    var frete = $("#qtdefrete").val(val);
1452    checkStock(input, val, dataMax, frete);
1453  });
1454
1455  const checkStock = (input, val, dataMax, frete) => {
1456    if (val > dataMax) {
1457      input.css("color", "#F00");
1458    } else {
1459      input.css("color", "");
1460    }
1461
1462    return frete;
1463  };
1464};
1465
1466demo.enableTooltip = function () {
1467  $(".tip").tooltip({
1468    placement: "top",
1469    trigger: "manual",
1470    title: function () {
1471      var title = $(this).attr("data-title");
1472
1473      if (title) {
1474        return title;
1475      }
1476
1477      return;
1478    },
1479  });
1480};
1481
1482demo.showTooltip = function () {
1483  $('[data-toggle="tooltip"]').tooltip();
1484};
1485
1486demo.getProductSku = function (idProductJson) {
1487  var modalClass = "";
1488  var labelOption = "[text-color]";
1489  var isRetailType = $(".form-grade-varejo");
1490
1491  if (idProductJson != "#skuProducts") {
1492    modalClass = ".modal-body ";
1493  }
1494
1495  var optionContent = modalClass + ".option-content";
1496
1497  if ($(optionContent).length < 1) {
1498    return;
1499  }
1500
1501  if ($(idProductJson).text()) {
1502    var json = JSON.parse($(idProductJson).text());
1503    var skuProducts = json.produtos;
1504    var idProduct = Object.keys(skuProducts)[0];
1505    var units = skuProducts[idProduct].unidades;
1506
1507    var optionContentHtml = "";
1508    var textTitleOption = "";
1509    var options = [];
1510    var sizeContentHtml = [];
1511    var unitStock = [];
1512    var unitStockControl = [];
1513    var countOptions = 0;
1514    var countSizes = [];
1515    var skusPrice = [];
1516
1517    unitStock[idProduct] = [];
1518    unitStockControl[idProduct] = [];
1519    window.units = units;
1520    textTitleOption += demo.getTitleOption(skuProducts[idProduct]);
1521
1522    for (let sku in units) {
1523      let unit = units[sku];
1524
1525      let option = unit.opcao;
1526      let size = unit.tamanho;
1527      let priceDe = unit.de;
1528      let pricePor = unit.por;
1529      let stock = unit.estoque;
1530      let stockControl = unit.controlaEstoque == 1;
1531
1532      skusPrice[option.id + "-" + size.id] = [priceDe, pricePor];
1533
1534      if (options.indexOf(option.id) < 0) {
1535        let skusStock = [];
1536        let skusStockControl = [];
1537        options.push(option.id);
1538
1539        skusStock[size.id] = stock;
1540        skusStockControl[size.id] = stockControl;
1541
1542        unitStock[idProduct][option.id] = skusStock;
1543        unitStockControl[idProduct][option.id] = skusStockControl;
1544        countSizes[option.id] = 1;
1545
1546        optionContentHtml += demo.getOptionHtml(unit, option, size);
1547        sizeContentHtml[option.id] = demo.getSizeHtml(unit, option, size);
1548
1549        countOptions++;
1550      } else {
1551        unitStock[idProduct][option.id][size.id] = stock;
1552        unitStockControl[idProduct][option.id][size.id] = stockControl;
1553
1554        sizeContentHtml[option.id] += demo.getSizeHtml(unit, option, size);
1555
1556        countSizes[option.id] += 1;
1557      }
1558
1559      // Caso o produto seja unico, ele irá entrar nesse if e não gerar todos os opc/tam
1560      if (units.length == 1 && !isRetailType.length) {
1561        $(".options-section").addClass("hidden");
1562        customization.init();
1563
1564        let optionSelected = option.id;
1565        let sizeSelected = size.id;
1566        let sku = optionSelected + "/" + sizeSelected;
1567        let buyContent = $(".buy-content");
1568
1569        buyContent.find("[name=opcao]").attr("value", optionSelected);
1570        buyContent.find("[name=tamanho]").attr("value", "");
1571
1572        customization.changeUnit(sku, 1, true);
1573        return;
1574      }
1575    }
1576
1577    $(labelOption).html(textTitleOption);
1578    $(optionContent).html(optionContentHtml);
1579
1580    demo.checkStockInSizes(optionContent, sizeContentHtml);
1581
1582    // customization.init();
1583
1584    demo.selectableSku(
1585      idProduct,
1586      sizeContentHtml,
1587      unitStock,
1588      countOptions,
1589      countSizes,
1590      unitStockControl,
1591      skusPrice,
1592      idProductJson
1593    );
1594  }
1595};
1596
1597demo.checkStockInSizes = function (optionContent, sizeContentHtml) {
1598  $(optionContent)
1599    .find("li")
1600    .each(function () {
1601      var optionId = $(this).attr("data-option");
1602      var sizes = sizeContentHtml[optionId];
1603      var hasStock = $(sizes).hasClass("in-stock");
1604
1605      if (!hasStock) {
1606        $(this).addClass("no-stock");
1607      }
1608    });
1609};
1610
1611demo.getTitleOption = function (option) {
1612  var html =
1613    '<label class="control-label" text-color alt="' +
1614    option.rotuloOpcao +
1615    '">' +
1616    option.rotuloOpcao +
1617    "</label>";
1618
1619  return html;
1620};
1621
1622demo.addProductToWishList = function () {
1623  var optionsWish = ".options-sku";
1624  var sizesWish = ".sizes-sku";
1625  var options = ".sku.options";
1626  var sizes = ".sku.sizes";
1627
1628  var optionContentClass = "option-content";
1629  var optionContent = options + " ." + optionContentClass;
1630  var optionTitle = options + " .option-title";
1631  var optionContentWish = optionsWish + " ." + optionContentClass;
1632  var optionTitleWish = optionsWish + " .option-title";
1633  var sizeContentClass = "size-content";
1634  var sizeContent = sizes + " ." + sizeContentClass;
1635  var sizeTitle = sizes + " .size-title";
1636  var sizeContentWish = sizesWish + " ." + sizeContentClass;
1637  var sizeTitleWish = sizesWish + " .size-title";
1638  var optionItem = options + " ul li";
1639  var optionItemColor = options + " ul li span";
1640  var optionItemWish = optionsWish + " ul li";
1641  var optionItemWishColor = optionsWish + " ul li span";
1642  var sizeItem = sizes + " ul li";
1643  var sizeItemWish = sizesWish + " ul li";
1644  var buyClass = ".buy-content";
1645  var buyClassWish = ".sku.wish";
1646  var oldPriceClass = ".sku.oldprice";
1647  var newPriceClass = ".sku.newprice";
1648  var statusClass = ".sku.status";
1649
1650  var urlOption =
1651    $("#urlajax").val() +
1652    "/produto.php?act=opcaobloco&class=" +
1653    sizeContentClass;
1654  var urlSize =
1655    $("#urlajax").val() +
1656    "/produto.php?act=tamanhobloco&class=" +
1657    buyClass +
1658    "&newprice=" +
1659    newPriceClass +
1660    "&oldprice=" +
1661    oldPriceClass +
1662    "&status=" +
1663    statusClass;
1664  var urlSizeWish =
1665    $("#urlajax").val() +
1666    "/produto.php?act=tamanhobloco&class=" +
1667    buyClassWish +
1668    "&newprice=" +
1669    newPriceClass +
1670    "&oldprice=" +
1671    oldPriceClass +
1672    "&status=" +
1673    statusClass;
1674
1675  var initialBuy = $(buyClass).html();
1676  var initialBuyWish = $(buyClassWish).html();
1677
1678  $(document).on(
1679    "click",
1680    optionItemWish + ", " + optionItemWishColor,
1681    function (e) {
1682      e.preventDefault();
1683
1684      if ($(".options-sku ul li").parents(".modal-body.wish").length < 1) {
1685        return;
1686      }
1687
1688      var optionElement = $(this);
1689      var optionElementWish = $(this);
1690
1691      if (optionElement.hasClass("color")) {
1692        optionElement = optionElement.closest(optionItem);
1693      }
1694
1695      if (optionElementWish.hasClass("color")) {
1696        optionElementWish = optionElementWish.closest(optionItemWish);
1697      }
1698
1699      $(optionItem).removeClass("active");
1700      $(optionItemWish).removeClass("active");
1701      optionElement.addClass("active");
1702      optionElementWish.addClass("active");
1703
1704      var product = parseInt(
1705        optionElement.closest(options).attr("data-product")
1706      );
1707      var productWish = parseInt(
1708        optionElementWish.closest(optionsWish).attr("data-product")
1709      );
1710
1711      var option = parseInt(optionElement.attr("data-option"));
1712      var optionWish = parseInt(optionElementWish.attr("data-option"));
1713      var isModal = optionElement.parents(".modal").length > 0;
1714
1715      if (product > 0 && option > 0) {
1716        var url = urlOption + "&produto=" + product + "&opcao=" + option;
1717        if (isModal) {
1718          url += "&modal=true";
1719          $(".modal " + buyClass).html(initialBuy);
1720        } else {
1721          $(buyClass).html(initialBuy);
1722        }
1723
1724        X.get(url);
1725
1726        // Set button values when exists
1727        if (optionElement.find("a").length > 0) {
1728          var stitle = "selecione o tamanho";
1729          var otitle = optionElement.find("a").html();
1730
1731          if ($(sizeTitle).length > 0) {
1732            $(sizeTitle).html(stitle);
1733          }
1734
1735          if ($(optionTitle).length > 0) {
1736            $(optionTitle).html(otitle);
1737          }
1738        }
1739      }
1740
1741      if (productWish > 0 && optionWish > 0) {
1742        var url =
1743          urlOption + "&produto=" + productWish + "&opcao=" + optionWish;
1744        if (isModal) {
1745          url += "&modal=true";
1746          $(".modal " + buyClassWish).html(initialBuyWish);
1747        } else {
1748          $(buyClassWish).html(initialBuyWish);
1749        }
1750
1751        X.get(url);
1752
1753        if (optionElementWish.find("a").length > 0) {
1754          var stitle = "selecione o tamanho";
1755          var otitle = optionElementWish.find("a").html();
1756
1757          if ($(sizeTitleWish).length > 0) {
1758            $(sizeTitleWish).html(stitle);
1759          }
1760
1761          if ($(optionTitleWish).length > 0) {
1762            $(optionTitleWish).html(otitle);
1763          }
1764        }
1765      }
1766
1767      if (isModal) {
1768        $(".modal .product-content .tip").eq(0).tooltip("hide");
1769        $(".modal .product-content .tip").eq(1).tooltip("show");
1770      } else {
1771        $(".product-content .tip").eq(0).tooltip("hide");
1772        $(".product-content .tip").eq(1).tooltip("show");
1773      }
1774    }
1775  );
1776
1777  $(document).on("ready show.bs.modal", function () {
1778    var isModal = $(".modal").length;
1779    if (isModal) {
1780      $(".modal " + optionItem)
1781        .first()
1782        .trigger("click");
1783    } else {
1784      $(optionItem).first().trigger("click");
1785    }
1786  });
1787
1788  $(document).on("click", sizeItem + ", " + sizeItemWish, function (e) {
1789    e.preventDefault();
1790
1791    if ($(".sizes-sku ul li").parents(".modal-body.wish").length < 1) {
1792      return;
1793    }
1794
1795    $(sizeItemWish).removeClass("active");
1796
1797    var product = parseInt($(this).closest(sizes).attr("data-product"));
1798    var productWish = parseInt($(this).closest(sizesWish).attr("data-product"));
1799    var option = parseInt($(this).attr("data-option"));
1800    var size = parseInt($(this).attr("data-size"));
1801    var isModal = $(this).parents(".modal").length > 0;
1802    var isWish = $(this).parents(".wish").length > 0;
1803
1804    if ((product > 0 || productWish) && option > 0 && size > 0) {
1805      if (isWish) {
1806        var url =
1807          urlSizeWish +
1808          "&produto=" +
1809          productWish +
1810          "&opcao=" +
1811          option +
1812          "&tamanho=" +
1813          size;
1814        url += "&wish=true";
1815
1816        if (isModal) {
1817          url += "&modal=true";
1818        }
1819      } else {
1820        var url =
1821          urlSize +
1822          "&produto=" +
1823          product +
1824          "&opcao=" +
1825          option +
1826          "&tamanho=" +
1827          size;
1828
1829        if (isModal) {
1830          url += "&modal=true";
1831        }
1832      }
1833
1834      X.get(url);
1835
1836      if ($(this).find("a").length > 0) {
1837        var stitle = $(this).find("a").html();
1838        if (isWish) {
1839          if ($(sizeTitleWish).length > 0) {
1840            $(sizeTitleWish).html(stitle);
1841          }
1842        } else {
1843          if ($(sizeTitle).length > 0) {
1844            $(sizeTitle).html(stitle);
1845          }
1846        }
1847      }
1848
1849      if (isModal) {
1850        $(".modal .product-content .tip").tooltip("hide");
1851      } else {
1852        $(".product-content .tip").tooltip("hide");
1853      }
1854    }
1855  });
1856};
1857
1858demo.selectableSku = function (
1859  idProduct,
1860  sizeContentHtml,
1861  unitStock,
1862  countOptions,
1863  countSizes,
1864  unitStockControl,
1865  skusPrice,
1866  idProductJson
1867) {
1868  var modalClass = "";
1869
1870  if (idProductJson != "#skuProducts") {
1871    modalClass = ".modal-body ";
1872  }
1873
1874  var dataProduct = $(modalClass + ".sizes").attr("data-product");
1875  var sizeContent =
1876    modalClass + `[data-product=${dataProduct}] ` + ".size-content";
1877  var optionContent =
1878    modalClass + `[data-product=${dataProduct}] ` + ".option-content";
1879  var optionItem = optionContent + " li span";
1880  var sizeItem = sizeContent + " li";
1881
1882  var optionsWish = ".options-sku";
1883  var sizesWish = ".sizes-sku";
1884  var optionItemWish = optionsWish + " ul li";
1885  var sizeItemWish = sizesWish + " ul li";
1886
1887  var dropdownTamanho = $(`${modalClass} #dropdownTamanho`);
1888  var buyContent = $(`${modalClass} .buy-content`);
1889  var btnCart = buyContent.find(".btn-cart-able");
1890  var btnCartDisable = buyContent.find(".btn-cart-disable");
1891  var btnOptionNotSelected = buyContent.find(".btn-cart-option-not-selected");
1892  var btnSizeNotSelected = buyContent.find(".btn-cart-size-not-selected");
1893  var optionSelected = null;
1894  var sizeSelected = null;
1895
1896  $("#tamanhofrete").val(sizeContent);
1897
1898  $(document).on("click", optionItem, function (e) {
1899    e.preventDefault();
1900
1901    if ($(optionItem).parents(".modal-body.wish").length > 0) {
1902      return;
1903    }
1904
1905    customization.clearSelect();
1906    optionSelected = $(this).closest("li").attr("data-option");
1907    optionSelectedObj = $(this).closest("li");
1908
1909    $(sizeContent).html(sizeContentHtml[optionSelected]);
1910
1911    $(optionItem).closest("li").removeClass("active");
1912    $(optionSelectedObj).addClass("active");
1913
1914    buyContent.find("[name=opcao]").attr("value", optionSelected);
1915    buyContent.find("[name=tamanho]").attr("value", "");
1916
1917    btnCart.addClass("hidden");
1918    btnCartDisable.addClass("hidden");
1919    btnOptionNotSelected.addClass("hidden");
1920
1921    if (countSizes[optionSelected] < 2) {
1922      $(sizeItem).first().click();
1923    } else {
1924      dropdownTamanho.html(
1925        'Tamanho <span><i class="fa fa-angle-down"></i></span>'
1926      );
1927      btnSizeNotSelected.removeClass("hidden");
1928    }
1929    $(sizeItem).first().click();
1930  });
1931
1932  $(document).on("click", sizeItem, function (e) {
1933    e.preventDefault();
1934
1935    if ($(sizeItem).parents(".modal-body.wish").length > 0) {
1936      return;
1937    }
1938
1939    customization.clearSelect();
1940    $(sizeItem).removeClass("active");
1941    $(this).addClass("active");
1942
1943    if (optionSelected == null) {
1944      return;
1945    }
1946
1947    sizeSelected = $(this).attr("data-size");
1948    window.skuPrices = skusPrice;
1949
1950    if (modalClass) {
1951      modalOptionActive = $(".modal .options.sku li.active").attr(
1952        "data-option"
1953      );
1954      precoDe = skusPrice[modalOptionActive + "-" + sizeSelected.toString()][0];
1955      precoPor =
1956        skusPrice[modalOptionActive + "-" + sizeSelected.toString()][1];
1957
1958      $(".modal .prices__old-price span")[0].innerText = precoDe;
1959      $(".modal .prices__new-price span")[0].innerText = precoPor;
1960    } else {
1961      indexOptionActive = $(".options.sku li.active").attr("data-option");
1962      precoDe = skusPrice[indexOptionActive + "-" + sizeSelected.toString()][0];
1963      precoPor =
1964        skusPrice[indexOptionActive + "-" + sizeSelected.toString()][1];
1965
1966      if (
1967        $(".product-data .prices__old-price span")[0] &&
1968        $(".product-data .prices__new-price span")[0]
1969      ) {
1970        $(".product-data .prices__old-price span")[0].innerText = precoDe;
1971        $(".product-data .prices__new-price span")[0].innerText = precoPor;
1972      }
1973    }
1974
1975    var text = $(this).find("a").attr("data-value");
1976    dropdownTamanho.html(
1977      text + '  <span><i class="fa fa-angle-down"></i></span>'
1978    );
1979
1980    buyContent.find("[name=tamanho]").attr("value", sizeSelected);
1981
1982    if (
1983      unitStock[dataProduct][optionSelected][sizeSelected] > 0 ||
1984      unitStockControl[dataProduct][optionSelected][sizeSelected] == false
1985    ) {
1986      btnCart.removeClass("hidden");
1987      btnCartDisable.addClass("hidden");
1988      let sku = optionSelected + "/" + sizeSelected;
1989      $("#tamanhofrete").val(sizeContent);
1990      customization.changeUnit(sku, 1);
1991
1992      if (countOptions < 2 && countSizes[optionSelected] < 2) {
1993        $("[data-custom-adicionar]").on("change", function () {
1994          $(this).trigger("click");
1995        });
1996      }
1997    } else {
1998      btnCart.addClass("hidden");
1999
2000      let baseUrl = helper.getBaseUrl();
2001      baseUrl += "/ajax/produto?act=avisodisponivelmodal";
2002
2003      let noStockNotificationUrl =
2004        "&produto=" +
2005        idProduct +
2006        "&opcao=" +
2007        optionSelected +
2008        "&tamanho=" +
2009        sizeSelected;
2010
2011      let urlCartDisable = btnCartDisable.find("a");
2012      urlCartDisable.attr("data-href", baseUrl + noStockNotificationUrl);
2013
2014      btnCartDisable.removeClass("hidden");
2015    }
2016
2017    btnSizeNotSelected.addClass("hidden");
2018  });
2019
2020  if ($(".new-product-content").length) {
2021    $(optionItem).first().click();
2022  }
2023  if (countOptions < 2) {
2024    btnOptionNotSelected.addClass("hidden");
2025
2026    if (countOptions < 2 && countSizes[optionSelected] < 2) {
2027      $(".options-section").addClass("hidden");
2028    }
2029  }
2030};
2031
2032demo.getOptionHtml = function (unit, option, size) {
2033  var element = null;
2034  var stock = unit.estoque;
2035  var stockControl = unit.controlaEstoque == 1;
2036  var stockClass = "";
2037  var titleNoStock = "";
2038
2039  if (stock > 0 || stockControl == false) {
2040    stockClass = "in-stock";
2041    titleNoStock = "";
2042  } else {
2043    stockClass = "no-stock";
2044    titleNoStock = " (sem estoque)";
2045  }
2046
2047  var imagemCor = option.imagemCor ? option.imagemCor : "";
2048  var imagem = option.imagem ? option.imagem : "";
2049
2050  if (imagemCor || imagem) {
2051    element = `
2052			<span class="color" data-sku="${option.id}">
2053				<img src="${imagemCor || imagem}" alt="${option.descricao}${titleNoStock}" title="${
2054      option.descricao
2055    }"
2056				loading="lazy" width="100" height="100" />
2057			</span>
2058		`;
2059  } else if (option.corHexa != null && option.corHexa != "") {
2060    element = `
2061		<span class="color" data-sku="${option.id}" style="background-color: #${option.corHexa}"
2062		title="${option.descricao}${titleNoStock}"></span>
2063		`;
2064  } else {
2065    let optionImage = $("#urlsite").val() + "/static/img/semimagem.jpg";
2066    element = `
2067		<span class="color" data-sku="${option.id}">
2068				<img src="${optionImage}" alt="${option.descricao}" title="${option.descricao}${titleNoStock}"
2069				loading="lazy" width="100" height="100" />
2070		</span>
2071		`;
2072  }
2073
2074  var html = `
2075	<li data-option="${option.id}" class="">
2076		<a href="#" aria-label="${option.descricao}">
2077			${element}
2078		</a>
2079	</li>
2080	`;
2081
2082  return html;
2083};
2084
2085demo.getSizeHtml = function (unit, option, size) {
2086  var stock = unit.estoque;
2087  var stockControl = unit.controlaEstoque == 1;
2088  var stockClass = "";
2089
2090  if (stock > 0 || stockControl == false) {
2091    stockClass = "in-stock";
2092  } else {
2093    stockClass = "no-stock";
2094  }
2095
2096  var html = `
2097		<li role="presentation" class="hidden-xs ${stockClass} " data-size="${size.id}" data-option="${option.id}">
2098			<a class="tam change-select" href="#" aria-label="${size.descricao}" data-value="${size.descricao}">
2099				<span>${size.descricao}</span>
2100			</a>
2101		</li>
2102		<li role="presentation" class="visible-xs ${stockClass} " data-size="${size.id}" data-option="${option.id}">
2103			<a class="tam change-select" href="#" aria-label="${size.descricao}" data-value="${size.descricao}">
2104				<span>${size.descricao}</span>
2105			</a>
2106		</li>
2107	`;
2108
2109  return html;
2110};
2111
2112demo.generateAllUnits = function (idProductJson = "#skuProducts") {
2113  demo.startProductTip();
2114  demo.getProductSku(idProductJson);
2115  if ($('#exibiropcoesprodutonaslistas').length && $('#exibiropcoesprodutonaslistas').val() == 's') {
2116    productPage.handleSelectedProductOption();
2117  }
2118};
2119
2120demo.animatedHeadTitle = function () {
2121  let hiddenTitle = $("#alternative-title").val();
2122
2123  if (!hiddenTitle) {
2124    return;
2125  }
2126
2127  let title = document.title;
2128  let interval = null;
2129
2130  document.addEventListener("visibilitychange", function () {
2131    let counter = 0;
2132
2133    if (document.visibilityState === "visible") {
2134      if (interval != null) {
2135        clearInterval(interval);
2136      }
2137
2138      document.title = title;
2139      return;
2140    }
2141
2142    interval = setInterval(function () {
2143      counter++;
2144      if (counter % 2) {
2145        document.title = title;
2146        return;
2147      }
2148
2149      document.title = hiddenTitle;
2150    }, 1000);
2151  });
2152};
2153
2154demo.changeProductPriceCatalog = function (price) {
2155  if (price != undefined) {
2156    price = price.replace(/R\$ /, "");
2157    price = parseFloat(price.replace(/,/, "."));
2158    price = (price * 1).toFixed(2);
2159
2160    if (price != undefined) {
2161      $(".catalog .price").val(price);
2162      $(".catalog .original-value").val(price);
2163    }
2164  }
2165};
2166
2167demo.submenuOpacityEffect = function () {
2168  $(document).on("mouseenter", "header #menu", function () {
2169    $(".main-content-overlay").removeClass("hidden");
2170  });
2171  $(document).on("mouseleave", "header #menu", function () {
2172    $(".main-content-overlay").addClass("hidden");
2173  });
2174};
2175
2176demo.expandAsideFilters = function () {
2177  if ($(".new-category-background .new-filters__content").length) {
2178    $(".new-category-background .new-filters__content .submenu").each(function (
2179      index
2180    ) {
2181      var list = $(this);
2182      var seemore = list.next(".see-more-less");
2183      var itemHeight = list.find("li").outerHeight();
2184      var itemsQty = 3;
2185
2186      if (list.find("li").length <= itemsQty) {
2187        seemore.remove();
2188      } else {
2189        list.css("max-height", 120);
2190        list.find("li").css("height", itemHeight);
2191      }
2192      seemore.on("click", function () {
2193        list.toggleClass("expanded");
2194      });
2195    });
2196  }
2197};
2198
2199demo.executeFunctionsAfterAjaxIsLoaded = function () {
2200  $(document).on("ajaxcache.ended", function () {
2201    console.log("ajax templates ended");
2202  });
2203};
2204
2205demo.getHashParameters = function () {
2206  const hash = window.location.hash.substr(1);
2207
2208  let result = {};
2209  hash.split(";").map((item) => {
2210    var parts = item.split(":");
2211    result[parts[0]] = parts[1];
2212    return result;
2213  });
2214
2215  if (result.sellerId != undefined) {
2216    demo.addSellerIdToCookies(result.sellerId);
2217  }
2218};
2219
2220demo.addSellerIdToCookies = function (sellerId) {
2221  if (!sellerId) {
2222    return;
2223  }
2224
2225  let expires = new Date();
2226  expires.setDate(expires.getDate() + 7);
2227
2228  document.cookie = `vendedorAtualId=${sellerId}; path=/; expires=${expires}`;
2229};
2230
2231demo.validateFormNewsletter = function () {
2232  const btnEnviar = $("#btn-validate-newsletter");
2233  const nameNewsletter = $(".name-newsletter");
2234  const emailNewsletter = $(".email-newsletter");
2235  const checkboxNewsletter = $("#check-validate-newsletter");
2236  let nameCheck = false;
2237  let emailCheck = false;
2238
2239  function validateTermNewsletter() {
2240    checkboxNewsletter.is(":checked") && nameCheck && emailCheck
2241      ? btnEnviar.prop("disabled", false)
2242      : btnEnviar.prop("disabled", true);
2243  }
2244
2245  nameNewsletter.on("input", function (e) {
2246    e.stopPropagation();
2247
2248    $(this).val() ? (nameCheck = true) : (nameCheck = false);
2249
2250    validateTermNewsletter();
2251  });
2252
2253  emailNewsletter.on("input", function (e) {
2254    e.stopPropagation();
2255
2256    $(this).val() ? (emailCheck = true) : (emailCheck = false);
2257
2258    validateTermNewsletter();
2259  });
2260
2261  checkboxNewsletter.on("click", function (e) {
2262    e.stopPropagation();
2263    validateTermNewsletter();
2264  });
2265};
2266
2267demo.updateItemCount = function () {
2268  const itemList = document.querySelectorAll("#itemList li");
2269  const count = itemList.length;
2270  const verMaisBtn = document.getElementById("verMaisBtn");
2271  verMaisBtn.textContent = `Ver mais (${count})`;
2272};
2273
2274demo.panelEventsFastcart = function () {
2275  $("#calculate-freight-header").on("click", function (e) {
2276    e.preventDefault();
2277    demo.calculateFreightHeader();
2278  });
2279  $("#header-zipcode").on("keypress", function (e) {
2280    if (e.which === 13) {
2281      e.preventDefault();
2282      demo.calculateFreightHeader();
2283    }
2284  });
2285  $("#header-zipcode").on("input", function () {
2286    var valor = $(this).val();
2287    valor = valor.replace(/[^0-9.-]/g, "");
2288    $(this).val(valor);
2289  });
2290  
2291  $("#apply-coupon-header").on("click", function (e) {
2292    e.preventDefault();
2293    demo.applyCouponHeader();
2294  });
2295  $("#header-coupon").on("keypress", function (e) {
2296    if (e.which === 13) {
2297      e.preventDefault();
2298      demo.applyCouponHeader();
2299    }
2300  });
2301}
2302
2303demo.checkStopwatch = function (modal = false) {
2304  if (modal) {
2305    var productModalContainer = $(".modal-content.fast-shopping");
2306    if (
2307      productModalContainer.length > 0 &&
2308      productModalContainer.find(".stopwatch-product-timer").length > 0
2309    ) {
2310      productModalContainer.find(".stopwatch-product-timer").remove();
2311    }
2312  }
2313
2314  var productContainer = $("#product-top");
2315  if (
2316    productContainer.length > 0 &&
2317    productContainer.find(".stopwatch-product-timer").length > 0
2318  ) {
2319    productContainer.find(".stopwatch-product-timer").remove();
2320  }
2321};
2322
2323demo.clientLoginWarning = function () {
2324		setTimeout(function() {
2325			var perfilLogado = $('.new-header__client-area__login .menu-login');
2326			var perfilLogadoMobile = $('.new-mobile-menu__header .menu-login');
2327
2328      if (!perfilLogado && !perfilLogadoMobile) {
2329        return
2330      }
2331
2332			if (!perfilLogado.length > 0 || !perfilLogadoMobile.length > 0) {
2333				$('form .new-product-inner__thumb__buttons').addClass('hidden');
2334				$('form .btn-cart-atacado-container').addClass('hidden');
2335				$('.product-scroll-bar .product-top-button').addClass('hidden');
2336				$('#product-top .stopwatch-content').addClass('hidden');
2337				$('#product-top .btn-cart-able .btn-cart-atacado-container').addClass('hidden');
2338				$('.stopwatch-content').addClass('hidden');
2339				$('.button-buy-cart--list').addClass('hidden');
2340				$('.login-warning').removeClass('hidden');
2341			} else {
2342				$('form .new-product-inner__thumb__buttons').removeClass('hidden');
2343				$('form .btn-cart-atacado-container').removeClass('hidden');
2344				$('.product-scroll-bar .product-top-button').removeClass('hidden');
2345				$('#product-top .stopwatch-content').removeClass('hidden');
2346				$('#product-top .btn-cart-able .btn-cart-atacado-container').removeClass('hidden');
2347				$('.stopwatch-content').removeClass('hidden');
2348				$('.button-buy-cart--list').removeClass('hidden');
2349				$('.login-warning').addClass('hidden');
2350				X.post($('#urlajax').val() + '/produto.php?act=exibiPrecoClienteLogado');
2351			}
2352		}, 300);
2353}
2354
2355demo.calculatePriceDiscountOnProductListPromotion = function() {
2356	const productList = $('.product-inner');
2357
2358	if (productList.length == 0) {
2359		return;
2360	}
2361
2362	productList.each(function(index, item) {
2363		const productItem = $(item);
2364    const elementText = productItem.find('.new-product-inner__thumb__seals .porcentagem-produto');
2365    if (elementText.length == 0) {
2366      return;
2367    }
2368		demo.calculeDiscount(productItem, elementText);
2369	});
2370}
2371
2372demo.calculatePriceDiscountOnProductList = function() {
2373	const productList = $('.new-product-inner');
2374
2375	if (productList.length == 0) {
2376		return;
2377	}
2378
2379	productList.each(function(index, item) {
2380		const productItem = $(item);
2381    const elementText = productItem.find('.new-product-inner__thumb__seals .porcentagem-produto');
2382    if (elementText.length == 0) {
2383      return;
2384    }
2385		demo.calculeDiscount(productItem, elementText);
2386	});
2387}
2388
2389demo.calculePriceDiscountOnProduct = function() {
2390  let productContent = ''
2391  if (window.innerWidth < 1101) {
2392    productContent = $(".new-product-content");
2393  } else {
2394    productContent = $("#product-top");
2395  }
2396  const elementText = productContent.find('.product-data__container__tags .porcentagem-produto');
2397
2398	if (productContent.length == 0 || elementText.length == 0) {
2399		return;
2400	}
2401
2402  demo.calculeDiscount(productContent, elementText);
2403}
2404
2405demo.calculeDiscount = function(element, elementText) {
2406  if (!element.find("input[name='valorPor']").length || !element.find("input[name='valorDe']").length) {
2407    elementText.addClass("hidden");
2408    return
2409  }
2410
2411  var valorPor = parseFloat(
2412      element.find("input[name='valorPor']").val()
2413        .replace('R$ ', '')
2414        .replace(/\./g, '')
2415        .replace(/,/, '.')
2416  );
2417
2418  var valorDe = parseFloat(
2419      element.find("input[name='valorDe']").val()
2420        .replace('R$ ', '')
2421        .replace(/\./g, '')
2422        .replace(/,/, '.')
2423  );
2424
2425  if (!valorDe || valorDe === 0 || !valorPor) {
2426    elementText.addClass("hidden");
2427      return;
2428  }
2429
2430  var descontoPorcentagem = 100 - ((valorPor * 100) / valorDe);
2431  var descontoArredondado = Math.round(descontoPorcentagem);
2432  if (!descontoPorcentagem) {
2433    elementText.addClass("hidden");
2434    return
2435  }
2436
2437  elementText.text('- ' + descontoArredondado + '%'); 
2438}
2439
2440demo.verifyImageFastCart = function() {
2441  const imageUnits = document.querySelectorAll('input[name="imagemUnidadeFastCart"]');
2442  const imageProducts = document.querySelectorAll('input[name="imagemProdutoFastCart"]');
2443  const imgElementIds = document.querySelectorAll('input[name="idProdutoFastCart"]');
2444  const urlSite = document.getElementById("urlsite");
2445
2446  if (imageUnits.length !== imageProducts.length || imageUnits.length !== imgElementIds.length) {
2447    console.error("Os arrays de imagens e IDs não têm o mesmo comprimento.");
2448    return;
2449  }
2450
2451  for (let i = 0; i < imageUnits.length; i++) {
2452    let imageUnit = imageUnits[i]?.value || '';
2453    let imageProduct = imageProducts[i]?.value || '';
2454    let imgElementId = imgElementIds[i]?.value || '';
2455
2456    const imgElement = document.getElementById(imgElementId);
2457    const defaultImageUrl = urlSite.value + "/static/img/semimagem.jpg";
2458
2459    if (!imgElement) {
2460      console.error(`Elemento de imagem do carrinho rápido não foi encontrado.`);
2461      return;
2462    }
2463
2464    if (imageUnit && !imageUnit.includes("semimagem.jpg")) {
2465        imgElement.src = imageUnit;
2466    } else if (imageProduct && !imageProduct.includes("semimagem.jpg")) {
2467        imgElement.src = imageProduct;
2468    } else {
2469        imgElement.src = defaultImageUrl;
2470    }
2471  }
2472}
2473
2474demo.runFunctionsAfterFirstInteraction = function () {
2475  lazyLoadService.loadNoScriptHtml();
2476  if (window.innerWidth < 992) {
2477    lazyLoadService.loadNoScriptHtml("lazyload-html-mobile");
2478    demo.mainBannersMobile();
2479  } else {
2480    lazyLoadService.loadNoScriptHtml("lazyload-html-desktop");
2481    demo.mainBanners();
2482  }
2483
2484  demo.updateCart();
2485  demo.panelEventsFastcart();
2486  demo.showcategorieDesktop();
2487  demo.benefitsCarousel();
2488  demo.initializeProductListCarousel(true);
2489  demo.promotionCarousel();
2490  demo.changeQuantity();
2491  demo.recentPostCarousel();
2492  demo.instagramCarousel();
2493  demo.productSuppliersCarousel();
2494  demo.showSuppliers();
2495  demo.categoryBanner();
2496  demo.checkBuyBrandsSupplier();
2497  demo.buyForBrandCarousel();
2498  demo.bannersMiddle();
2499  demo.bannersBottom();
2500  demo.generateAllUnits();
2501  demo.calculatePriceDiscountOnProductList();
2502  demo.calculePriceDiscountOnProduct();
2503  demo.calculateFreightProduct();
2504}
2505
2506demo.lazyloadFunctions = function () {
2507  demo.checkStopwatch();
2508  timer.dataTimer();
2509  //não exibi produto bannerPromocao se nao possui cronometro ou cronometro zerado
2510  // demo.checkStopwatchPromotion();
2511
2512  demo.backTop();
2513  demo.equalizeColumns();
2514  demo.slideBackTop();
2515  demo.openTrackingURL();
2516  demo.goBackPage();
2517  demo.showTooltip();
2518  demo.enableTooltip();
2519  demo.footerSectionsMobile();
2520
2521  demo.submenuOpacityEffect();
2522  demo.getHashParameters();
2523  demo.validateFormNewsletter();
2524  demo.animatedHeadTitle();
2525  demo.expandAsideFilters();
2526  // demo.clientLoginWarning();
2527};
2528
2529$(function () {
2530  demo.cartPanel();
2531  //new index
2532  demo.menuMobile();
2533  demo.hoverOnCategoryDesktop();
2534  demo.addProductToCartEvent();
2535  demo.addProductToWishList();
2536  demo.executeFunctionsAfterAjaxIsLoaded();
2537  // demo.clientLoginWarning(); remoção - alterar via css
2538  demo.initializeProductListCarousel(false);
2539
2540  lazyLoadService.addFunctionToQueueAfterInteraction(demo.runFunctionsAfterFirstInteraction);
2541	lazyLoadService.addFunctionToQueue(demo.lazyloadFunctions);
2542
2543  setTimeout(demo.equalizeColumns, 1000);
2544
2545  $(window).on("resize", demo.equalizeColumns);
2546  $(window).on("resize", demo.resizeAutocompleteResults);
2547});
2548
2549(function(w,d,s,l,i){
2550    w[l]=w[l]||[];
2551    w[l].push({'gtm.start': new Date().getTime(), event:'gtm.js'});
2552    var f = d.getElementsByTagName(s)[0],
2553        j = d.createElement(s),
2554        dl = l != 'dataLayer' ? '&l='+l : '';
2555    j.async = true;
2556    j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
2557    if(d.head){
2558        d.head.appendChild(j);
2559    } else if(f && f.parentNode){
2560        f.parentNode.insertBefore(j, f);
2561    } else {
2562        d.body.appendChild(j);
2563    }
2564})(window, document, 'script', 'dataLayer', 'GTM-TQZ5GKLL');

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.