/*File:~/Custom/Content/Themes/Shared/Scripts/delivery.flags.js*/
try{try {
    document.addEventListener('DOMContentLoaded', async function () {
        let postalCodeRanges = [];

        async function loadPostalCodeRanges() {
            if (postalCodeRanges.length === 0) {
                const data = await $.getJSON('/Custom/Content/Themes/Shared/Json/ceps.min.json');
                postalCodeRanges = data.map(item => ({
                    ini: parseInt(item.ini),
                    end: parseInt(item.end)
                }));
            }
        }

        function isPostalCodeInRange(cep) {
            cep = parseInt(cep.replace(/\D/g, ''));
            return postalCodeRanges.some(range => cep >= range.ini && cep <= range.end);
        }

        const postalCodeStored = localStorage.getItem('myPostalCode');
        if (postalCodeStored) {
            await loadPostalCodeRanges();
            const check = isPostalCodeInRange(postalCodeStored);
            localStorage.setItem('isPostalCodeValid', check);
            $('body').attr('data-postal-code-in-range', check);
        }

        $.subscribe('/set/postalCode', async (e, postalCode) => {
            localStorage.setItem('myPostalCode', postalCode);
            await loadPostalCodeRanges();
            const check = isPostalCodeInRange(postalCode);
            localStorage.setItem('isPostalCodeValid', check);
            $('body').attr('data-postal-code-in-range', check);
        });
    });
} catch (error) {
    console.error(error);
}

//# sourceMappingURL=delivery.flags.js.map

}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Themes/Havanna/Scripts/mini-cart.js*/
try{ var updateMiniCart;
 var  miniCart;
 

    Vue.component('minicart', {
        props:['Basket','Installments'],
        data(){
            return{
            Items:[],
            url:browsingContext.Common.Urls.BaseUrl,
            CDN:browsingContext.Common.ImagesPath,
            previousQuantities: {},
            CalculatorFrete:false,
            SelectedDeliveryOption: null,
            PageParameters:null,
            IsPostalCode:false,
            percentFrete:0,
            isCoupom:false,
            CouponCode:'',
            Locations:[],
            changeLocation:false,
            }
        },
        async created(){
            $('#mini-cart').addClass('loading')
           this.resumeCart();
        },
        template: '#mini-cart-template',
        methods: {
            IsFrete(){
                this.CalculatorFrete=true;
            },

            applyMask(event) { 
                let value = event.target.value.replace(/\D/g, '');
                 if (value.length > 5) {
                     value = value.slice(0, 5) + '-' + value.slice(5);
                } 
                this.postalcode = value; 
            },
            easy(){
                window.location.href = this.url+'carrinho';
            },
            returncart(){
                $('body').removeClass('blocked modal-mini-cart');
            },
            async resumeCart(){
                const response = await $.ajax({
                    url: browsingContext.Common.Urls.BaseUrl + 'resumo-carrinho?_=' + new Date().getTime(),
                   
                });
                const {Basket, PageParameters,Installments} = JSON.parse(response)
                this.Basket=Basket;
      console.log("Basket ================>", this.Basket);

                this.Installments=Installments;
                //console.log(Installments, this.Installments);
                this.Items = Basket ? Basket.Items : [];
                this.PageParameters = PageParameters
                
                this.isCoupom = Basket?.CouponCode ? true : false;
                // if(!this.isCoupom){
                //     this.isCoupom = Basket?.GiftCertificates?.length ? true : false;
                // }
                console.log(this.isCoupom)
                this.SelectedDeliveryOption=Basket?.SelectedDeliveryOption ? Basket?.SelectedDeliveryOption.DeliveryOptionID : null;
                if(Basket?.DeliveryGroups[0]?.DeliveryOptions?.filter(option => option.Alias == 'PICKUP').length > 0){
                    this.Locations  = Basket?.DeliveryGroups[0]?.DeliveryOptions?.filter(option => option.Alias == 'PICKUP')[0].PointOfSales;
                }
                this.previousQuantities = this.Items.reduce((acc, item) => {
                    acc[item.BasketItemID] = item.Quantity;
                    return acc;
                }, {});
               
                $('#mini-cart').removeClass('loading')
            },
            discount(product){
                const value = ((product.ListPrice-product.RetailPrice)/product.ListPrice)*100;
                return value.toFixed(0);
            },
            truncateText(text){
                if (text.length <= 70) return text;
                return text.slice(0, 70) + '...';
            },
            imageProduct(image){
                return this.CDN.Product.Cdn.replace(this.CDN.Product.Match,'')+image;
            },
            async removeItem(BasketItemID){
                console.log('remover',BasketItemID);
                $('#mini-cart').addClass('loading')
                const response = await $.ajax({
                    url: browsingContext.Common.Urls.BaseUrl + 'carrinho/remover-produto',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        BasketItemID
                    }
                })
                if (response.IsValid) {
                    $('#mini-cart').removeClass('loading')
                    await this.resumeCart();
                    this.BestPrices();
                }
            },
           async update(BasketItemID, Quantity){
                $('#mini-cart').addClass('loading')
                const response = await $.ajax({
                    url: browsingContext.Common.Urls.BaseUrl + 'carrinho/alterar-quantidade',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        BasketItemID,
                        Quantity
                    }
                });
                if (response.IsValid) {
                      this.resumeCart();
                }else{
                    $(`.details [data-basket=${BasketItemID}]`).text(response.Errors[0].ErrorMessage).show();
                    setTimeout(()=>{
                        $(`.details [data-basket=${BasketItemID}]`).fadeOut("slow");
                    },2000)
                    product.Quantity=oldQuantity;
                    console.log(response.Errors[0].ErrorMessage);
                    $('#mini-cart').removeClass('loading')
                }  
            },
            formatToCurrency(value) {
                if(value==0){
                    return 'Grátis'
                }
                return value.toLocaleString('pt-BR', {
                  style: 'currency',
                  currency: 'BRL',
                });
              },
            formattedPrice(value, type = 0) {
                const formatter = new Intl.NumberFormat('pt-BR', {
                  style: 'decimal',
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2
                });
                let formattedValue = formatter.format(value);
                const [integerPart, decimalPart] = formattedValue.split(',');
                var styledIntegerPart;
                if(type!=0){
                    styledIntegerPart = `<span class="integer-part">de R$ ${integerPart}</span>`;
                }else{
                    styledIntegerPart = `<span class="integer-part">${integerPart}</span>`;
                }
                const styledDecimalPart = `<span class="decimal-part">,${decimalPart}</span>`;
                
                return `${styledIntegerPart}${styledDecimalPart}`;
              },
            async BestPrices(){
                $('#mini-cart').addClass('loading')
                if(this.Items.length < 1){
                    $('#mini-cart').removeClass('loading')
                    return
                }
                const products = this.Items.map(item => item.ProductID).join(';')
               
                const ProductList = await $.ajax({
                    url: browsingContext.Common.Urls.BaseUrl + `widget/product_list_by_id?Products=${products}&PageSize=999&RenderMode=json`,
                    type: 'get',
                });
                var Items = JSON.parse(ProductList).Products;
                for (let i = 0; i < Items.length; i++) {
                    const matchedItem = this.Items.find(item => item.ProductID === Items[i].ProductID);
                    if (matchedItem && Items[i].Price.BestInstallment != null) {
                        matchedItem.RetailPrice = Items[i].Price.BestInstallment.RetailPrice * matchedItem.Quantity;
                        matchedItem.ListPrice = matchedItem.ListPrice  * matchedItem.Quantity;
                    }
                }
                $('#mini-cart').removeClass('loading')
                return Items
            },

              async setPostalCode(e){
                e.preventDefault();
                $('#mini-cart').addClass('loading')
                const response = await $.ajax({
                    url: browsingContext.Common.Urls.BaseUrl + 'carrinho/definir-cep',
                    type: 'post',
                    cache: false,
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    data: {
                        postalCode: this.Basket.PostalCode,
                        latitude: 0,
                        longitude: 0
                    }
                })
                if(response.IsValid){
                    this.resumeCart();
                    
                }else{
                    $('#mini-cart').removeClass('loading')
                }
                return response
                
            },
            async setDeliveryOption(Alias, DeliveryOptionID, LocationID=null)  {
                if(Alias == 'PICKUP' ){
                    LocationID = this.Locations[0].PointOfSaleID
                    //return this.changeLocation=true;
                }
                groupKey = this.Basket.DeliveryGroups.GroupKey || 'DEFAULT';
                let data = {}
                if(LocationID != null){
                    data = {
                        DeliveryOptionID,
                        groupKey,
                        LocationID
                    }
                }else{
                    data = {
                        DeliveryOptionID,
                        groupKey
                    }
                }
                
                $('#mini-cart').addClass('loading')
                const response = await $.ajax({
                    url: browsingContext.Common.Urls.BaseUrl + 'carrinho/definir-opcao-entrega',
                    type: 'post',
                    dataType: 'json',
                    cache: false,
                   data
                })
                if(response.IsValid){
                    this.changeLocation=false;
                    this.resumeCart();
                    
                }else{
                    $('#mini-cart').removeClass('loading')
                }
            },
            alterLocation(){
                this.changeLocation=true; 
            },
            selectedLocation(Alias,DeliveryOptionID,LocationID){
                this.setDeliveryOption(Alias, DeliveryOptionID,LocationID)
            },
            alterCoupom(){
                this.isCoupom=true
            },
        
            async addCoupon (){
                $('.form-cupom','#mini-cart').addClass('loading');
                    const response = await linxCommerce.Basket.setCoupon({ CouponCode: this.CouponCode });
                if (response.IsValid && !response.Warnings.length) {
                    this.resumeCart();
                } else {
                    $('.callback', '#mini-cart .form-cupom').html(response.Errors.length ? response.Errors[0].ErrorMessage : response.Warnings[0].Message).show();
                    setTimeout(() => {
                        $('.callback', "#mini-cart .form-cupom").fadeOut(2000);
                    }, 2000)
                }
                $('.form-cupom','#mini-cart').removeClass('loading')
            }
        },
        watch: {
            Basket(newBasket) {
                this.Items = newBasket ? newBasket.Items : [];
                this.previousQuantities = this.Items.reduce((acc, item) => {
                    acc[item.BasketItemID] = item.Quantity;
                    return acc;
                }, {});
                this.IsPostalCode = newBasket.PostalCode ? true : false;
                this.BestPrices();
                $('#header .cart .total').text(newBasket.Items.length);
            },
            Installments(newInstallments) {
                this.Installments = newInstallments;
            },
        },
        computed:{
            QtdItems(){
                return this.Items ? this.Items.length : 0;
            },
            TotalFrete(){
                
                if(this.Basket.Total<this.PageParameters.value_freight){
                    this.percentFrete = Math.floor(( this.Basket.Total* 100)) / (this.PageParameters.value_freight);
                    return this.PageParameters.value_freight-this.Basket.Total;
                   
                }
                this.percentFrete=100;
                return 0;
            },
             Discounts (){
                let soma = 0;
                const itemDiscounts = this.Basket.ItemDiscounts;
                
                itemDiscounts.forEach(product => {
                    const subtotal = product.Item.Quantity * product.Amount;
                    soma += subtotal;
                });
                if(this.Installments?.VariationAmountPercentage != 0){
                    soma += this.Installments.VariationAmount;
                }
              this.Basket.GiftCertificates.forEach(d => {
                    soma += d.Amount;
                });
              //  if (Installments.VariationAmountPercentage !== 0) {
                //    soma += Installments.VariationAmount;
               // }
                return soma;
            },
            TotalProducts(){
                const soma = this.Basket.Items.reduce((acumulador, item) => {
                    return acumulador + (item.Quantity * item.ListPrice);
                }, 0);
                
                return this.formatToCurrency(soma);
            },
            BestPrice(){
                return this.formatToCurrency(this.Installments.Total);
            }
        },
      });
     
    
     miniCart = new Vue({
        el: '#app',
        data: {
            Basket: null,
            PageParameters: null,
            Installments: null
        },
    });

     updateMiniCart = async ()=>{
        const response = await $.ajax({
            url: browsingContext.Common.Urls.BaseUrl + 'resumo-carrinho?_=' + new Date().getTime(),
           
        });
        const {Basket, PageParameters,Installments} = JSON.parse(response);
        miniCart.Basket = Basket;
        miniCart.PageParameters = PageParameters;
        miniCart.Installments = Installments;
        //console.log(Installments,miniCart.Installments);
        return Basket;
    }

 
}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Themes/Havanna/Scripts/wishlist.js*/
try{let
    wishlists = null,
    lcWishlist = {};
try {

    const loadWishlist = async () => {
        if (browsingContext.Common.Shopper.IsAuthenticated) {
            const response = await $.ajax({
                url: browsingContext.Common.Urls.BaseUrl + 'painel-do-cliente/lista-de-desejo/listar',
                dataType: 'json'
            });
            $(response).each(function (index, value) {
                $(value.Products).each(function (index, value) {
                    const product_id = value.ProductID;
                    $(`.wd-product-line[data-product-id="${product_id}"] .btn-wishlist`).addClass('favorite');
                });
            });
            if (response.length == 1) {
                $('.add-product-wishlist input[name="WishlistID"]').each(function () {
                    $(this).val(response[0].WishlistID);
                });
            }
            wishlists = response;
        }
    }

    if (browsingContext.Common.ready) {
        loadWishlist()
    } else {
        $.subscribe('/wd/browsing/context/ready', () => {
            loadWishlist()
        })
    }

    const TEMPLATE_MODAL_ADD_TO_WISHLIST = `
    <template id="template-modal-add-to-wishlist">
        <form>
            <div class="input-wrapper">
                <label>Selecione a lista</label>
                <select name="WishlistID" required>
                    {{#each wishlists}}
                    <option value="{{WishlistID}}">{{Name}}</option>
                    {{/each}}
                </select>
            </div>
            <div class="input-wrapper">
                <label>Informe a quantidade</label>
                <input type="number" name="Quantity" value="1" required />
            </div>
            <button>Adicionar à lista</button>
        </form>
    </template>
    `

    $('body').append(TEMPLATE_MODAL_ADD_TO_WISHLIST)

    const applyBinds = ({ ProductID, SkuID }) => {
        if (browsingContext.Common.Shopper.IsAuthenticated) {
            if (wishlists.length) {
                let
                    source = $('#template-modal-add-to-wishlist').html(),
                    template = Handlebars.compile(source),
                    html = template({ wishlists })

                app.modal({
                    html,
                    customClass: 'modal-add-to-wishlist'
                })

                $('.modal-add-to-wishlist form').on('submit', async e => {
                    e.preventDefault()

                    $('.the-modal').addClass('loading')

                    const
                        form = e.currentTarget,
                        WishlistID = $('[name="WishlistID"]', form).val(),
                        Quantity = $('[name="Quantity"]', form).val()

                    const response = await lcWishlist.addToWishlist({
                        WishlistID,
                        ProductID,
                        Quantity,
                        SkuID
                    })

                    if (response.ServiceResponse.Data.IsValid) {
                        app.modal({
                            html: '<div>Produto adicionado a lista com sucesso!</div>'
                        });
                    } else {
                        const errors = response.ServiceResponse.Data.Errors.map(error => {
                            return `<p>${error.Message}</p>`
                        })

                        app.modal({
                            html: `
                            <div>
                                <strong>Ocorreu um erro ao adicionar o produto à lista</strong>
                            </div>
                            <div>
                                ${errors.join('')}
                            </div>
                            `
                        });
                    }

                    $('.the-modal').removeClass('loading')

                    console.log(WishlistID, ProductID, Quantity)

                })
            } else {
                app.modal({
                    html: `
                    <div>
                        <div class="message">Você não possui lista para adicionar produtos.</div>
                        <div class="button-wrapper">
                            <a href="${browsingContext.Common.Urls.Profile.AccountWishlist.Create}">Criar Lista</a>
                            <button  onclick="javascript: $.modal().close();" class="no">Fechar</button>
                        </div>
                    </div>`,
                    customClass: 'modal-no-wishlists'
                });
            }
        } else {
            //document.location.href = browsingContext.Common.Urls.Profile.Login.Index
            app.modal({
                html: `
                <div>
                    <div class="message">
                        Você precisa estar autenticado para adicionar à lista.
                    </div>
                    <div class="button-wrapper">
                        <a href="${browsingContext.Common.Urls.Profile.Login.Index}?url=${document.location.href}">Fazer Login</a>
                        <button class="no" onclick="javascript: $.modal().close();">Fechar</button>
                    </div>
                </div>`,
                customClass: 'modal-no-auth'
            });
        }
    }



    lcWishlist = {
        addToWishlist: async ({ WishlistID, ProductID, Quantity = 1, SkuID = ProductID }) => {
            const { WebSiteID } = browsingContext.Common.WebSite
            let data = {
                WishlistID,
                ProductID,
                Quantity,
                SkuID,
                WebSiteID
            }
            // if (SkuID != null) {
            //     data.SkuID = SkuID
            // }
            const response = $.ajax({
                url: browsingContext.Common.Urls.BaseUrl + 'Profile/Wishlist/AddProductToWishlist',
                type: 'post',
                dataType: 'json',
                data
            })
            return response
        }
    }

    $('.product-line .add-to-wishlist').on('click', e => {
        e.preventDefault()

        const
            el = e.currentTarget,
            productLine = $(el).closest('.product-line'),
            ProductID = productLine.attr('data-product-id'),
            SkuID = productLine.attr('data-sku-id') ?? ProductID

        applyBinds({ ProductID, SkuID })

    })

    if ($('body').attr('class').includes('context-product')) {
        $('#btn-add-to-wishlist').on('click', e => {
            e.preventDefault()

            const
                el = e.currentTarget,
                ProductID = product.ProductID,
                SkuID = product.Options.length == 0 ? product.Items[1].ProductID : null

            applyBinds({ ProductID, SkuID })

        })
    }







    $('body').on("submit", ".add-product-wishlist", function (event) {
        event.preventDefault();
        try {
            if (browsingContext.Common.Shopper.IsAuthenticated) {
                var val = $(this);
                if (wishlists.length > 1 && $(this).find('input[name=WishlistID]').val() == '') {
                    $(this).find('input[name=WishlistID]').remove();
                    var lists = '<select name="WishlistID">';
                    $(wishlists).each(function (index, value) {
                        lists += `<option value=${value.WishlistID}>${value.Name}</option>`;
                    });
                    lists += '</select >';
                    const cont = $(this).clone();
                    app.modal({
                        html: $(cont).append(lists)
                    });

                } else if (wishlists.length == 0) {
                    app.modal({
                        html: `<div><div class="message">Você não possui lista para adicionar produtos.</div><div class="button-wrapper"><button  onclick="top.$('.the-modal.opened .close').click();" class="no">Fechar</button>
                <a href = ${browsingContext.Common.Urls.Profile.AccountWishlist.Create}>Criar Lista</a></div></div>"`,
                    });
                }
                else if (wishlists.length == 1) {
                    $.ajax({
                        url: browsingContext.Common.Urls.BaseUrl + 'Profile/Wishlist/AddProductToWishlist',
                        type: 'post',
                        dataType: 'json',
                        data: $(this).serialize(),
                        success: function (response) {
                            if (response.ServiceResponse.Data.IsValid) {
                                app.modal({
                                    html: '<div>Produto adicionado a lista com sucesso!</div>'
                                });
                            }
                        }
                    });
                }
            } else {
                app.modal({
                    html: `<div><div class="message">Você precisa estar autenticado para adicionar à lista.</div><div class="button-wrapper"><button class="no">Fechar</button>
			<a href = ${browsingContext.Common.Urls.Profile.Login.Index}>Fazer Login </a></div></div>"`,
                });
            }
        } catch (e) {
            console.error(e);
        }
    });

    $('body').on('click', '.favorite.btn-wishlist', function () {
        var id = $(this).data('product-wishlist');
        var result = [];

        $(wishlists).each(function (index, value) {
            var filteredProducts = $(value.Products).filter(function (index, product) {
                return product.ProductID == id;
            }).map(function (index, product) {
                return {
                    WishlistID: value.WishlistID,
                    Product: product,
                    Name: value.Name
                };
            }).get();
            result.push(...filteredProducts);
        });

        if (result.length == 1) {
            $.ajax({
                url: browsingContext.Common.Urls.BaseUrl + 'painel-do-cliente/lista-de-desejo/remover-produto',
                type: "POST",
                data: {
                    'WishlistID': result[0].WishlistID,
                    'WebSiteID': browsingContext.Common.WebSite.WebSiteID,
                    'WishlistProductID': result[0].Product.WishlistProductID,
                    success: function (response) {
                        app.modal({
                            html: 'Produto removido da lista de desejos'
                        });
                    }
                }
            });
        } else if (result.length > 1) {
            var lists = '<form data-id="' + id + '" class="remove-wishlist-modal" > <select name="WishlistID">';
            $(result).each(function (index, value) {
                lists += `<option value=${value.WishlistID}>${value.Name}</option>`;
            });
            lists += '</select > <input type="hidden" name="WebSiteID" value=' + browsingContext.Common.WebSite.WebSiteID + '></input>' +
                '<input type="hidden" name="WishlistProductID" value=' + result[0].Product.WishlistProductID + '></input>' +
                '<button type="submit">Remover produto da lista</button> </form';
            app.modal({
                html: lists,

                onComplete: function () {
                    $('.remove-wishlist-modal').submit(function (event) {
                        event.preventDefault();
                        $.ajax({
                            url: browsingContext.Common.Urls.BaseUrl + 'painel-do-cliente/lista-de-desejo/remover-produto',
                            type: "POST",
                            data: $(this).serialize(),
                            success: function (response) {
                                app.modal({
                                    html: 'Produto removido da lista de desejos'
                                });
                            }
                        });
                    });

                    $('body').on('change', '.remove-wishlist-modal select', function () {
                        const Wishlist_id = $(this).val();
                        const product_id = $(this).parent().data('id');

                        $(wishlists).each(function (index, value) {
                            if (value.WishlistID == Wishlist_id) {
                                const list = value.Products;
                                $(list).each(function (index, product) {
                                    if (product.ProductID == product_id) {
                                        $('.remove-wishlist-modal input[name="WishlistProductID"]').val(product.WishlistProductID);
                                    }
                                });
                            }
                        });
                    });
                }
            });
        }
    });

} catch (error) {
    console.log(error)
}
}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Themes/Havanna/Scripts/general.js*/
try{var linxCommerce = {};
function detectmob() {
    if (navigator.userAgent.match(/Android/i)
        || navigator.userAgent.match(/webOS/i)
        || navigator.userAgent.match(/iPhone/i)
        || navigator.userAgent.match(/iPad/i)
        || navigator.userAgent.match(/iPod/i)
        || navigator.userAgent.match(/BlackBerry/i)
        || navigator.userAgent.match(/Windows Phone/i)
    ) {
        return true;
    }
    else {
        return false;
    }
}
function startCountdownHome(futureDateString, outputElement) {
    const futureDate = new Date(futureDateString);
    const interval = setInterval(function () {
        const now = new Date();
        const difference = futureDate - now;
        if (difference <= 0) {
            clearInterval(interval);
            outputElement.html(`<span class="date-expired">A oferta acabou!</span> `);
            return;
        }
        const days = Math.floor(difference / (1000 * 60 * 60 * 24));
        const hours = String(Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))).padStart(2, '0');
        const minutes = String(Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60))).padStart(2, '0');
        const seconds = String(Math.floor((difference % (1000 * 60)) / 1000)).padStart(2, '0');
        outputElement.html(`<span> Termina em: </span> <span class="countdown"> ${days}d  :  ${hours}h  :  ${minutes}m  :  ${seconds}s </span>`);
    }, 1000);
}

; (function () {
    try {
        // HELPERS - BEGIN
        Handlebars.registerHelper('ifCond', function (v1, v2, options) {
            if (v1 === v2)
                return options.fn(this);
            return options.inverse(this);
        })

        Handlebars.registerHelper('formatDate', function (data) {
            // if (data != undefined) {
            //     var d = data.split('-')
            //     return [d[2], d[1], d[0]].join('/')
            // }
            if (data != undefined) {
                const
                    t = data.split('T'),
                    d = t[0].split('-')
                return [d[2], d[1], d[0]].join('/')
            }
        })

        Handlebars.registerHelper('formatCurrency', data => {
            return 'R$ ' + Number(data).toFixed(2).replace('.', ',')
        })

        Handlebars.registerHelper('cdnProduct', data => {
            const cdn = browsingContext.Common.ImagesPath.Product.Cdn.replace(browsingContext.Common.ImagesPath.Product.Match, '')
            return cdn + data
        })
        // HELPERS - END


        // API - BEGIN
        linxCommerce = {
            Cdn: {
                Product: browsingContext.Common.ImagesPath.Product.Cdn.replace(browsingContext.Common.ImagesPath.Product.Match, '')
            },
            Basket: {
                addProduct: async ({ ProductID, SkuID, Quantity = 1, data = null }) => {
                    if (data == null) {
                        data = {
                            'Products[0].ProductID': ProductID,
                            'Products[0].SkuID': SkuID,
                            'Products[0].Quantity': Quantity,
                            'WebSiteID': browsingContext.Common.WebSite.WebSiteID
                        }
                    }

                    $('body').addClass('loading')
                    const response = await $.ajax({
                        url: browsingContext.Common.Urls.Shopping.Basket.AddProduct,
                        type: 'post',
                        dataType: 'json',
                        data
                    });

                    if (response.IsValid) {

                        if($('body').hasClass('context-landing-SelectVariationRoute')){
                           
                            const Basket = await top.updateMiniCart();
                            $.publish('view_cart', Basket);
                            top.$('#header .cart').trigger('click')

                            top.setTimeout(() => {
                                top.app.closeModal()
                                
                            },500);
                           
                            
                        }else{
                            if($('body').hasClass('BasketIndexRoute')) {
                             return   linxCommerce.Basket.AttBasket();
                            }
                            $.publish('/basket/add/product/success', response);
                           
                        }
                        $('body').removeClass('loading')
                        return response;
                    } else {
                        $.publish('/basket/add/product/error', response);
                    }
                    $('body').removeClass('loading')
                },
                load: async () => {
                    $('#modal-fixed .content').html('')
                    $('body').addClass('modal-fixed-show loading-modal-fixed')
                    const response = await $.ajax({
                        url: browsingContext.Common.Urls.BaseUrl + 'resumo-carrinho?_=' + new Date().getTime(),
                        cache: false,
                        beforeSend: () => {
                            $('body').addClass('modal-fixed-show')
                        }
                    });

                    const { Basket, Checkout } = JSON.parse(response)
                    const cdn = browsingContext.Common.ImagesPath.Product.Cdn.replace(browsingContext.Common.ImagesPath.Product.Match, '')
                    Basket.Items.map(item => {
                        return item.Image = cdn + item.ImagePath
                    })

                    const source = $("#template-mini-cart").html();
                    const template = Handlebars.compile(source);
                    const html = template({ Basket, Checkout, Shopper: browsingContext.Common.Shopper });

                    $('#modal-fixed .content').html(html)
                    $('body').removeClass('loading-modal-fixed')

                    const total = Basket.Items.reduce((sum, item) => sum + Number(item.Quantity), 0)
                    $('.total-items').html(total)

                },
                remove: async ({ BasketItemID }) => {
                    console.log(BasketItemID)
                    $('body').addClass('loading')
                    const response = await $.ajax({
                        url: browsingContext.Common.Urls.BaseUrl + 'carrinho/remover-produto',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            BasketItemID
                        }
                    })
                    if (response.IsValid) {

                        linxCommerce.Basket.AttBasket()
                    }
                },
                update: async ({ BasketItemID, Quantity = 1 }) => {
                    $('body').addClass('loading');
                    const response = await $.ajax({

                        url: browsingContext.Common.Urls.BaseUrl + 'carrinho/alterar-quantidade',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            BasketItemID,
                            Quantity
                        }
                    });
                    if (response.IsValid) {
                        linxCommerce.Basket.AttBasket()
                    }
                    return response;
                },
                share: async () => {
                    const response = await $.ajax({
                        url: browsingContext.Common.Urls.BaseUrl + 'widget/basket_sendemail?template=~/Custom/Content/Themes/Shared/Templates/debug.template',
                        dataType: 'json'
                    })

                    return response
                },
                setPostalCode: async ({ postalCode }) => {
                    const response = await $.ajax({
                        url: browsingContext.Common.Urls.BaseUrl + 'carrinho/definir-cep',
                        type: 'post',
                        cache: false,
                        headers: {
                            'Accept': 'application/json',
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        data: {
                            postalCode,
                            latitude: 0,
                            longitude: 0
                        }
                    })

                    return response
                },
                setDeliveryOption: async ({ DeliveryOptionID, groupKey , LocationID = null}) => {
                    let data = {}
                    if(LocationID != null){
                        data = {
                            DeliveryOptionID,
                            groupKey,
                            LocationID
                        }
                    }else{
                        data = {
                            DeliveryOptionID,
                            groupKey
                        }
                    }
                    const response = await $.ajax({
                        url: browsingContext.Common.Urls.BaseUrl + 'carrinho/definir-opcao-entrega',
                        type: 'post',
                        dataType: 'json',
                        cache: false,
                        data
                    })

                    return response
                },
                setCoupon: async ({ CouponCode }) => {
                    const response = await $.ajax({
                        url: browsingContext.Common.Urls.BaseUrl + 'carrinho/adicionar-cupom',
                        type: 'post',
                        dataType: 'json',
                        data: {
                            CouponCode,
                        }
                    })
                    return response
                },
                AttBasket: () => {
                    $('body').removeClass('loading')
                    const wdBasket = $('.wd-checkout-basket').data()
                    wdBasket.basket._refresh()
                }
            }
        };
        // API - END

        // SEARCH - BEGIN


        /** MODAL - BEGIN */
        $('#modal-fixed .close-modal').on('click', e => {
            e.preventDefault()
            $('body').removeClass('modal-fixed-show')
        })
        /** MODAL - END */


        // MINI-CART - BEGIN        
        $('#header .cart').on('click', async e => {
            e.preventDefault()
            //linxCommerce.Basket.load()
            $('body').addClass('blocked modal-mini-cart')
        })

        const changeBasket = input => {
            input.trigger('change')
            return
        }
        $('body').on('click', '#mini-cart .actions .group a', e => {
            e.preventDefault()
            const
                el = e.target,
                form = $(el).closest('.group'),
                input = $('input', form),
                count = Number(input.val()),
                action = $(el).attr('data-action')

            if (action == 'less' && (count - 1) == 0) {
                let basketItemID = $(e.target).closest('li').data('basket-item-id');
                linxCommerce.Basket.remove({ BasketItemID: basketItemID });
            }
            else {
                if (action == 'less') {
                    input.val(Math.max(1, count - 1));
                } else {
                    input.val(count + 1)
                }
                changeBasket(input)
            }
        });
        // MINI-CART - END



        /** BACKDROP - BEGIN */
        $('#backdrop, .backdrop-part').on('click', e => {
            e.preventDefault()
            $('body').removeClass('searching modal-fixed-show blocked show-search show-welcome show-facets show-notify-me show-set-location modal-mini-cart')
        })
        /** BACKDROP - END */


        /** NEWSLETTER - BEGIN */
        $('#footer .newsletter form').on('submit', async e => {
            e.preventDefault()

            const
                form = e.target,
                Name = $('[name="name"]', form).val(),
                Email = $('[name="email"]', form).val()

            $('button', form).addClass('loading')

            const response = await $.ajax({
                url: browsingContext.Common.Urls.BaseUrl + 'shopping/newsletter',
                type: 'post',
                dataType: 'json',
                data: {
                    Name,
                    Email
                }
            })

            if (response.Response.IsValid) {
                $('#footer .newsletter .result').html('<strong>E-mail cadastrado com sucesso!</strong>').show()
                $('#footer .newsletter form')[0].reset()
                $('#footer .newsletter form').hide()
            } else {
                $('#footer .newsletter .result').html('<strong>Esse e-mail já está cadastrado</strong>').show()
            }

            $('button', form).removeClass('loading')

            setTimeout(() => {
                $('#footer .newsletter .result').html('').hide()
                $('#footer .newsletter form').show()
            }, 3000)

        })
        /** NEWSLETTER - END */


        // FOOTER - BEGIN
        $('.accordion [data-visibility]').on('click', e => {
            e.preventDefault()
            const
                el = e.currentTarget,
                li = $(el).closest('li')

            let visibility = $(el).attr('data-visibility')

            visibility = visibility == 'hide' ? 'show' : 'hide'
            $('.content', li).attr('style', `display:${visibility == 'hide' ? 'none' : 'flex'}`)

            $(el).attr('data-visibility', visibility)


        })
        // FOOTER - END




        /** PRODUCTLINE - BEGIN */
        const productLineBehavior = () => {
            $('.product-line img').on('mouseover', e => {
                const el = e.target,
                    productLine = $(el).closest('.product-line'),
                    second = $('.second', productLine)

                if (second.length) {
                    second.removeAttr('style')
                    setTimeout(() => {
                        productLine.addClass('two-images')
                    }, 100)

                }

            })

            $('.product-line .variation button').on('click', e => {
                e.preventDefault()
                const
                    el = e.target,
                    li = $(el).closest('li'),
                    pp = $(el).attr('data-property-path'),
                    product = $(el).closest('.product-line'),
                    link = $('.link-product', product),
                    medias = JSON.parse($('figure[data-medias]', product).attr('data-medias'))

                product.addClass('loading-photo')
                $('.variation li.selected', product).removeClass('selected')
                li.addClass('selected')

                const item = medias.find(i => i.vp == pp)
                const cdn = browsingContext.Common.ImagesPath.Product.Cdn.replace(browsingContext.Common.ImagesPath.Product.Match, '')
                const src = cdn + (detectmob() ? item.small.mp : item.medium.mp)

                $(`picture .${detectmob() ? 'small' : 'medium'}`, product).attr('srcset', src)
                $('.second', product).remove()

                const img = new Image();
                img.onload = function () {
                    product.removeClass('loading-photo')
                };
                img.src = src

                let url = link.attr('href').split('?')[0] + `?pp=${pp}`
                link.attr('href', url)
            })
        }
        productLineBehavior()

        $('body').on('onBuildFacetingComplete', (e) => {
            productLineBehavior()
        })

        $.subscribe('/product/list/dynamic/loaded', (e, el) => {
            productLineBehavior()
        })
        /** PRODUCTLINE - END */


        /** LOGGED - BEGIN */
        if (browsingContext.Common.ready) {
            $('#header .cart .total').text(browsingContext.Common.Basket.Items.length)

            if (!detectmob()) {
                if (browsingContext.Common.Shopper.IsAuthenticated) {
                    $('body').addClass('is-authenticated')
                    $('#header .profile > a span').html(`Olá, ${browsingContext.Common.Customer.Name}`)
                } else {
                    $('body').addClass('no-authenticated')
                    $('#header .profile > a span').html('Login | Cadastre-se')
                }
            }
        } else {
            $.subscribe('/wd/browsing/context/ready', () => {
                $('#header .cart .total').text(browsingContext.Common.Basket.Items.length)

                if (!detectmob()) {
                    if (browsingContext.Common.Shopper.IsAuthenticated) {
                        $('body').addClass('is-authenticated')
                        $('#header .profile > a span').html(`Olá, ${browsingContext.Common.Customer.Name}`)
                    } else {
                        $('body').addClass('no-authenticated')
                        $('#header .profile > a span').html('Login | Cadastre-se')
                    }
                }
            })
        }
        /** LOGGED - END */


        if (detectmob()) {
            $('.wd-profile-panelmenu .col-menu a').on('click', e => {
                e.preventDefault()

                $('body').toggleClass('show-menu')
            })
        }

        /** SERVICES FLOAT - BEGIN */
        $('.service-float').on('click', e => {
            e.preventDefault()
            $('.service-float').toggleClass('opened')
        })
        /** SERVICES FLOAT - END */

        /** EVENTS - BEGIN */
        $.subscribe('basket/add/product/error', (e, response) => {
            const errors = response.Errors.map(error => {
                return `<p>${error.ErrorMessage}</p>`
            })
            app.modal({
                html: errors.join(''),
                customClass: 'modal-error'
            })
        })
         $.subscribe('/basket/add/product/success', async (e, args) => {
            if (args.IsValid) {
               const Basket = await updateMiniCart();
               $.publish('view_cart', Basket);
                $('#header .cart').trigger('click')
            } else {

            }
        })

      
        /** EVENTS - END */

        /**TIME PRODUCTS - BEGIN */
        $('.data-item').each(function () {
            const futureDateString = $(this).data('date');
            startCountdown(futureDateString, $(this));
        });

        $('.promotion-item').each(function () {
            const futureDateString = $(this).data('date');
            startCountdownHome(futureDateString, $(this));
        });



        function startCountdown(futureDateString, outputElement) {
            const futureDate = new Date(futureDateString);

            const interval = setInterval(function () {
                const now = new Date();
                const difference = futureDate - now;
                if (difference <= 0) {
                    clearInterval(interval);
                    outputElement.html(`<span class="date-expired">A oferta acabou!</span> `);
                    return;
                }

                const days = Math.floor(difference / (1000 * 60 * 60 * 24));
                const hours = String(Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))).padStart(2, '0');
                const minutes = String(Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60))).padStart(2, '0');
                const seconds = String(Math.floor((difference % (1000 * 60)) / 1000)).padStart(2, '0');
                if ($('body[class*="context-product"]').length > 0) {
                    const discount = $('.header  .data-item').data('discount');
                    if (discount > 0) {
                        outputElement.html(`<span> Ofertas acabam em:  <span class="countdown"> ${days}D : ${hours} : ${minutes} : ${seconds} </span> </span> <span class=discount>${discount}% </span>`);
                    } else {
                        outputElement.html(`<span> Ofertas acabam em:  <span class="countdown"> ${days}D : ${hours} : ${minutes} : ${seconds} </span> </span>`);
                    }
                } else if ($('body').hasClass('BasketIndexRoute')) {
                    outputElement.html(`<span class="flex items-center gap-2"> <svg width="14" height="15" viewBox="0 0 14 15" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M6.76667 0.733398C3.02954 0.733398 0 3.76294 0 7.50006C0 11.2372 3.02954 14.2667 6.76667 14.2667C10.5038 14.2667 13.5333 11.2372 13.5333 7.50006C13.5333 3.76294 10.5038 0.733398 6.76667 0.733398Z" fill="#F2AE00"/>
                                        <path d="M6.7666 4.7666V8.04423C6.7666 8.15819 6.82483 8.26426 6.92098 8.32545L8.79575 9.51848" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                                        </svg>
                                        Ofertas acabam em  <span class="countdown"> ${days}D : ${hours}H : ${minutes}M : ${seconds}S </span> </span>`);
                } else {
                    outputElement.html(`<span> Ofertas acabam em <span class="countdown"> ${days}d : ${hours}h : ${minutes}m : ${seconds}s </span> </span>`);
                }

            }, 1000);
        }
        /**TIME PRODUCTS - END */

                /** ADD TO CART - BEGIN */
                $('body').on('submit', '.form-add-product', async e => {
                    e.preventDefault()
                    const el = e.currentTarget;
                    $(el).closest('.product-line').addClass('loading')
                    //linxCommerce.Basket.addProduct({ data : $(el).serialize() })
                    const response = await $.ajax({
                        url: browsingContext.Common.Urls.Shopping.Basket.AddProduct,
                        type: 'post',
                        dataType: 'json',
                        data: $(el).serialize()
                    });        
                    if (response.IsValid) {
                        const item_id = $(el).find('input[name="Products[0].ProductID"]').val();
                        const item_name = $(el).attr('data-name');
                        const value = $(el).attr('data-value').replace(',', '.');
                        $.publish('add_to_cart', {item_id,item_name, value});
                        if($('body').hasClass('BasketIndexRoute')) {
                            $(el).closest('.product-line').removeClass('loading')
                            return  linxCommerce.Basket.AttBasket();
                        }
                        $.publish('/basket/add/product/success', response);
                       
                    } else {
                        $.publish('/basket/add/product/error', response);
                    }
                    $(el).closest('.product-line').removeClass('loading')
                })
                /** ADD TO CART - END */
                
        
    } catch (error) {
        console.log(error)
    }
})()
}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Themes/Havanna/Scripts/footer.js*/
try{; (function () {
    try {
        $('.brands-list h3').on('click', (e) => {
            const el = e.target;
            $('.brands-list').toggleClass('closed');
        });

        $('.departments-list h3').on('click', (e) => {
            const el = e.target;
            $('.departments-list').toggleClass('closed');
        });

        $('.links h3').on('click', (e) => {
            const el = e.target;
            $('.links').toggleClass('closed');
        });

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(async e => {
                if (e.isIntersecting) {
                    const
                        el = e.target

                    if (!$(el).hasClass('loaded')) {
                        const
                            slider = $(el).data('slider') || false,
                            slidesPerView = $(el).data('slider-show') || 'auto',
                            source = $(el).data('source') || 171,
                            PageSize = $(el).data('page-size') || 30,
                            row = $(el).data('page-row') || 9,
                            spaceBetween = $(el).data('space') || 0

                        const list = await $.ajax({
                            url: browsingContext.Common.Urls.BaseUrl + `widget/clean_product_list_swiper?DataSourceID=${source}&WidgetBox=false&PageSize=${PageSize}&Orientation=vertical`
                        })

                        $(el).append(list)

                        /*let options = {
                            slidesPerView,
                            spaceBetween,
                            grid: {
                                rows: row,
                            },
                        }
                        const swiper = new Swiper($('.swiper', el)[0], options)*/
                        e.target.classList.add('loaded')
                        $.publish('/product/list/dynamic/loaded', el)
                    }
                }
            })
        })
        const elements = document.querySelectorAll('.product-list-dynamic-footer')
        elements.forEach(el => {
            observer.observe(el);
        });
    } catch (error) {
        console.log(error);
    }
})();
}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Themes/Havanna/Scripts/header.js*/
try{try {
    /**
     * MENU HAMBURGUER - BEGIN
     */
    $('#header .hamburguer').on('click', e => {
        e.preventDefault()
        const
            parent = e.currentTarget,
            href = $('use', parent).attr('xlink:href').split('#')[0]
        if ($('body').hasClass('show-menu-hamburguer')) {
            $('body').removeClass('show-menu-hamburguer')
            $('use', parent).attr('xlink:href', `${href}#hamburguer`)
        } else {
            $('body').addClass('show-menu-hamburguer')
            $('use', parent).attr('xlink:href', `${href}#close`)
        }
    })

    $('#menu-hamburguer a.go').on('click', e => {
        e.preventDefault()
        const
            el = e.currentTarget,
            parent = $(el).closest('li')

        if ($(el).hasClass('last')) {
            document.location.href = $(el).attr('href')
        } else {
            parent.addClass('active')
        }
    })

    $('#menu-hamburguer .back').on('click', e => {
        e.preventDefault()
        const
            el = e.currentTarget,
            parent = $(el).closest('.active')
        parent.toggleClass('active')
    })
    /**
     * MENU HAMBURGUER - END
     */


    /**
     * SEARCH - BEGIN
     */
    let timeoutID
    const doSuggestions = async (t) => {
        if (t.length > 3) {
            $('body').addClass('searching')
            const response = await $.ajax({
                url: browsingContext.Common.Urls.BaseUrl + 'sugestao.partial',
                data: {
                    t,
                    showCorrections: true,
                    showTerms: true,
                    showProducts: true,
                    termsLimit: 0,
                    productsLimit: 0
                }
            })
            return response
        }
    }

    $('.search [name="t"]').focus(e => {
        if ($('.search .result ul').length) {
            $('body').addClass('searching')
        }
    })

    $('.search [name="t"]').keyup(async e => {
        const
            el = e.target,
            t = $(el).val()

        clearTimeout(timeoutID);
        timeoutID = setTimeout(async () => {
            if ($(el).attr('data-term') != t) {
                const response = await doSuggestions(t)
                $('.search .result').html(response)
            }
            $(el).attr('data-term', t)
        }, 100);
    })

    $('.search button.close').on('click', e => {
        e.preventDefault()
        $('body').removeClass('searching')
    })

    /**
     * SEARCH - END
     */


    /**
     * PIN SET LOCATION - BEGIN
     */
    /*
    if (browsingContext.Common.ready) {
        if (browsingContext.Common.Shopper.IsAuthenticated) {
            $('.modal-my-postalcode .or').hide()
        }
    } else {
        $.subscribe('/wd/browsing/context/ready', () => {
            if (browsingContext.Common.Shopper.IsAuthenticated) {
                $('.modal-my-postalcode .or').hide()
            }
        })
    }
    */

    $('#header .pin > a').on('click', e => {
        e.preventDefault()
        $('body').toggleClass('blocked show-set-location')
    })
    $('#header .modal-my-postalcode .close').on('click', e => {
        e.preventDefault()
        //$('body').removeClass('show-set-location')
        $('#backdrop').trigger('click')
    })
    $('#header .modal-my-postalcode form').on('submit', async e => {
        e.preventDefault()
        const
            form = e.target,
            postalCode = $('[name="postalcode"]', form).val()

        $('#header .modal-my-postalcode').addClass('loading')
        const response = await $.ajax({
            url: browsingContext.Common.Urls.BaseUrl + 'carrinho/definir-cep',
            type: 'post',
            dataType: 'json',
            data: {
                postalCode,
                latitude: 0,
                longitude: 0
            }
        })
        $('#header .pin small').html(`Sua localização <em>${postalCode}</em>`)
        $('#header .modal-my-postalcode').removeClass('loading')

        localStorage.setItem('myPostalCode', postalCode)
        $.publish('/set/postalCode', postalCode)
        $('body').removeClass('show-set-location')
        $('#backdrop').trigger('click')

    })

    $('#header .modal-my-postalcode [name="postalcode"]').on('input', (event) => {
        let value = event.target.value.replace(/\D/g, '')
        if (value.length > 5) {
            value = value.replace(/^(\d{5})(\d)/, '$1-$2')
        }
        event.target.value = value
    });



    const checkHasAddresses = async () => {
        if (browsingContext.Common.Shopper.IsAuthenticated) {
            const { Addresses } = await $.ajax({
                url: browsingContext.Common.Urls.Profile.AccountAddress.Index,
                dataType: 'json'
            })

            if (Addresses.length) {
                const address = Addresses.find(_address => _address.IsMainAddress == true)
                const postalCode = address.PostalCode

                const response = await $.ajax({
                    url: browsingContext.Common.Urls.BaseUrl + 'carrinho/definir-cep',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        postalCode,
                        latitude: 0,
                        longitude: 0
                    }
                })
                $('#header .pin small').html(`Sua localização <em>${postalCode}</em>`)
                $('#header .modal-my-postalcode').removeClass('loading')

                localStorage.setItem('myPostalCode', postalCode)
                $('body').removeClass('show-set-location')
                $('#backdrop').trigger('click')
            } else {
                $('#header .pin small').html('Informe seu CEP')
                if ($('body').hasClass('HomeRoute')) {
                    $('body').toggleClass('blocked show-set-location')
                }
            }
        } else {
            $('#header .pin small').html('Informe seu CEP')
            if ($('body').hasClass('HomeRoute')) {
                $('body').toggleClass('blocked show-set-location')
            }
        }
    }

    /*
    (async () => {
        try {
            if (localStorage.getItem('myPostalCode') != null) {
                $('body').addClass('has-postalcode')

                const postalCode = localStorage.getItem('myPostalCode')
                $('#header .modal-my-postalcode form [name="postalcode"]').val(postalCode)
                $('#header .pin small').html(`Sua localização <em>${postalCode}</em>`)
            } else {
                if (browsingContext.Common.ready) {
                    checkHasAddresses()
                } else {
                    $.subscribe('/wd/browsing/context/ready', async () => {
                        checkHasAddresses()
                    })
                }
            }
        } catch (error) {
            console.log(error)
        }
    })()
    */
    /**
     * PIN SET LOCATION- END
     */


    /** HOVER MENU - BEGIN */
    if (!detectmob()) {
        let timer;

        $('#header #main-menu > .lv-1').hover(
            function () {
                timer = setTimeout(() => {
                    $('body').addClass('hovered');
                }, 200);
            },
            function () {
                clearTimeout(timer);
                $('body').removeClass('hovered');
            }
        );
    }
    /** HOVER MENU - END */

    /** HEADER FIXED - BEGIN */
    if (!detectmob()) {
        const
            header = $("#header"),
            body = $("body:not(.BasketIndexRoute)");

        const observer = new IntersectionObserver(
            function ([entry]) {
                if (entry.isIntersecting) {
                    body.removeClass("header-fixed");
                } else {
                    body.addClass("header-fixed");
                }
            },
            {
                root: null,
                threshold: 0
            }
        )

        observer.observe(header[0])
    }
    /** HEADER FIXED - END */
} catch (error) {

}
}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Themes/Havanna/Scripts/product.swiper.js*/
try{$('[name="Name"]', '#modal-notify-me form').mask("(99)999999999");
$('[name="CEP"]', '.delivery').mask("99999-999");
var swiper;
var swiperThumbs;
Handlebars.registerHelper('formatCurrency', function(value) {
  if (typeof value !== 'number') {
    value = parseFloat(value); 
  }
  if(value==0){
    return 'Gratis'
  }
  return value.toLocaleString('pt-BR', {
    style: 'currency',
    currency: 'BRL', 
  });
});
Handlebars.registerHelper('eq', function (a, b) {
    return a === b;
});
function detectmob() {
    if (navigator.userAgent.match(/Android/i)
        || navigator.userAgent.match(/webOS/i)
        || navigator.userAgent.match(/iPhone/i)
        || navigator.userAgent.match(/iPad/i)
        || navigator.userAgent.match(/iPod/i)
        || navigator.userAgent.match(/BlackBerry/i)
        || navigator.userAgent.match(/Windows Phone/i)
    ) {
        return true;
    }
    else {
        return false;
    }
}
; (function () {
    try {

        /** PRODUCT - FLOATING - BEGIN */
       
        const $btnFloating = $('.btn-floating');
        const mobileThreshold = 1000;
        const desktopThreshold = 800;
      
        function getScrollThreshold() {
          return $(window).width() <= 768 ? mobileThreshold : desktopThreshold;
        }
      
        let scrollThreshold = getScrollThreshold();
      
        $(window).on('resize', function () {
          scrollThreshold = getScrollThreshold();
          toggleBtnFloating();
        });
      
        function toggleBtnFloating() {
          const scrollTop = $(window).scrollTop();
          if (scrollTop >= scrollThreshold) {
            $btnFloating.css('display', 'block');
          } else {
            $btnFloating.css('display', 'none');
          }
        }
      
        const observer = new IntersectionObserver(
          ([entry]) => {
            if (entry.isIntersecting) {
              toggleBtnFloating();
            }
          },
          { threshold: [0, 1] }
        );
      
        observer.observe(document.documentElement);
      
        $(window).on('scroll', toggleBtnFloating);

        /** PRODUCT - FLOATING - END */
        /** BTN - FLOATING - BEGIN   */


        $('body[class*=context-product] [data-scroll]').on('click', function (e) {
            const el = e.currentTarget,
                $el = $(el).attr('data-scroll');
            $('html, body').animate({
                scrollTop: $($el).offset().top -100
            }, 800);    
        })

        /** BTN - FLOATING - END */

        /** MEDIAS - BEGIN */
        const hasMediasOnFather = $('#product-detail .medias ul li[data-variation-path="/"]').length ? true : false
        if (detectmob()) {
            const swiper = new Swiper('#product-detail .medias .swiper', {
                //slidesPerView: 'auto',
                //spaceBetween: 16,
                loop: true,
                //zoom: true,
                pagination: {
                    el: "#product-detail .medias .swiper-pagination",
                    type: "bullets",
                },
            })
        } else {

           const sizeMedias = parseInt($('#product-detail .wp-medias').attr('data-size'), 10);

if (sizeMedias <= 7) {
    $('#product-detail .wp-medias .swiper-button-next').hide();
    $('#product-detail .wp-medias .swiper-button-prev').hide();
}

            swiperThumbs = new Swiper('#product-detail .wp-medias .thumbs-swiper', {
                slidesPerView: 7,
                direction: "vertical",
                loop: true,
                spaceBetween: 0,
                zoom: false,
                navigation: {
                    nextEl: "#product-detail .swiper-button-next",
                    prevEl: "#product-detail .swiper-button-prev",
                },
            })
         
            swiper = new Swiper('#product-detail .medias .swiper', {
                slidesPerView: 1,
                slidesPerGroup: 1,
                spaceBetween: 0,
                loop: true,
                thumbs: {
                    swiper : swiperThumbs
                },
                navigation: {
                    nextEl: "#product-detail .swiper-button-next",
                    prevEl: "#product-detail .swiper-button-prev",
                },
            })


       
              new Swiper("aside .wd-product-associations.suggestion .swiper", {
                direction: "vertical",
                slidesPerView: "auto",
                navigation: {
                    nextEl: ".suggestion .swiper-button-next",
                    prevEl: ".suggestion .swiper-button-prev",
                    
                  },    
              });
        }

        $('.wp-medias .media a').on('click', function (e) {
            e.preventDefault();
            const el = e.currentTarget;
            const selectedImage = $(el).find('img').attr('src');
            $(el).closest('ul').find('li').each(function () {
                $(this).removeClass('selected');
            })
            $(el).closest('li').addClass('selected');

            const zoomContainer = $('.swiper-zoom-container img');
            zoomContainer.attr('src', selectedImage);
        });

        $('.wd-product-associations.suggestion .product-line').on('click',e=> {
            e.preventDefault();
            const el = e.currentTarget;
            app.modal({
                href: browsingContext.Common.Urls.BaseUrl+'selectvariation-sv'+$(el).attr('data-product-id'),
                className: 'wd-modal-sv',
              
            })
        })
        $('#product-detail .variations [data-property-path]').on('click', e => {
            e.preventDefault()
            const
                el = e.target,
                li = $(el).closest('li'),
                variationName = $(el).text(),
                variation = $(el).closest('.variation'),
                label = variation.attr('data-label').toLowerCase(),
                propertyPathSelected = $(el).data('property-path')
            $('li', variation).removeClass('selected')
            $(li).addClass('selected')

            if (label == 'cor' && product.Options.length > 1) {
                $('#product-detail .variation[data-label="Tamanho"] li').removeClass('selected')
            }

            let propertyPath = ''
            $('#product-detail .variations li.selected [data-property-path]').each((k, i) => {
                propertyPath += $(i).data('property-path')
            })
            propertyPath = propertyPath.replace('\/\/', '/')
            console.log('propertyPath', propertyPath, propertyPathSelected)

            // disponibilidade
            $('#product-detail .variations .variation').each((k, i) => {
                let propertyPathParent = null
                if (k == 0) {
                    propertyPathParent = $('.options li.selected a', i).attr('data-property-path')
                    if (propertyPathParent != null) {
                        $('#product-detail .variations .variation + .variation li').removeClass('unavailable')
                        product.Items.forEach(i => {
                            if (i.VariationPath.includes(propertyPathParent) && i.Availability == 'O') {
                                const variationPath = '/' + i.VariationPath.replace(propertyPathParent, '')
                                $(`#product-detail .variations [data-property-path="${variationPath}"]`).closest('li').addClass('unavailable')
                            }
                        })
                    }
                }
            })
            const item = product.Items.filter(i => {
                return i.VariationPath == propertyPath
            })[0]
            if (typeof (item) != 'undefined') {
                if (item?.Availability == 'O') {
                    $('body').addClass('unavailable')
                    $('#product-detail .almost-out-of-stock').hide()
                } else {
                    if (item?.StockBalance <= 5) {
                        $('#product-detail .almost-out-of-stock').show()
                    } else {
                        $('#product-detail .almost-out-of-stock').hide()
                    }
                    $('body').removeClass('unavailable')
                }
            } else {
                $('body').removeClass('unavailable')
            }
            const medias = product.Medias.filter(i => {
                return i.MediaType == 'Image' && i.MediaSizeType == 'Small' && i.VariationPath == propertyPathSelected
            })
            console.log(medias)

            if (item != undefined) {
                $('#product-detail').attr('data-sku-id', item.ProductID)
                $('#product-detail .add-to-cart').attr('data-sku-id', item.ProductID)
                $('#product-detail .details .price').html(item.PriceDescription)
            } else {
                $('#product-detail .add-to-cart').attr('data-sku-id', '')
            }
        })
        const
            urlParams = new URLSearchParams(window.location.search),
            pp = urlParams.get('pp'),
            v = urlParams.get('v')
        if (pp != null) {
            $(`#product-detail .main .variation a[data-property-path="${pp}"]`).trigger('click')
        } else {
            $('#product-detail .variations .variation:first li.selected a[data-property-path]').trigger('click')
        }
        if (v != null) {
            const sku = product.Items.find(i => i.ProductID == v)
            if (sku != undefined) {
                sku.SKUOptions.forEach((option, k) => {
                    $(`.variations .variation[data-index="${k}"] .options a[data-property-path="${option.PropertyPath}"]`).trigger('click')
                })
            }
        }
        /** LOAD - END */
        /** VARIATIONS - END */


        /** ADD TO CART - BEGIN */

        $("#product-detail .add-to-cart-gift").on('click', async e => {
            e.preventDefault()
           app.modal({
               html: $('#template-gift').html(),
               onComplete: (() => {
                    $('#add-to-gift').on('submit', async e => {
                        e.preventDefault()
                        const form = e.target,
                              data = $(form).serialize();
                        $(form).addClass('loading')
                        const response = await linxCommerce.Basket.addProduct({ data})
                        $(form).removeClass('loading')
                        if(response.IsValid){
                            app.closeModal()
                            $.publish('add_to_cart', {item_id:product.ProductID,item_name:product.Name, value:product.Price.SalesPrice});
                        }
                    })
               })
           })
        })
        $('.btn-floating button').on('click', async e => {
            $('#product-detail .add-to-cart').trigger('click')
        })
        $('#product-detail .add-to-cart').on('click', async e => {
            e.preventDefault()
            
            const
                el = e.target,
                ProductID = product.ProductID,
                SkuID = $(el).attr('data-sku-id'),
                
                 Quantity = $('#product-detail .details .change input').val() || 1
            console.log(SkuID)
            if (SkuID) {
               const response = await linxCommerce.Basket.addProduct({ ProductID, SkuID, Quantity })
               if(response.IsValid){
              
                $.publish('add_to_cart', {item_id:product.ProductID,item_name:product.Name, value:product.Price.SalesPrice});
                }
            }
        })
        /** ADD TO CART - END */


        /** ADD TO CART BUNDLE - BEGIN */
        $('#product-detail .add-to-cart-bundle').on('click', async e => {
            e.preventDefault()

            const
                el = e.target,
                ProductID = product.ProductID,
                SkuID = product.ProductID,
                //Quantity = $('#product-detail [name="quantity"]').val()
                Quantity = 1

            let data = {
                'Products[0].ProductID': ProductID,
                'Products[0].SkuID': SkuID,
                'Products[0].Quantity': 1,
            }
            $('#product-detail .bundle [name="ProductID"]:checked').each((k, i) => {
                data[`Products[0].Additionals[${k}].ProductID`] = Number($(i).val())
                data[`Products[0].Additionals[${k}].IsSelected`] = true
            })
            console.log(data)

            const response = await linxCommerce.Basket.addProduct({ ProductID, SkuID, Quantity, data })
            if(response.IsValid){
                $.publish('add_to_cart', {item_id:product.ProductID,item_name:product.Name, value:product.Price.SalesPrice});
            }

        })
        /** ADD TO CART BUNDLE - END */


        /** CHANGE PRICE BUNDLE - BEGIN */
        $('#product-detail .bundle [name="ProductID"]').on('change', async e => {
            e.preventDefault()

            const
                el = e.target,
                productIdSelected = $(el).val()

            const totalChecked = $('#product-detail .bundle [name="ProductID"]:checked').length
            return
            if (totalChecked == 0) {
                $(`#product-detail .bundle [name="ProductID"]:not([value="${productIdSelected}"])`).trigger('click')
            } else {
                $('#product-detail .price').addClass('loading')
                let items = []
                $('#product-detail .bundle [name="ProductID"]:checked').each((k, i) => {
                    items.push({
                        'I': $(i).val(),
                        'Q': 1
                    })
                })
                const data = {
                    'R': [{
                        'id': product.ProductID,
                        'I': items
                    }]
                }
                const response = await $.ajax({
                    url: browsingContext.Common.Urls.BaseUrl + 'web-api/v1/Shopping/Price/Post',
                        type: 'post',
                        dataType: 'json',
                        contentType: 'application/json',
                        data: JSON.stringify(data)
                    })

                $('#product-detail .price').html(response.Prices[0].PriceDescription)
                $('#product-detail .price').removeClass('loading')
            }
        })
        if (product.CatalogItemBehavior == 'Bundle') {
            $('#product-detail .bundle [name="ProductID"]:checked:first').trigger('change')
        }
        /** CHANGE PRICE BUNDLE - END */


        /** NOTIFY-ME - BEGIN */
        $('#product-detail .notify-me ').on('click', e => {
            e.preventDefault()
            $('body').addClass('blocked show-notify-me')
        })

        $('#modal-notify-me [data-action="close"]').on('click', e => {
            e.preventDefault()
            $('body').removeClass('blocked show-notify-me')
        })

      

        $('#modal-notify-me form').on('submit', async e => {
            e.preventDefault()
            var IsValid = false;
            const
                ProductID = product.ProductID,
                SkuID = $('#product-detail').attr('data-sku-id') ?? product.ProductID,
                form = e.target,
                Name = $('[name="Name"]', form).val(),
                Email = $('[name="Email"]', form).val()

            if(!$('[name="Name"]', form).val()){
                $('[name="Name"]', form).parent().addClass('error')
            }else{
                IsValid=true;
                $('[name="Name"]', form).css('border', '1.5px solid #059669');
            }
            if(IsValid){  
            const response = await $.ajax({
                url: browsingContext.Common.Urls.BaseUrl + 'Shopping/ProductNotification/Notify',
                type: 'post',
                dataType: 'json',
                data: {
                    ProductID,
                    SkuID,
                    Name,
                    Email
                }
            })

            if (response.IsValid) {
                //$('#modal-notify-me .info').attr('style', 'display:none;')
                $('#modal-notify-me .callback').html('Sua solicitação de aviso foi cadastrada com sucesso!').attr('style', 'display:flex;')
            } else {
                //$('#footer .newsletter .result').html('<strong>Esse e-mail já está cadastrado</strong>')
            }

            setTimeout(() => {
                $('#modal-notify-me [data-action="close"]').trigger('click')
                //$('#modal-notify-me .info').attr('style', 'display:flex;')
                $('#modal-notify-me .callback').html('').attr('style', 'display:none;')
                $('#modal-notify-me form')[0].reset()
                //$('#footer .newsletter .result').html('')
            }, 3000)
        }
        })
        /** NOTIFY-ME - END */


        /** DELIVERY - BEGIN */
        $('#product-detail .delivery form').on('submit', async e => {
            e.preventDefault()

            $('#product-detail .delivery .result').addClass('hidden').empty()
            $('#product-detail .delivery').addClass('loading')

            const
                form = e.target,
                ProductID = product.ProductID,
                SkuID = product.ProductID,
                PostalCode = $('input', form).val()

            const response = await $.ajax({
                url: browsingContext.Common.Urls.BaseUrl + 'widget/product_deliveryfee',
                type: 'get',
                dataType: 'json',
                data: {
                    ProductID,
                    SkuID,
                    PostalCode,
                    Template: '~/custom/content/themes/Shared/Templates/debug.template'
                }
            })

            if (response.Response.IsValid) {
                const
                    source = $('#template-delivery-list').html(),
                    template = Handlebars.compile(source),
                    html = template(response)

                $('#product-detail .delivery .result').removeClass('hidden').html(html)
                linxCommerce.Basket.setPostalCode({postalCode: PostalCode})
                $.publish('/set/postalCode', PostalCode)
            } else {
                const errors = response.Response.Errors.map(error => {
                    return `<p>${error.ErrorMessage}</p>`
                })
                $('#product-detail .delivery .result').removeClass('hidden').html(errors.join(''))
            }

            $('#product-detail .delivery').removeClass('loading')

        })
        $('.btn-alter-delivery').on('click', e => {
            e.preventDefault()
            const el = e.currentTarget;
            $(el).closest('.postalcode-empty').addClass('hidden');
            $('.IsPostalCode').removeClass('hidden');

        })
       /* if($('.postalcode-empty .CEP').is(':visible')){
            $('.IsPostalCode button').click()
       }*/
        
        /** DELIVERY - END */

        /** PAYMENT - BEGIN */
        $('#product-detail .price-container .parcels').on('click', async e => {
            e.preventDefault()
            $('body').addClass('loading')
            const
                el = e.target,
                form = e.target,
                ProductID = product.ProductID,
                SkuID = product.ProductID

                const response = await $.ajax({
                    url: browsingContext.Common.Urls.BaseUrl + 'widget/product_payment_options',
                    type: 'get',
                    dataType: 'json',
                    data: {
                        ProductID,
                        SkuID,
                        Template: '~/custom/content/themes/Shared/Templates/debug.template'
                    }
                });        
                $('body').removeClass('loading')

                if (response.Response.IsValid) {
                    const
                        source = $('#template-payment-list').html(),
                        template = Handlebars.compile(source),
                        html = template(response.Groups.filter(group => group.Alias === 'PIX' || group.Alias === 'CREDITCARD'))

                  
                        app.modal({
                            html,
                            height:400,
                            className: 'payments-modal',
                            onOpenFunction: function() {
                                $('.payments-modal .group').first().click();
                                $('.group').on('click',(e)=>{
                                    e.preventDefault();
                                    const el = e.currentTarget;
                                    const id= $(el).data('id');
                                    $('.group').each((k,j)=>{
                                        $(j).removeClass('selected');
                                    })
                                    $(el).addClass('selected') ;
                                    $('.group-installments').each((k,j)=>{
                                        $(j).hide();
                                    })
                                    $(`.group-installments[data-id="${id}"]`).show();
                                })   
                            }
                        })
                    // }
                    
                } else {
                    const errors = response.Response.Errors.map(error => {
                        return `<p>${error.ErrorMessage}</p>`
                    })
                    $('.').html(errors.join(''))
                }
                
        })
      

        /** review - END */

        let total = Reviews.Reviews.reduce((total, review) => total + review.RatingAverage,0)
        if(Reviews.Reviews.length>0){
            $('.media-stars').html((total/Reviews.Reviews.length).toFixed(1))
            for(let i = 1; i <= 5; i++){
                $('.stars-' + i + ' .box-barras div').css('width', (Reviews.Reviews.filter(review=> review.RatingAverage == i).length/Reviews.Reviews.length*100) + '%')
                $('.stars-' + i + ' .value-porcent').html((Reviews.Reviews.filter(review=> review.RatingAverage == i).length/Reviews.Reviews.length*100) + '%')
            }
        }  

        $('.btn-review').on('click', e => {
            e.preventDefault()
            const $form = $('#form-review').clone();
            const html = $form.html();
            app.modal({
                html,
                height:400,
                className: 'review-modal',
                onComplete: function() {
                    $('.review-modal .the-modal-container form').on('submit', async e => { 
                        e.preventDefault()
                        const
                            form = e.target,
                            ProductID = product.ProductID;
                            $(form).addClass('loading')
                            try{
                               const response = await $.ajax({
                                    url: browsingContext.Common.Urls.BaseUrl + 'shopping/review/create/' + ProductID,
                                    type: 'post',
                                    dataType: 'json',
                                    data: $(form).serialize()
                                })
                                if(response.IsValid){
                                    app.modal({
                                        html: '<div class="success"><p>Avaliação enviada com sucesso!</p></div>',
                                        customClass: 'modal-success'
                                    })
                                }else{
                                    const errors = response.Errors.map(error => {
                                        return `<p>${error.ErrorMessage}</p>`
                                    })
                                    app.modal({
                                        html: errors.join(''),
                                        customClass: 'modal-error'
                                    })
                                }
                            }catch(error){
                                console.log(error)
                            }
                            $(form).removeClass('loading')
                           
                        })
                }
            })
           
        })

        $('body').on('click','.results-paymets .close',(e)=>{
            e.preventDefault();
            $('.results-paymets').removeClass('visible');
        });

        $('body').on('click','.group',(e)=>{
            e.preventDefault();
            const el = e.currentTarget;
            const id= $(el).data('id');
            $('.results-paymets .group').each((k,j)=>{
                $(j).removeClass('selected');
            })
            $(el).addClass('selected') ;
            $('.results-paymets .group-installments').each((k,j)=>{
                $(j).hide();
            })
            $(`.group-installments[data-id="${id}"]`).show();
        })
        /** PAYMENT - BEGIN */

       


  

        /** MEASURES - BEGIN */
        $('.info-measure a').on('click', e => {
            e.preventDefault()
            app.modal({
                href: '/Custom/Content/Themes/Shared/Html/tabela-de-medidas-mobile.html',
                customClass: 'table-measure'
            })
        })
        /** MEASURES - END */


        /** SHARE - BEGIN */
        $('#product-detail .share').on('click', async e => {
            e.preventDefault()

            if (navigator.share) {
                try {
                    await navigator.share({
                        title: document.title,
                        text: product.Name,
                        url: window.location.href,
                    })
                } catch (error) {
                    console.error('Erro ao compartilhar', error)
                }
            } else {
                //alert('O compartilhamento não é suportado neste navegador.')
            }
        })
        /** SHARE - END */

        /** PRODUCT-REVIEW - BEGIN */

        function renderItems() {
            $('.comments').hide(); 
            $('.comments').slice(0, currentCount).show(); 
        }
        function sortItems(order) {
            const items = $('.comments').toArray();
    
            if (order === 'mais-avaliados') {
                items.sort((a, b) => {
                    return $(b).data('star') - $(a).data('star');
                });
            } else if (order === 'recentes') {
                items.sort((a, b) => {
                    return new Date($(b).data('date')) - new Date($(a).data('date'));
                });
            }
    
            $('.comments').empty().append(items); 
            renderItems();
        }

        $('.order-review select').on('change', function() {
            const value = $(this).val();
            sortItems(value);
        })
        let currentCount = 1;
        $('.load-comment').on('click', function() {
            currentCount += 5; 
            renderItems(); 
        });
        renderItems(); 

        
        /** PRODUCT-REVIEW - END */

    } catch (error) {
        console.log(error)
    }
})()

}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Themes/Havanna/Scripts/product.table.comparative.js*/
try{; (function () {
    try {
        async function getProducts() {
			var otherIdsRaw = product.ExtendedMetadatas.find(metadata => metadata.Alias === 'Tabela_Comparativa')?.Value || '';
			
			if (otherIdsRaw != '') {
				var otherIds = otherIdsRaw
					.split(',')
					.map(id => id.trim())
					.filter(id => id); 

				var productIds = [product.ProductID, ...otherIds];
				const response = await $.ajax({
					url: browsingContext.Common.Urls.BaseUrl + `widget/product_list_by_id?Products=${productIds.join(';')}&template=~/Custom/Content/Themes/Temas/Partials/pdp.table.template&ProductIDBase=${product.ProductID}`,

				});
				$('#ComparativeTable').show();
				return response;
			}
        }

        getProducts().then(html => {            
            $('#ComparativeTable .result').html(html);			
        });

    } catch (error) {
        console.log(error);
    }
})();
}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Themes/Havanna/Scripts/associations.js*/
try{;(function() {
	try {
		updateTotal= async function($form) {
			var productID = [$('.cross-sell-product:first .cross-sell-SKUID', $form).val()],
				allSelected = true,
				bundles = [],
				cont = 0;
			var $crossSells = $($form).find(".cross-sell-product");

			$('.cross-sell-product', $form).each(function() {
				var PID = $('.cross-sell-SKUID', this).val(),
					QTT = parseInt($('.cross-sell-quantity', this).val());

				if (PID.length) {
					while (QTT--) {
						productID.push(PID);
					}
				} else {
					allSelected = false;
				}
			});
			if (allSelected) {
				$($form).find('.cross-sell-form-ready').val('true');
				$($form).find('.cross-sell-footer').addClass('form-ready-true').removeClass('form-ready-false');

				$crossSells.each(function(i, el) {
					const children = $('.product-line',el),
						  IsSelected = $(children).attr('data-selected') || false,
						  pid =  $(children).attr('data-pid'),
						  vid =  $(children).attr('data-vid') || pid;
					if(i==0){
						bundles[cont] = pid + 'x' + 1 + 'x' + vid;
						cont++;
					}
					 if(IsSelected=="true" && i>0 ){
						 
						bundles[cont] = pid + 'x' + 1 + 'x' + vid;
						cont++;
					}

				});
				var data = {
					Bundles: bundles.join(),
					AggregateResultItems: true,
					Template: 'wd.product.asyncprice.total.json.template'
				};
				$.ajax({
					url: browsingContext.Common.Urls.BaseUrl + 'widget/product_asyncprice',
					data,
					dataType: 'json',
					type: 'GET',
					success: function(response) {
						if(browsingContext.Common.Config.Catalog.Price.MustShowPrice)
							$($form).find(".total").find(".asyncprice-area").html(response.PriceDescription).show();
					},
					error: function(err) {
						console.log(err);
					}
				});
			} else {
				$($form).find('.cross-sell-form-ready').val('false');
				$($form).find('.cross-sell-footer').addClass('form-ready-false').removeClass('form-ready-true');
				$($form).find('.asyncprice-area').hide();
			}
		};
		$('.cross-sell').find('form').on('submit', async (e)=> {
			e.preventDefault(); 
			const el = e.currentTarget;  	
				$('body').addClass('loading');		
				const response = await $.ajax({
					url: browsingContext.Common.Urls.Shopping.Basket.AddProduct,
					type: 'post',
					dataType: 'json',
					data : $(el).serialize(),
				});
				$.publish(response.IsValid ? '/basket/add/product/success' : '/basket/add/product/error', response);
				$('body').removeClass('loading');
		});
    
		$('.cross-sell-form-data .checkbox input').on('click',function(e){
			const el = e.currentTarget,
				  pai = $(el).closest('.cross-sell-form-data'),
				  form = $(pai).closest('form');
				  var x = 0;
				  $(form).find('.cross-sell-form-data').each((i, item) => {
					if($('.checkbox input',item).is(':checked') ){  
						$(':input', item).each((i,item)=> {
							$(item).removeAttr('disabled').attr('name', $(item).attr('name').replace('{0}', x));
						});
						x++;
					}else{
						$(':input', item).each((i,item)=> {
							if(!$('.checkbox input',item).is(':checked') )
								if($(item).attr('type')!='checkbox')
							$(item).attr('disabled', 'disabled').attr('name', $(item).attr('name').replace(/\[\d+\]/, '[{0}]'))
						});
					}
				});

			if(!$(el).is(':checked')){
				$(pai).parent().find('.product-line').attr('data-selected', false);
			}else{
				console.log(pai)
				$(pai).parent().find('.product-line').attr('data-selected',true);
			}
			updateTotal($(pai).closest('form'));
		});


		$(document).ready(function(){
			if(browsingContext.Common.Config.Catalog.Price.MustShowPrice)
				document.querySelectorAll(".product-price-must-logged").forEach(el => el.remove());
		});

	} catch (error) {
		console.log(error);
	}
}());
}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Themes/Havanna/Scripts/ajustes.js*/
try{;(function() {
	try {

      let mouseX = 0, mouseY = 0;
            $(document).on('mousemove', function (e) {
            mouseX = e.clientX;
            mouseY = e.clientY;
        });

        $('.row-coupon .header').on('click', (e)=> {
            const el = e.currentTarget;
            const texto = $(el).attr("data-coupom");
            navigator.clipboard.writeText(texto).then(function () {
                const $tooltip = $('.message', ".row-coupon");
                $tooltip.css({
                    top: mouseY + 10 + 'px',
                    left: mouseX + 10 + 'px',
                    opacity: 1
                });
                    setTimeout(function () {
                        $tooltip.css('opacity', 0);
                    }, 1500);

            }).catch(function (err) {
                    console.log(err);
            });
        });
        $('body').on('click','.click-copy', (e)=> {
            e.preventDefault();
            const el = e.currentTarget;
            const texto = $(el).find('strong').attr("data-coupom");
            navigator.clipboard.writeText(texto).then(function () {
                $('.coupon-copy').addClass('copied');
            }).catch(function (err) {
                    console.log(err);
            });
        });
	} catch (error) {
		console.log(error);
	}
}());

if($('#product-detail').length){
    if(browsingContext.Common.Basket.PostalCode !=''){
        $('.postalcode-empty .CEP').text(browsingContext.Common.Basket.PostalCode.replace(/(\d{5})(\d{3})/, '$1-$2'))
        $('.IsPostalCode input').val(browsingContext.Common.Basket.PostalCode.replace(/(\d{5})(\d{3})/, '$1-$2'))

         $('#product-detail .delivery form').trigger('submit')
    }



}
   $('.qty-less, .qty-more', '#product-detail .main #btn-buy-main').on('click', e => {
        e.preventDefault()
        const
            el = e.currentTarget,
            content = $(el).closest('#btn-buy-main'),
            input = $('input', content),
            count = Number(input.val()),
            action = $(el).hasClass('qty-less') ? 'qty-less' : 'qty-more'
            if (action == 'qty-less') {
                
                input.val(Math.max(1, count - 1));
            } else {
                
                if( count+1 <= Number(product.StockBalance)){
                    input.val(count + 1)
                }else{
                    input.val(product.StockBalance)
                }
            }
        
    });

    $(  '#product-detail .main .details .change input').on('change',  e => {
        const
            el = e.currentTarget,
            Quantity = Number($(el).val()) || 1,
            max = Number(product.StockBalance)
            
        if(Quantity <= max){

            $(el).val(Quantity)
        }else{
            $(el).val(max)
            
        }
    })


}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Themes/Havanna/Scripts/entrega-hoje.js*/
try{;(async function  () {
    try {
    const RAIO_KM = 10;
    // function getLatLngFromCEP(cep) {
    //     return $.ajax({
    //         url: `https://nominatim.openstreetmap.org/search?postalcode=${cep}&country=Brazil&format=json`,
    //     }).then(res => {
    //         if (!res.length) throw new Error('CEP não encontrado');
    //         return {
    //         lat: parseFloat(res[0].lat),
    //         lon: parseFloat(res[0].lon)
    //         };
    //     });
    // }
    async function getLatLngFromCEP(cep) {
        const res = await $.ajax({
                url: `https://nominatim.openstreetmap.org/search?postalcode=${cep}&country=Brazil&format=json`,
            });

            if (!res.length) throw new Error('CEP não encontrado');

            return {
                lat: parseFloat(res[0].lat),
                lon: parseFloat(res[0].lon)
            };
    }
    function calcularDistancia(lat1, lon1, lat2, lon2) {
    const R = 6371;
    const toRad = g => g * Math.PI / 180;
    const dLat = toRad(lat2 - lat1);
    const dLon = toRad(lon2 - lon1);

    const a =
        Math.sin(dLat / 2) ** 2 +
        Math.cos(toRad(lat1)) *
        Math.cos(toRad(lat2)) *
        Math.sin(dLon / 2) ** 2;

    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return R * c;
    }

    function dentroDoRaio(dist, raio) {
        return dist <= raio;
    }

const calcularDistanciaEntreCeps = async function (cep1, cep2) {
    try {
        const [origem, destino] = await Promise.all([
            getLatLngFromCEP(cep1),
            getLatLngFromCEP(cep2)
        ]);

        const distancia = calcularDistancia(
            origem.lat,
            origem.lon,
            destino.lat,
            destino.lon
        );

        return {
            cepOrigem: cep1,
            cepDestino: cep2,
            distanciaKm: Number(distancia.toFixed(2)),
            raioKm: RAIO_KM,
            dentroDoRaio: dentroDoRaio(distancia, RAIO_KM)
        };

    } catch (err) {
        console.log(err.message);
        return null;
    }
};
    if(browsingContext.Common.Basket.PostalCode != null ){
        const distanciaInfo = JSON.parse(localStorage.getItem('distanciaInfo'));
        if(distanciaInfo?.cepOrigem != browsingContext.Common.Basket.PostalCode){
            const result = await calcularDistanciaEntreCeps(browsingContext.Common.Basket.PostalCode, '01209001');
            localStorage.setItem('distanciaInfo', JSON.stringify(result));
            result.dentroDoRaio ? $('body').addClass('ativar-entrega') : $('body').removeClass('ativar-entrega');
        }else{
            distanciaInfo.dentroDoRaio ? $('body').addClass('ativar-entrega') : $('body').removeClass('ativar-entrega');
        }
    }
    }catch (error) {
        console.log(error)
    }
})();
}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
/*File:~/Custom/Content/Themes/Havanna/JS/ajuste_sugestao_linx.js*/
try{document.addEventListener('DOMContentLoaded', function () {
  function aplicarAjusteSugestoes() {
    // 1. Reposiciona o elemento no container de associações
    const lateral = document.querySelector('aside.lateral');
    const associationsContainer = document.querySelector('#product-detail .associations');

    if (lateral && associationsContainer) {
      associationsContainer.appendChild(lateral);
    }

    // 2. Limpa estilos de testes passados
    document.querySelectorAll('[id^="ajuste-sugestao"]').forEach(el => el.remove());

    // 3. Aplica o CSS customizado
    if (!document.getElementById('ajuste-sugestao-css')) {
      const style = document.createElement('style');
      style.id = 'ajuste-sugestao-css';
      style.innerHTML = `
        /* Container Principal */
        #product-detail .associations aside.lateral,
        #product-detail .associations aside.lateral .wd-product-associations,
        #product-detail .associations aside.lateral .suggestion {
          width: 100% !important;
          max-width: 100% !important;
          display: block !important;
          float: none !important;
          margin: 20px 0 !important;
          padding: 0 !important;
          overflow: visible !important;
          border: none !important;
        }

        /* RESET HEADER */
        #product-detail .associations aside.lateral .header,
        #product-detail .associations aside.lateral .wd-header,
        #product-detail .associations aside.lateral h2,
        #product-detail .associations aside.lateral .underline {
          border: none !important;
          border-bottom: none !important;
          text-decoration: none !important;
          box-shadow: none !important;
          background: transparent !important;
        }

        #product-detail .associations aside.lateral .header::after,
        #product-detail .associations aside.lateral .header::before,
        #product-detail .associations aside.lateral h2::before {
          display: none !important;
          content: none !important;
          border: none !important;
        }

        /* TÍTULO SUGESTÕES */
        #product-detail .associations aside.lateral .header {
          display: flex !important;
          justify-content: flex-start !important;
          align-items: center !important;
          width: 100% !important;
          margin-bottom: 16px !important;
          padding: 0 !important;
        }

        #product-detail .associations aside.lateral h2 {
          font-size: 0 !important;
          margin: 0 !important;
          padding: 0 !important;
        }

        #product-detail .associations aside.lateral h2::after {
          content: "Sugestões" !important;
          font-size: 16px !important;
          font-weight: 600 !important;
          color: #27272a !important;
          text-transform: capitalize !important;
          display: block !important;
          letter-spacing: -0.2px !important;
        }

        /* ESTRUTURA DOS CARDS */
        #product-detail .associations aside.lateral .swiper,
        #product-detail .associations aside.lateral .swiper-container {
          width: 100% !important;
          overflow: visible !important;
        }

        #product-detail .associations aside.lateral .swiper-wrapper,
        #product-detail .associations aside.lateral .products-list,
        #product-detail .associations aside.lateral .product-associations {
          display: flex !important;
          flex-direction: row !important;
          justify-content: flex-start !important;
          align-items: stretch !important;
          gap: 16px !important;
          width: 100% !important;
          transform: none !important;
          overflow-x: auto !important;
          padding: 4px 4px 12px 4px !important;
          scrollbar-width: none !important;
        }

        #product-detail .associations aside.lateral .swiper-wrapper::-webkit-scrollbar {
          display: none !important;
        }

        /* Card com Altura e Formato do Tema */
        #product-detail .associations aside.lateral .swiper-slide {
           width: 270px !important;
           min-width: 240px !important;
           height: auto !important;
           flex: 0 0 auto !important;

           display: flex !important;
           flex-direction: column !important;
           align-items: stretch !important;

           border: 1px solid #e4e4e7 !important;
           border-radius: 12px !important;
           padding: 18px !important;
           background: #fff !important;
        }

        /* Hover Avermelhado Havanna */
        #product-detail .associations aside.lateral .swiper-slide:hover {
          border-color: #d95338 !important;
          box-shadow: 0 4px 12px rgba(217, 83, 56, 0.15) !important;
        }

        #product-detail .associations aside.lateral .product-line {
          border: none !important;
          background: transparent !important;
          padding: 0 !important;
          margin: 0 !important;
          width: 100% !important;
          box-shadow: none !important;
        }

        #product-detail .associations aside.lateral .link-product {
           display: flex !important;
           flex-direction: column !important;
           align-items: flex-start !important;
           gap: 12px !important;
           width: 100% !important;
           height: 100% !important;
           text-decoration: none !important;
        }

        #product-detail .associations aside.lateral .link-product img {
          width: 100% !important;
          height: 170px !important;
          max-height: 170px !important;
          object-fit: contain !important;
          display: block !important;
          margin: 0 auto !important;
        }

        #product-detail .associations aside.lateral .link-product .name,
        #product-detail .associations aside.lateral .link-product h4,
        #product-detail .associations aside.lateral .link-product [class*="title"] {
          font-size: 14px !important;
          font-weight: 600 !important;
          color: #27272a !important;
          line-height: 1.25 !important;
          margin: 0 !important;
          text-align: left !important;
          flex: 1 1 auto !important;
          white-space: normal !important;
        }

        #product-detail .associations aside.lateral .link-product .price,
        #product-detail .associations aside.lateral .link-product .sales-price {
          font-size: 14px !important;
          font-weight: 700 !important;
          color: #18181b !important;
          white-space: nowrap !important;
          flex-shrink: 0 !important;
          text-align: right !important;
        }
      `;
      document.head.appendChild(style);
    }
     
        // Redirecionamento somente mobile
        document.querySelectorAll(
       '#product-detail .associations aside.lateral .swiper-slide'
       ).forEach(card => {

       if (card.dataset.mobileRedirectFinal) return;

       card.dataset.mobileRedirectFinal = 'true';

       card.addEventListener('click', function (e) {

       if (window.innerWidth <= 991) {

       e.preventDefault();
       e.stopPropagation();
       e.stopImmediatePropagation();

       const link = this.querySelector('a[href]') ||
                    this.closest('a[href]');

       if (link && link.href) {
       window.location.href = link.href;
      }

       return false;
     }

   }, true);

 });

    // 4. Desativa a navegação vertical original do Swiper
    const swiperEl = document.querySelector('aside.lateral .swiper') || document.querySelector('.wd-product-associations.suggestion .swiper');
    if (swiperEl && swiperEl.swiper) {
      swiperEl.swiper.destroy(true, true);
    }
  }

  // Executa imediatamente e aguarda breve atraso para componentes dinâmicos da Linx
  aplicarAjusteSugestoes();
  setTimeout(aplicarAjusteSugestoes, 800);
  setTimeout(aplicarAjusteSugestoes, 1500);
});
}catch(e){var se=window.SE || [];se.push(e);window.SE=se; };
