// source --> https://corpsequeenstore.com/wp-content/plugins/woocommerce/assets/js/frontend/woocommerce.min.js?ver=10.6.2 
function on_keydown_remove_from_cart(e){" "===e.key&&(e.preventDefault(),e.currentTarget.click())}function focus_populate_live_region(){var e=["woocommerce-message","woocommerce-error","wc-block-components-notice-banner"].map(function(e){return"."+e+'[role="alert"]'}).join(", "),o=document.querySelectorAll(e);if(0!==o.length){var t=o[0];t.setAttribute("tabindex","-1");var n=setTimeout(function(){t.focus(),clearTimeout(n)},500)}}function refresh_sorted_by_live_region(){var e=document.querySelector(".woocommerce-result-count");if(e){var o=e.innerHTML;e.setAttribute("aria-hidden","true");var t=setTimeout(function(){e.setAttribute("aria-hidden","false"),e.innerHTML="",e.innerHTML=o,clearTimeout(t)},2e3)}}function on_document_ready(){focus_populate_live_region(),refresh_sorted_by_live_region()}jQuery(function(e){e(".woocommerce-ordering").on("change","select.orderby",function(){e(this).closest("form").trigger("submit")}),e("input.qty:not(.product-quantity input.qty)").each(function(){var o=parseFloat(e(this).attr("min"));o>=0&&parseFloat(e(this).val())<o&&e(this).val(o)});var o="store_notice"+(e(".woocommerce-store-notice").data("noticeId")||"");if("hidden"===Cookies.get(o))e(".woocommerce-store-notice").hide();else{function t(o){["Enter"," "].includes(o.key)&&(o.preventDefault(),e(".woocommerce-store-notice__dismiss-link").click())}e(".woocommerce-store-notice").show(),e(".woocommerce-store-notice__dismiss-link").on("click",function n(r){Cookies.set(o,"hidden",{path:"/"}),e(".woocommerce-store-notice").hide(),r.preventDefault(),e(".woocommerce-store-notice__dismiss-link").off("click",n).off("keydown",t)}).on("keydown",t)}e(".woocommerce-input-wrapper span.description").length&&e(document.body).on("click",function(){e(".woocommerce-input-wrapper span.description:visible").prop("aria-hidden",!0).slideUp(250)}),e(".woocommerce-input-wrapper").on("click",function(e){e.stopPropagation()}),e(".woocommerce-input-wrapper :input").on("keydown",function(o){var t=e(this).parent().find("span.description");if(27===o.which&&t.length&&t.is(":visible"))return t.prop("aria-hidden",!0).slideUp(250),o.preventDefault(),!1}).on("click focus",function(){var o=e(this).parent(),t=o.find("span.description");o.addClass("currentTarget"),e(".woocommerce-input-wrapper:not(.currentTarget) span.description:visible").prop("aria-hidden",!0).slideUp(250),t.length&&t.is(":hidden")&&t.prop("aria-hidden",!1).slideDown(250),o.removeClass("currentTarget")}),e.scroll_to_notices=function(o){o.length&&e("html, body").animate({scrollTop:o.offset().top-100},1e3)},e('.woocommerce form .woocommerce-Input[type="password"]').wrap('<span class="password-input"></span>'),e(".woocommerce form input").filter(":password").parent("span").addClass("password-input"),e(".password-input").each(function(){const o=e(this).find("input").attr("id");e(this).append('<button type="button" class="show-password-input" aria-label="'+woocommerce_params.i18n_password_show+'" aria-describedBy="'+o+'"></button>')}),e(".show-password-input").on("click",function(o){o.preventDefault(),e(this).hasClass("display-password")?(e(this).removeClass("display-password"),e(this).attr("aria-label",woocommerce_params.i18n_password_show)):(e(this).addClass("display-password"),e(this).attr("aria-label",woocommerce_params.i18n_password_hide)),e(this).hasClass("display-password")?e(this).siblings(['input[type="password"]']).prop("type","text"):e(this).siblings('input[type="text"]').prop("type","password"),e(this).siblings("input").focus()}),e("a.coming-soon-footer-banner-dismiss").on("click",function(o){var t=e(o.target);e.ajax({type:"post",url:t.data("rest-url"),data:{woocommerce_meta:{coming_soon_banner_dismissed:"yes"}},beforeSend:function(e){e.setRequestHeader("X-WP-Nonce",t.data("rest-nonce"))},complete:function(){e("#coming-soon-footer-banner").hide()}})}),"undefined"==typeof wc_add_to_cart_params&&e(document.body).on("keydown",".remove_from_cart_button",on_keydown_remove_from_cart),e(document.body).on("item_removed_from_classic_cart updated_wc_div",focus_populate_live_region)}),document.addEventListener("DOMContentLoaded",on_document_ready);
// source --> https://corpsequeenstore.com/wp-content/plugins/melhor-envio-cotacao/assets/js/shipping-product-page.js?ver=6.9.4 
(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://corpsequeenstore.com/wp-content/plugins/melhor-envio-cotacao/assets/js/shipping-product-page-variacao.js?ver=6.9.4 
(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://corpsequeenstore.com/wp-content/plugins/melhor-envio-cotacao/assets/js/calculator.js?ver=6.9.4 
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;
    }
};