/*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/grid.js*/
try{; (function () {
    try {
        const init = () => {
        }
        //init()

        const showAppliedFacets = () => {

            $('.selected-filters').empty()
            $('.wd-facet-group .selected-facets .selected-facet').each((k, i) => {
                $('ul > li', i).each((k, i) => {
                    const
                        url = $(i).attr('data-url'),
                        label = $('.option-label', i).text()

                    $('.selected-filters').append(`
                            <a href="javascript:void(0)" data-url="${url}">
                                ${label}
                            </div>
                        `)
                })
            })
            return
        }
        showAppliedFacets()

        $(window).on('hashchange', function (e) {
            $('body').addClass('faceting')     
            const hash = document.location.hash;
        })
        
        $('body').on('onFacetingComplete ', (e) => {
            if ($('.wd-facet-group .selected-facets').hasClass('hidden')) {
                $('.selected-filters').empty()
            } else {
                showAppliedFacets()
            }
            $('body').removeClass('faceting')
        })

        $('body').on('onBuildFacetingComplete', (e) => {
            $('body').removeClass('faceting')
        })

        $('.filters .part-1 a').on('click', e => {
            e.preventDefault()
            $('body').toggleClass('blocked show-facets')
        })

        if (detectmob()) {
            $('.filters .btn-filter').on('click', e => {
                e.preventDefault()

                $('body').toggleClass('blocked show-facets')
            })
        } else {
            $('.options .view a').on('click', e => {
                e.preventDefault()
                const
                    el = e.target,
                    a = $(el).closest('a'),
                    view = $(a).attr('data-view')

                $('.options .view a').removeClass('selected')
                $(a).addClass('selected')

                $('#grid').attr('data-view', view)
            })
        }

        new Swiper('.products .brands .swiper', {
            loop: false,
            slidesPerView: 'auto',
            spaceBetween: 8,
            navigation: {
                nextEl: ".swiper-button-next",
                prevEl: ".swiper-button-prev",
            },
        })

        /**
         * remove facetas
         */
        $(document).on('click', '.selected-filters a', e => {
            e.preventDefault()
            const
                el = e.currentTarget,
                url = $(el).attr('data-url')

            $(`.wd-facet-group .selected-facet li[data-url="${url}"] .clear-filter`).trigger('click')
        })


    } catch (error) {
        console.log(error)
    }
})()
}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; };
