1function parseMadesaCartAjaxI18n(){var defaults={toast_cross_sell_added:"Product added to cart!",toast_cross_sell_error:"Could not add the product to your cart. Please try again."},el=document.getElementById("madesa-cart-ajax-i18n");if(!el||!String(el.textContent||"").trim())return defaults;try{var parsed=JSON.parse(el.textContent),out={},k;for(k in defaults)out[k]=parsed[k]!=null&&parsed[k]!==""?parsed[k]:defaults[k];for(k in parsed)Object.prototype.hasOwnProperty.call(out,k)||(out[k]=parsed[k]);return out}catch{return defaults}}var MadesaCartAjaxI18n=parseMadesaCartAjaxI18n();class Cart extends HTMLElement{constructor(){super(),this.sectionId=this.dataset.sectionId}cartUpdate(itemCount=null){let pageCart,url;this.sectionId?(pageCart=document.querySelector(".minicart-drawer__inner"),url=`cart?section_id=${this.sectionId}`):(pageCart=document.querySelector("#page-cart"),url="/cart"),fetch(url).then(response=>response.text()).then(responseText=>{const html=new DOMParser().parseFromString(responseText,"text/html");let newPageCart;if(this.sectionId?newPageCart=html.querySelector(".minicart-drawer__inner"):newPageCart=html.querySelector("#page-cart"),pageCart&&newPageCart){pageCart.innerHTML=newPageCart.innerHTML,itemCount!=null?updateCartCounters(itemCount):updateCartCounters();const cartUpdateEvent=new CustomEvent("cart:updated",{bubbles:!0,detail:{sectionId:this.sectionId}});document.dispatchEvent(cartUpdateEvent)}}).catch(e=>{console.error("Erro ao atualizar carrinho:",e)})}}function isMainCartPageForTracking(){const path=window.location.pathname.replace(/\/+$/,"")||"/";return path==="/cart"||path.endsWith("/cart")}function buildRemoveFromCartPayloadFromManager(hostEl,prevQty,newQty){const prev=Number(prevQty),next=Number(newQty);if(!Number.isFinite(prev)||!Number.isFinite(next)||prev<=next)return null;const removed=prev-next,variantId=hostEl.dataset.lineVariantId||"",productId=hostEl.dataset.lineProductId||"",finalLineCents=parseInt(hostEl.dataset.lineFinalPrice||"0",10)||0,titleEl=hostEl.querySelector(".cart-item__name"),itemName=titleEl&&titleEl.textContent?titleEl.textContent.trim():"",unitMajor=prev>0?finalLineCents/prev/100:0;return{value:Math.round(unitMajor*removed*100)/100,items:[{item_id:String(variantId||productId||""),item_name:itemName,quantity:removed,price:Math.round(unitMajor*100)/100}]}}function buildRemoveFromCartPayloadForFullClear(){const managers=document.querySelectorAll("#page-cart cart-item-manager");if(!managers.length)return null;const items=[];let totalValue=0;for(let i=0;i<managers.length;i++){const hostEl=managers[i];if(!(hostEl instanceof HTMLElement))continue;const prevQty=parseInt(hostEl.dataset.lineQty||hostEl.dataset.quantity||"0",10)||0;if(prevQty<=0)continue;const part=buildRemoveFromCartPayloadFromManager(hostEl,prevQty,0);part&&part.items&&part.items[0]&&(items.push(part.items[0]),totalValue+=part.value)}return items.length?{value:Math.round(totalValue*100)/100,items}:null}class CartItemManager extends Cart{constructor(){super()}connectedCallback(){this.variantKey=this.dataset.variantKey,this.currentQuantity=parseInt(this.dataset.quantity),this.productPlus=this.querySelector('[data-action="increase"]'),this.productMinus=this.querySelector('[data-action="decrease"]'),this.btnRemove=this.querySelector('[data-action="remove"]'),this.productQtda=this.querySelector("[data-quantity-input]"),this.init()}init(){this.btnRemove&&this.btnRemove.addEventListener("click",this.removeProduct.bind(this)),this.productPlus&&this.productPlus.addEventListener("click",this.plusProductQtda.bind(this)),this.productMinus&&this.productMinus.addEventListener("click",this.minusProductQtda.bind(this)),this.productQtda&&this.productQtda.addEventListener("change",this.productChange.bind(this))}cartChange(variantKey,qtda,quantityBefore){this.setControlsDisabled(!0);const previousQty=quantityBefore!=null?Number(quantityBefore):this.currentQuantity,newQty=Number(qtda);let removePayload=null;isMainCartPageForTracking()&&typeof window.trackEvent=="function"&&!this.sectionId&&(removePayload=buildRemoveFromCartPayloadFromManager(this,previousQty,newQty));const brinde=window.MadesaBrinde,request=brinde&&typeof brinde.buildCartLineChangeFromDom=="function"?brinde.buildCartLineChangeFromDom(variantKey,newQty):{mode:"change",id:variantKey,quantity:newQty},url=request.mode==="update"?"/cart/update.js":"/cart/change.js",body=request.mode==="update"?JSON.stringify({updates:request.updates}):JSON.stringify({id:request.id,quantity:request.quantity});fetch(url,{method:"POST",headers:{"Content-Type":"application/json"},body}).then(response=>response.json()).then(data=>{brinde&&typeof brinde.applyCartMutationResponse=="function"&&brinde.applyCartMutationResponse(data),removePayload&&typeof window.trackEvent=="function"&&(data.currency&&(removePayload.currency=data.currency),window.trackEvent("remove_from_cart",removePayload)),updateCartCounters(data.item_count),this.cartUpdate(data.item_count)}
1).catch(error=>{console.error("Erro ao modificar carrinho:",error),this.setControlsDisabled(!1)})}setControlsDisabled(disabled){this.productPlus&&(this.productPlus.disabled=disabled),this.productMinus&&(this.productMinus.disabled=disabled),this.productQtda&&(this.productQtda.disabled=disabled)}removeProduct(){this.cartChange(this.variantKey,0)}plusProductQtda(){const prev=this.currentQuantity,newValue=prev+1;this.currentQuantity=newValue,this.cartChange(this.variantKey,newValue,prev)}minusProductQtda(){if(this.currentQuantity>1){const prev=this.currentQuantity,newValue=prev-1;this.currentQuantity=newValue,this.cartChange(this.variantKey,newValue,prev)}}productChange(event){const target=event.currentTarget,newValue=parseInt(target.value)||1;if(newValue<1){target.value=1;return}const prev=this.currentQuantity;this.currentQuantity=newValue,this.cartChange(this.variantKey,newValue,prev)}}class CartCrossSellItem extends Cart{constructor(){super()}connectedCallback(){this.variantId=this.dataset.variantId,this.btnAdd=this.querySelector('[data-action="add-to-cart"]'),this.init()}init(){this.btnAdd&&(this._boundAddToCart&&this.btnAdd.removeEventListener("click",this._boundAddToCart),this._boundAddToCart=this.addToCart.bind(this),this.btnAdd.addEventListener("click",this._boundAddToCart))}disconnectedCallback(){this.btnAdd&&this._boundAddToCart&&this.btnAdd.removeEventListener("click",this._boundAddToCart)}setAddLoading(isLoading){this.btnAdd&&(this.btnAdd.classList.toggle("is-loading",isLoading),this.btnAdd.setAttribute("aria-busy",isLoading?"true":"false"))}addToCart(event){if(event.preventDefault(),event.stopPropagation(),this.btnAdd.disabled)return;const brinde=window.MadesaBrinde,isBrindeVariant=brinde?.isBrindeVariant?.(this.variantId);if(isBrindeVariant&&brinde?.isAddLocked?.()){brinde.showError("already_in_cart");return}this.btnAdd.disabled=!0;const runAdd=()=>{this.setAddLoading(!0),fetch("/cart/add.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:this.variantId,quantity:1,...isBrindeVariant?{properties:{_brinde:"true"}}:{}})}).then(response=>response.json()).then(data=>{if(data.status&&data.status>=400)throw new Error(data.description||MadesaCartAjaxI18n.toast_cross_sell_error);isBrindeVariant&&brinde?.releaseBrindeAddSuccess?.(void 0,this.variantId),document.dispatchEvent(new CustomEvent("toast:show",{detail:{message:MadesaCartAjaxI18n.toast_cross_sell_added,type:"success"}})),document.dispatchEvent(new CustomEvent("cart:refresh")),this.setAddLoading(!1)}).catch(error=>{console.error("Erro ao adicionar ao carrinho:",error),isBrindeVariant&&brinde?.releaseBrindeAddFailed?.(),document.dispatchEvent(new CustomEvent("toast:show",{detail:{message:MadesaCartAjaxI18n.toast_cross_sell_error,type:"error"}})),this.setAddLoading(!1),brinde?.isAddLocked?.()||(this.btnAdd.disabled=!1)})};if(isBrindeVariant&&brinde?.validateBrindeAdd){if(!brinde.tryBeginBrindeAdd()){brinde.showError("already_in_cart");return}brinde.confirmBrindeAdd({variantId:this.variantId}).then(result=>{if(!result.ok){brinde.showError(result.reason||"already_in_cart"),brinde.isAddLocked()||(this.btnAdd.disabled=!1);return}runAdd()}).catch(()=>{brinde?.releaseBrindeAddFailed?.(),brinde?.isAddLocked?.()||(this.btnAdd.disabled=!1)});return}runAdd()}}class CartClearButton extends Cart{constructor(){super()}connectedCallback(){this.btnClear=this.querySelector('[data-action="clear-cart"]'),this.modal=this.querySelector("[data-clear-cart-modal]"),this.modalOverlay=this.querySelector("[data-modal-overlay]"),this.confirmBtn=this.querySelector('[data-action="confirm-clear"]'),this.cancelBtn=this.querySelector('[data-action="cancel-clear"]'),this.init()}init(){if(this.btnClear){const handler=this.modal?this.showModal.bind(this):this.clearCart.bind(this);this.btnClear.addEventListener("click",handler)}this.confirmBtn&&this.confirmBtn.addEventListener("click",this.clearCart.bind(this)),this.cancelBtn&&this.cancelBtn.addEventListener("click",this.hideModal.bind(this)),this.modalOverlay&&this.modalOverlay.addEventListener("click",this.hideModal.bind(this)),document.addEventListener("keydown",e=>{e.key==="Escape"&&this.modal&&this.modal.classList.contains("is-active")&&this.hideModal()})}showModal(event){event.preventDefault(),this.modal&&(this.modal.classList.add("is-active"),document.body.style.overflow="hidden")}hideModal(){this.modal&&(this.modal.classList.remove("is-active"),document.body.style.overflow="")}clearCart(event){event.preventDefault(),this.confirmBtn&&(this.confirmBtn.disabled=!0),this.modal&&this.hideModal();let removeAllPayload=null;isMainCartPageForTracking()&&typeof window.trackEvent=="function"&&(removeAllPayload=buildRemoveFromCartPayloadForFullClear()),fetch("/cart/clear.js",{method:"POST",headers:{"Content-Type":"application/json"}}).then(response=>response.json()).then(data=>{removeAllPayload&&typeof window.trackEvent=="function"&&(data.currency&&(removeAllPayload.currency=data.currency),window.trackEvent("remove_from_cart",removeAllPayload)),this.cartUpdate()}).catch(error=>{console.error("Erro ao limpar carrinho:",error),this.confirmBtn&&(this.confirmBtn.disabled=!1)})}}class CartButtonClose extends Cart{constructor(){super(),this.init()}init(){this.addEventListener("click",e=>{e.preventDefault(),document.dispatchEvent(new CustomEvent("minicart:close"))})}}class MinicartToggle extends Cart{constructor(){super(),this.addEventListener("click",this.toggle.bind(this)),this.selfHidden=!1}toggle(){const cartShipping=document.querySelector("cart-shipping");cartShipping&&(cartShipping.style.display=this.selfHidden?"block":"none");const cartCoupon=document.querySelector("cart-coupon");cartCoupon&&(cartCoupon.style.display=this.selfHidden?"block":"none"),this.selfHidden?this.classList.remove("in-hidden"):this.classList.add("in-hidden"),this.selfHidden=!this.selfHidden}}customElements.get("cart-item-manager")||customElements.define("cart-item-manager",CartItemManager),customElements.get("cart-cross-sell-item")||customElements.define("cart-cross-sell-item",CartCrossSellItem),customElements.get("cart-clear-button")||customElements.define("cart-clear-button",CartClearButton),customElements.get("cart-button-close")||customElements.define("cart-button-close",CartButtonClose),customElements.get("minicart-toggle")||customElements.define("minicart-toggle",MinicartToggle);function syncCartCountSession(itemCount){const count=Math.max(0,Number(itemCount)||0);try{sessionStorage.setItem("cart-count",JSON.stringify({value:String(count),timestamp:Date.now()}))}catch{}}function updateCartCounters(itemCount=null){return itemCount===null?fetch("/cart.js").then(response=>response.json()).then(cart=>(updateCartCountersDOM(cart.item_count),syncCartCountSession(cart.item_count),cart.item_count)).catch(error=>(console.error("Erro ao atualizar contadores:",error),null)):(updateCartCountersDOM(itemCount),syncCartCountSession(itemCount),Promise.resolve(itemCount))}function updateCartCountersDOM(itemCount){const count=Math.max(0,Number(itemCount)||0),displayValue=count>0?String(count):"";document.querySelectorAll("#header-group [data-cart-count]").forEach(el=>{el.textContent=displayValue,el.style.display=count>0?"":"none"}),document.querySelectorAll(".cart-count-bubble span, #cart-icon-bubble span, .header__icon--cart .cart-count-bubble").forEach(el=>{el.textContent=count>0&&count<100?String(count):"";const bubble=el.closest(".cart-count-bubble, .cart-bubble");bubble instanceof HTMLElement&&(bubble.classList.toggle("visually-hidden",count===0),bubble.classList.toggle("hidden",count===0))});const mobileCounter=document.querySelector(".madesa-mobile-cart-count");if(mobileCounter)mobileCounter.textContent=displayValue,mobileCounter.style.display=count>0?"":"none";else if(count>0){const mobileBtn=document.querySelector(".madesa-mobile-cart-btn");if(mobileBtn){const span=document.createElement("span");span.className="madesa-mobile-cart-count",span.textContent=displayValue,mobileBtn.appendChild(span)}}}document.addEventListener("cart:refresh",event=>
1{const skipCookie=typeof window.madesaShouldSkipCookieDiscount=="function"&&window.madesaShouldSkipCookieDiscount(),waitForCookie=!skipCookie&&typeof window.madesaHasPdpCouponIntent=="function"&&window.madesaHasPdpCouponIntent(),applyDiscount=skipCookie?Promise.resolve():waitForCookie&&typeof window.madesaApplyCookieDiscountWhenReady=="function"?window.madesaApplyCookieDiscountWhenReady({maxWait:1800,interval:50}):typeof window.madesaApplyCookieDiscount=="function"?window.madesaApplyCookieDiscount():Promise.resolve(),shouldRevealCoupon=event&&event.detail&&event.detail.revealCoupon===!0||waitForCookie;applyDiscount.finally(()=>refreshCart()).then(()=>{shouldRevealCoupon&&typeof window.madesaRevealCartCouponUI=="function"&&window.madesaRevealCartCouponUI()})}),document.addEventListener("cart:updated",()=>{setTimeout(()=>{const totalElement=document.querySelector("[data-installment-base-cents], [data-base-total-cents]");if(totalElement){const totalCents=parseInt(totalElement.getAttribute("data-installment-base-cents")||totalElement.getAttribute("data-base-total-cents"),10);isNaN(totalCents)||window.updateInstallmentsDisplay(totalCents)}},100)});function refreshCart(sectionId=null,options={}){const openMinicart=options.openMinicart!==!1,tasks=[],minicartContainer=document.querySelector(".minicart-drawer__inner");if(minicartContainer){const minicartSection=minicartContainer.closest("[data-section-id]"),sectionIdToUse=minicartSection?minicartSection.dataset.sectionId:sectionId;sectionIdToUse&&tasks.push(fetch(`/cart?section_id=${sectionIdToUse}`).then(response=>response.text()).then(html=>{const newContent=new DOMParser().parseFromString(html,"text/html").querySelector(".minicart-drawer__inner");newContent&&(minicartContainer.innerHTML=newContent.innerHTML,document.dispatchEvent(new CustomEvent("cart:updated",{bubbles:!0,detail:{sectionId:sectionIdToUse}})))}).catch(error=>console.error("Erro ao atualizar minicart:",error)))}const pageCart=document.querySelector("#page-cart");return pageCart&&tasks.push(fetch("/cart").then(response=>response.text()).then(html=>{const newContent=new DOMParser().parseFromString(html,"text/html").querySelector("#page-cart");newContent&&(pageCart.innerHTML=newContent.innerHTML,document.dispatchEvent(new CustomEvent("cart:updated",{bubbles:!0,detail:{sectionId:null}})))}).catch(error=>console.error("Erro ao atualizar p\xE1gina do carrinho:",error))),(tasks.length?Promise.all(tasks):Promise.resolve()).then(()=>updateCartCounters()).finally(()=>{openMinicart&&window.Minicart&&typeof window.Minicart.open=="function"&&window.Minicart.open()})}window.addEventListener("pageshow",event=>{event.persisted&&updateCartCounters()}),window.refreshCart=refreshCart,window.updateCartCounters=updateCartCounters,window.calculateInstallments=function(totalCents){const minInstallmentValue=(window.themeSettings?.installment_min_price||100)*100,maxInstallments=window.themeSettings?.installment_max_count||12,allowedCounts=String(window.themeSettings?.installment_allowed_counts||"").split(",").map(item=>parseInt(item.trim(),10)).filter(item=>Number.isInteger(item)&&item>=1);let maxPossibleInstallments=Math.floor(totalCents/minInstallmentValue);if(maxPossibleInstallments>maxInstallments&&(maxPossibleInstallments=maxInstallments),maxPossibleInstallments<1&&(maxPossibleInstallments=1),allowedCounts.length){const bestAllowed=allowedCounts.filter(item=>item<=maxPossibleInstallments).sort((a,b)=>b-a)[0];bestAllowed&&(maxPossibleInstallments=bestAllowed)}const installmentValue=Math.round(totalCents/maxPossibleInstallments);return{count:maxPossibleInstallments,value:installmentValue}},window.updateInstallmentsDisplay=function(totalCents){document.querySelectorAll("[data-installment-info]").forEach(element=>{const{count,value}=window.calculateInstallments(totalCents);element.setAttribute("data-installment-count",count),element.setAttribute("data-installment-value",value);const countDisplay=element.querySelector("[data-installment-count-display]"),valueDisplay=element.querySelector("[data-installment-value-display]");if(countDisplay&&(countDisplay.textContent=`${count}x`),valueDisplay){const formatted=new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"}).format(value/100);valueDisplay.textContent=formatted}})},document.addEventListener("toast:show",event=>{const{message,type="success",duration=3e3}=event.detail;showToast(message,type,duration)});function showToast(message,type="success",duration=3e3){let toastContainer=document.getElementById("toast-container");if(!toastContainer){const style=document.createElement("style");style.textContent=` 2 #toast-container { 3 position: fixed; 4 bottom: 20px; 5 left: 20px; 6 z-index: 9999; 7 display: flex; 8 flex-direction: column; 9 gap: 10px; 10 pointer-events: none; 11 } 12 13 .toast { 14 padding: 12px 20px; 15 border-radius: 4px; 16 font-size: 14px; 17 font-weight: 500; 18 box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2); 19 pointer-events: auto; 20 cursor: pointer; 21 animation: slideInRight 0.3s ease-in-out; 22 } 23 24 .toast-success { 25 background-color: #4CAF50; 26 color: #ffffff; 27 } 28 29 .toast-error { 30 background-color: #f44336; 31 color: #ffffff; 32 } 33 34 .toast-info { 35 background-color: #2196F3; 36 color: #ffffff; 37 } 38 39 .toast-remove { 40 animation: slideOutRight 0.3s ease-in-out forwards; 41 } 42 43 @keyframes slideInRight { 44 from { 45 transform: translateX(100%); 46 opacity: 0; 47 } 48 to { 49 transform: translateX(0); 50 opacity: 1; 51 } 52 } 53 54 @keyframes slideOutRight { 55 from { 56 transform: translateX(0); 57 opacity: 1; 58 } 59 to { 60 transform: translateX(100%); 61 opacity: 0; 62 } 63 } 64 `,document.head.appendChild(style),toastContainer=document.createElement("div"),toastContainer.id="toast-container",document.body.appendChild(toastContainer)}const toast=document.createElement("div");toast.className=`toast toast-${type}`,toast.textContent=message,toastContainer.appendChild(toast),setTimeout(()=>{toast.classList.add("toast-remove"),setTimeout(()=>{toast.remove()},300)},duration),toast.addEventListener("click",()=>{toast.classList.add("toast-remove"),setTimeout(()=>{toast.remove()},300)})} 65//# sourceMappingURL=/cdn/shop/t/29/assets/madesa-cart-ajax.js.map?v=100189038812251414631791468692
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.