// source --> https://mundomaisverde.com/wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart.min.js?ver=10.6.2 
jQuery(function(t){if("undefined"==typeof wc_add_to_cart_params)return!1;var a=function(){this.requests=[],this.addRequest=this.addRequest.bind(this),this.run=this.run.bind(this),this.$liveRegion=this.createLiveRegion(),t(document.body).on("click",".add_to_cart_button:not(.wc-interactive)",{addToCartHandler:this},this.onAddToCart).on("keydown",".add_to_cart_button:not(.wc-interactive)",{addToCartHandler:this},t=>{" "===t.key&&(t.preventDefault(),t.target.click())}).on("click",".remove_from_cart_button",{addToCartHandler:this},this.onRemoveFromCart).on("keydown",".remove_from_cart_button",this.onKeydownRemoveFromCart).on("added_to_cart",{addToCartHandler:this},this.onAddedToCart).on("removed_from_cart",{addToCartHandler:this},this.onRemovedFromCart).on("ajax_request_not_sent.adding_to_cart",this.updateButton)};a.prototype.addRequest=function(t){this.requests.push(t),1===this.requests.length&&this.run()},a.prototype.run=function(){var a=this,e=a.requests[0].complete;a.requests[0].complete=function(){"function"==typeof e&&e(),a.requests.shift(),a.requests.length>0&&a.run()},t.ajax(this.requests[0])},a.prototype.onAddToCart=function(a){var e=t(this);if(e.is(".ajax_add_to_cart")){if(!e.attr("data-product_id"))return!0;if(a.data.addToCartHandler.$liveRegion.text("").removeAttr("aria-relevant"),a.preventDefault(),e.removeClass("added"),e.addClass("loading"),!1===t(document.body).triggerHandler("should_send_ajax_request.adding_to_cart",[e]))return t(document.body).trigger("ajax_request_not_sent.adding_to_cart",[!1,!1,e]),!0;var r={};t.each(e.data(),function(t,a){r[t]=a}),t.each(e[0].dataset,function(t,a){r[t]=a}),t(document.body).trigger("adding_to_cart",[e,r]),a.data.addToCartHandler.addRequest({type:"POST",url:wc_add_to_cart_params.wc_ajax_url.toString().replace("%%endpoint%%","add_to_cart"),data:r,success:function(a){a&&(a.error&&a.product_url?window.location=a.product_url:"yes"!==wc_add_to_cart_params.cart_redirect_after_add?t(document.body).trigger("added_to_cart",[a.fragments,a.cart_hash,e]):window.location=wc_add_to_cart_params.cart_url)},dataType:"json"})}},a.prototype.onRemoveFromCart=function(a){var e=t(this),r=e.closest(".woocommerce-mini-cart-item");a.data.addToCartHandler.$liveRegion.text("").removeAttr("aria-relevant"),a.preventDefault(),r.block({message:null,overlayCSS:{opacity:.6}}),a.data.addToCartHandler.addRequest({type:"POST",url:wc_add_to_cart_params.wc_ajax_url.toString().replace("%%endpoint%%","remove_from_cart"),data:{cart_item_key:e.data("cart_item_key")},success:function(a){a&&a.fragments?t(document.body).trigger("removed_from_cart",[a.fragments,a.cart_hash,e]):window.location=e.attr("href")},error:function(){window.location=e.attr("href")},dataType:"json"})},a.prototype.onKeydownRemoveFromCart=function(a){" "===a.key&&(a.preventDefault(),t(this).trigger("click"))},a.prototype.updateButton=function(a,e,r,o){if(o=void 0!==o&&o){if(o.removeClass("loading"),e&&o.addClass("added"),e&&!wc_add_to_cart_params.is_cart&&0===o.parent().find(".added_to_cart").length){var d=document.createElement("a");d.href=wc_add_to_cart_params.cart_url,d.className="added_to_cart wc-forward",d.title=wc_add_to_cart_params.i18n_view_cart,d.textContent=wc_add_to_cart_params.i18n_view_cart,o.after(d)}t(document.body).trigger("wc_cart_button_updated",[o])}},a.prototype.updateFragments=function(a,e){e&&(t.each(e,function(a){t(a).addClass("updating").fadeTo("400","0.6").block({message:null,overlayCSS:{opacity:.6}})}),t.each(e,function(a,e){t(a).replaceWith(e),t(a).stop(!0).css("opacity","1").unblock()}),t(document.body).trigger("wc_fragments_loaded"))},a.prototype.alertCartUpdated=function(t,a,e,r){if(r=void 0!==r&&r){var o=r.data("success_message");if(!o)return;t.data.addToCartHandler.$liveRegion.delay(1e3).text(o).attr("aria-relevant","all")}},a.prototype.createLiveRegion=function(){var a=t(".widget_shopping_cart_live_region");return a.length?a:t('<div class="widget_shopping_cart_live_region screen-reader-text" role="status"></div>').appendTo("body")},a.prototype.onAddedToCart=function(t,a,e,r){t.data.addToCartHandler.updateButton(t,a,e,r),t.data.addToCartHandler.updateFragments(t,a),t.data.addToCartHandler.alertCartUpdated(t,a,e,r)},a.prototype.onRemovedFromCart=function(t,a,e,r){t.data.addToCartHandler.updateFragments(t,a),t.data.addToCartHandler.alertCartUpdated(t,a,e,r)},new a});
// source --> https://mundomaisverde.com/wp-content/plugins/woocommerce/assets/js/js-cookie/js.cookie.min.js?ver=2.1.4-wc.10.6.2 
/*! js-cookie v3.0.5 | MIT */
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self,function(){var n=e.Cookies,o=e.Cookies=t();o.noConflict=function(){return e.Cookies=n,o}}())}(this,function(){"use strict";function e(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)e[o]=n[o]}return e}return function t(n,o){function r(t,r,i){if("undefined"!=typeof document){"number"==typeof(i=e({},o,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),t=encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var c="";for(var u in i)i[u]&&(c+="; "+u,!0!==i[u]&&(c+="="+i[u].split(";")[0]));return document.cookie=t+"="+n.write(r,t)+c}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var t=document.cookie?document.cookie.split("; "):[],o={},r=0;r<t.length;r++){var i=t[r].split("="),c=i.slice(1).join("=");try{var u=decodeURIComponent(i[0]);if(o[u]=n.read(c,u),e===u)break}catch(f){}}return e?o[e]:o}},remove:function(t,n){r(t,"",e({},n,{expires:-1}))},withAttributes:function(n){return t(this.converter,e({},this.attributes,n))},withConverter:function(n){return t(e({},this.converter,n),this.attributes)}},{attributes:{value:Object.freeze(o)},converter:{value:Object.freeze(n)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"})});
// source --> https://mundomaisverde.com/wp-content/plugins/shipping-simulator-for-woocommerce/assets/js/form.min.js?ver=2.4.4 
(()=>{window.addEventListener("DOMContentLoaded",()=>{let u=(e,o=document)=>o.querySelector(e),_=(e,o,n)=>e.addEventListener(o,n),k=u("#wc-shipping-sim");if(!k)return;let f=u("#wc-shipping-sim-form"),d=JSON.parse(f.dataset.params),s=u(".input-postcode",f),m=u(".button.submit",f),v=u("#wc-shipping-sim-results"),p=e=>e,t={...d,requesting:!1,hooks:{filterFormData:p,filterXHR:p,filterResults:p,filterProduct:p,filterQuantity:p,filterPostcodeMaxLength:()=>t.postcode_mask?t.postcode_mask.length:15,beforeSubmit:e=>{t.hooks.resultsHandler(""),s.disabled=!0,m.classList.add("loading")},afterSubmit:e=>{s.disabled=!1,m.classList.remove("loading")},resultsHandler:e=>{v.ariaBusy=e?"false":"true",v.innerHTML=e},errorHandler:(e,o)=>{alert(e||t.errors.unexpected),console.error("wc-shipping-simulator request error:",o)},submitHandler:e=>{if(e.preventDefault(),t.requesting)return;let o=g();if(o.id===0)return;t.requesting=!0;let n=o.variation_id?"&variation_id="+o.variation_id:"",a=b(),h=t.hooks.filterFormData(`action=${d.ajax_action}&postcode=${s.value}&product_id=${o.id}&quantity=${a>=1?a:1}${n}`),r=new XMLHttpRequest;r.open("POST",d.ajax_url,!0),r.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),r.timeout=+t.timeout||0,r.onload=()=>{t.requesting=!1,t.hooks.afterSubmit(r);try{let i=JSON.parse(r.responseText);if(i.success){let l=t.hooks.filterResults(i.results_html?i.results_html:"");t.hooks.resultsHandler(l)}else t.hooks.errorHandler(i.error,i)}catch(i){t.hooks.errorHandler(null,i)}},r.ontimeout=()=>{t.requesting=!1,t.hooks.afterSubmit(r),t.hooks.errorHandler(t.errors.timeout,"timeout")},r=t.hooks.filterXHR(r),t.hooks.beforeSubmit(r),r.send(h)},inputMaskHandler:()=>{if(s.maxLength=t.hooks.filterPostcodeMaxLength(),t.postcode_mask){let o=function(n,a,h="X"){if(!a)return n;let r="",i=(n+"").replace(/[^0-9]/g,"");for(let l=0,c=0,w=a.length;l<w&&i[c];l++)h===a[l]?(r+=i[c],c++):(r+=a[l]||"",c=c>0?c--:0);return r};var e=o;_(s,"input",n=>{let a=t.postcode_mask;s.value=o(s.value||"",a),s.maxLength=t.postcode_mask.length}),s.dispatchEvent(new Event("input"))}}}};window.wc_shipping_simulator=t,document.dispatchEvent(new Event("wc_shipping_simulator:init")),k.style.display=t.root_display,t.hooks.inputMaskHandler&&t.hooks.inputMaskHandler(),_(f,"submit",t.hooks.submitHandler),t.auto_submit&&t.postcode_mask&&_(s,"input",e=>{let o=t.hooks.filterPostcodeMaxLength();o>0&&s.value.length===o&&(s.blur(),m.click())});function g(){let e={type:d.product_type,id:d.product_id};if(e.type==="variable"){let o=u(".variations_form .variation_id");if(e.variation_id=o?o.value:0,t.requires_variation&&!e.variation_id){let n=wc_add_to_cart_variation_params?wc_add_to_cart_variation_params.i18n_make_a_selection_text:"";t.hooks.errorHandler(n,"no_variation_selected"),e.id=0}}return t.hooks.filterProduct(e)}function b(){let e=1,o=u('.cart [name="quantity"]');return o&&(e=o.value),t.hooks.filterQuantity(+e||1)}});})();
// source --> https://mundomaisverde.com/wp-content/plugins/melhor-envio-cotacao/assets/js/shipping-product-page.js?ver=1707ae824362bebd67785847eed20c17 
(function ($) {
    'use strict';
    $(function () {
        toggleCalculator();
        $(document).on('keyup', '.iptCep', function (e) {
            jQuery('.observation-shipping-free').hide();
            resetarTabela();
            if ($(this).val().length === 9) {
                var url = $('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto #calculo_frete_endpoint_url').val();
                var cep = $(this).val();
                var id_produto = $('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto #id_produto').val();

                if ($(e.target).is('a#cfpp_credits')) { return; }

                var errors = [];
                if (errors.length > 0) {
                    var row = '';
                    row = '<tr><td colspan="3">Ocorreu um erro ao obter informações sobre o valor do frete</td></tr>';
                    errors.map(item => {
                        row += `<tr><td colspan="3">${item}</td></tr>`;
                        return row;
                    });
                    $('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto .resultado-frete table tbody').append(row);
                    esconderLoader();
                    exibirTabela();
                    return false;
                }

                let inpCEP = $(this);
                inpCEP.attr('disabled', 'disabled');
                exibirLoader();
                esconderTabela();
                resetarTabela();

                let qty = 1;
                let inpQty = $('.quantity .qty:visible').val();
                if (typeof inpQty != 'undefined') {
                    qty = inpQty;
                }

                $.ajax({
                    url: url,
                    type: "POST",
                    data: {
                        'action': 'cotation_product_page',
                        'data': {
                            'cep_origem': cep,
                            'id_produto': id_produto,
                            'quantity': qty
                        }
                    },
                    error: function (jqXHR, exception) {
                        inpCEP.removeAttr('disabled');
                        inpCEP.val('');
                        alert(jqXHR.responseJSON.error);
                        esconderLoader();
                        esconderTabela();
                        resetarTabela();
                        return false;
                    },
                    success: function (response) {
                        $('#destiny-shipping-mehor-envio').text('Frete para ' + response.data.destination);
                        var row = '';
                        let  data  = response.data.quotations;
                        data.map(item => {
                            if (item.observations && item.observations !== 'Frete Grátis') {
                                jQuery('.observation-shipping-free').show();
                                jQuery('.observation-shipping-free').html(item.observations);
                            }
                            let name = item.name
                            if (!item.delivery_time) {
                                item.delivery_time = '';
                            }
                            row += `<tr><td>${name} ${item.delivery_time}: ${item.price}</td></tr>`;
                        });

                        if (row == '') {
                            row = '<tr><td colspan="3">Desculpe, o cálculo de frete para este produto só está disponível no Carrinho, por favor, prossiga com a compra normalmente.</td></tr>';
                        }

                        $('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto .resultado-frete table tbody').append(row);
                        esconderLoader();
                        exibirTabela();
                        inpCEP.removeAttr('disabled');
                        inpCEP.val('');
                    }
                });
            }
        })

        function exibirLoader() {
            $('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto #calcular-frete').css('display', 'none');
            $('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto #calcular-frete-loader').css('display', 'flex');
        }

        function esconderLoader() {
            $('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto #calcular-frete').css('display', 'inline-block');
            $('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto #calcular-frete-loader').css('display', 'none');
        }

        function exibirTabela() {
            $('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto .resultado-frete').show();
        }

        function esconderTabela() {
            $('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto .resultado-frete').hide();
        }

        function resetarTabela() {
            $('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto .resultado-frete table tbody').html('');
            $('#destiny-shipping-mehor-envio').text('');
        }

        $(".single_variation_wrap").on("show_variation", function (event, variation) {
            resetarTabela();
            esconderTabela();
            $('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto #calculo_frete_produto_preco').val(variation.display_price.toFixed(2));
        });
    });
})(jQuery);
// source --> https://mundomaisverde.com/wp-content/plugins/melhor-envio-cotacao/assets/js/shipping-product-page-variacao.js?ver=1707ae824362bebd67785847eed20c17 
(function (jQuery) {
    'use strict';
    jQuery(function () {
        jQuery(document).ready(function () {
            jQuery(document).change(function () {
                let variation_id = jQuery('.variation_id').val();
                if (variation_id) {
                    jQuery('#id_produto').val(variation_id);
                }
            });
        })
    });
})(jQuery);
// source --> https://mundomaisverde.com/wp-content/plugins/melhor-envio-cotacao/assets/js/calculator.js?ver=1707ae824362bebd67785847eed20c17 
function toggleCalculator() {

    let widthProduct = document.querySelector('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto #calculo_frete_produto_altura');
    if (!widthProduct) {
        return;
    }

    document.querySelector('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto').style.display = 'block';
}

function getDimension() {
    let dimensions = {
        'heigth': document.querySelector('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto #calculo_frete_produto_altura').value,
        'width': document.querySelector('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto #calculo_frete_produto_largura').value,
        'length': document.querySelector('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto #calculo_frete_produto_comprimento').value,
        'weight': document.querySelector('#woocommerce-correios-calculo-de-frete-na-pagina-do-produto #calculo_frete_produto_peso').value
    }
    return dimensions;
}

/**
 *  mask to replace non number
 * @param {string} content - number to format
 * @returns {string}
 * @example
 * const valueToFormat = '12345678'
 * numberMask(valueToFormat);
 */
function numberMask(content) {
    return content.replace(/[^0-9-]+/g, "");
}

/**
 *  mask to format postal code
 * @param {string} content - postal code number
 * @returns {string}
 * @example
 * const valueToFormat = '12345678'
 * postalCodeMask(valueToFormat);
 */
 function postalCodeMask(content, input) {
    let value = content;
    let formatedValue = '';

    if(isNaN(content)) {
        input.value = numberMask(content);

        return;
    }

    //regex to add " - " in position 5 of cep: EX:123456-78
    formatedValue = value.replace(/(\d{5})(\d{1,2})$/, "$1-$2");
    input.value = formatedValue;
}

/**
 *  this function is used to apply the postal code mask in the input to calculate the quotation
 */
function usePostalCodeMask(evt='') {
    const inputDefault = evt ? evt.target : evt;
    const inputShortcode = document.querySelector('.iptCepShortcode');


    if(inputDefault) {
        const content = inputDefault.value;
        postalCodeMask(content, inputDefault);
    }

    if(inputShortcode) {
        const content = inputShortcode.value;
        postalCodeMask(content, inputShortcode);
    }
}

function validateNumber(event) {
    var key = window.event ? event.keyCode : event.which;
    if (event.keyCode === 8 || event.keyCode === 46) {
        return true;
    } else if (key < 48 || key > 57) {
        return false;
    } else {
        return true;
    }
};