function isMobile() {
    var a = navigator.userAgent || navigator.vendor || window.opera;
    if ((/mac/i.test(a)) && !(/iphone/i.test(a))) return false;
    if ((/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|ip(hone|od|ad)|iris|kindle|lge|maemo|midp|mmp|mobile|o2|opera m(ob|in)i|palm( os)?|p(ixi|re)\/|plucker|pocket|psp|smartphone|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce; (iemobile|ppc)|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a)))
        return true;
    else
        return false;
}

function rebind_img_js_detalhe(){
    $('img.js-detalhe').hover(
        function(){
            var obj = $(this);
  
            if (!obj.data('original-src')) {
                obj.data('original-src', obj.attr('src'));
            }
  
            if (obj.data('src1')) {
                var indice = Number(obj.data('indice'));
                var src = 'src' + indice;
                var newImg = new Image();
  
                if (!obj.data(src)) {
                    src = 'src1';
                    indice = 1;
                } else {
                    indice++;
                }
  
                obj.data('indice', indice);
  
                obj.animate({opacity: .9}, 100);
  
                if (!obj.data('load')) {
                    newImg.onload = function() {
                        obj.data('load', 1);
                        obj.attr('src', this.src);
                        obj.animate({opacity: 1}, 100);
                    };
  
                    newImg.src = obj.data(src);
                } else {
                    obj.attr('src', obj.data(src));
                    obj.animate({opacity: 1}, 100);
                }
            }
        },
        function(){
            var obj = $(this);
            if (obj.data('original-src')) {
                obj.attr('src', obj.data('original-src'));
                obj.animate({opacity: 1}, 100);
            }
        }
    );
  }
  
  $(document).ready(function() {
    rebind_img_js_detalhe();
  });


function formataMoeda(objTextBox, e) {

    var SeparadorMilesimo = '.';
    var SeparadorDecimal = ',';
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';

    //var whichCode = (window.Event) ? e.which : e.keyCode;

    var whichCode = (document.all) ? e.keyCode : e.which;

    //alert(whichCode);

    if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8))
        return true;

    key = String.fromCharCode(whichCode); // Valor para o c�digo da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inv�lida
    len = objTextBox.value.length;
    for (i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for (; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i)) != -1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0' + SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0' + SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
            objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}

function formataMoedaValor(valor) {
    var SeparadorMilesimo = '.';
    var SeparadorDecimal = ',';
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';

    valor = valor.replace(".", "");

    aux = valor;
    len = aux.length;
    if (len == 0) valor = '';
    if (len == 1) valor = '0' + SeparadorDecimal + '0' + aux;
    if (len == 2) valor = '0' + SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        valor = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
            valor += aux2.charAt(i);
        valor += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return valor;
}

function formata(v) {
    var s = new String(v);
    if (s.indexOf('.') == -1) {
        return float2moeda(s) + ',00';
    }
    else {
        var x = s.split('.');
        if (x[1].length >= 2) {
            return float2moeda(x[0]) + ',' + x[1].substr(0, 2);
        }
        else {
            return float2moeda(x[0]) + ',' + x[1] + '0';
        }
    }
}

function float2moeda(num) {
    x = 0;

    if (num < 0) {
        num = Math.abs(num);
        x = 1;
    }

    if (isNaN(num)) num = "0";

    num = Math.floor((num * 100 + 0.5) / 100).toString();

    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)

        num = num.substring(0, num.length - (4 * i + 3)) + '.' + num.substring(num.length - (4 * i + 3));
    ret = num;

    if (x == 1) ret = ' - ' + ret;

    return ret;
}

function toFloat(str) {
    str = new String(str);
    str = new Number(str.replace(',', '.'));
    return str;
}

function addSubMenu(linkId, ulId) {

    linkId.bind('mouseover', function () {

        var elem = $(this);

        //console.log(linkId);

        if (linkId.data('isOver')) {
            return;
        }

        linkId.data('isOver', true);

        ulId.slideDown('fast', function () {

            ulId.unbind('mousemove');
            ulId.unbind('mouseout');


            var maxHeight = Math.max.apply(null, $(".menu-categorias-pai-item .menu-categorias-filho").map(function () {
                // return $(this).height();
                return $(this).outerHeight();
            }).get());

            //$('.menu-categorias-pai .menu-categorias-filho').css('min-height',maxHeight);
            //$('.menu-categorias-filho').css('min-height','auto');

            ulId.bind('mousemove', function () {
                linkId.data('isOver', true);
                linkId.addClass('selected');
            });

            ulId.bind('mouseout', function () {
                linkId.data('isOver', false);
                setTimeout(
                    function () {
                        if (!linkId.data('isOver')) {
                            ulId.slideUp('fast', function () {
                                linkId.removeClass('selected');
                            });

                        }
                    }
                    , 500);
            });
        });
    });

    linkId.bind('mouseout', function () {

        linkId.data('isOver', false);

        setTimeout(
            function () {
                if (!linkId.data('isOver')) {
                    ulId.slideUp('fast', function () {
                        linkId.removeClass('selected');
                    });
                }
            }
            , 500);

    });
}

$(document).ready(function () {

    $('.produtos').click(function () { $('.d-menu-categorias').slideToggle(); });
    // Fecha os alertas
    var display = $('.alertas').css('display');
    if (display == 'block') {
        setTimeout(function () { $('.alertas').hide('slow'); }, 6000)
    }
    function redimensionar() {
        var height = $('.site').height();
        if (height < 640) {
            var cH = $(document).height();
            $('.site').css('height', cH - 303);
        }

        var tamanhoJanela = $(window).width();
        if (tamanhoJanela > 1470) $('div.container-categorias div.det').css('right', 0);
        else {
            var tamanhoImagem = $('div.container-categorias div.det').width();
            var tamanhoSite = 980;
            var alinhamento = 14;
            var right = (tamanhoImagem - ((tamanhoJanela - tamanhoSite) / 2)) * -1;
            right = right + alinhamento;
            $('div.container-categorias div.det').css('right', right);
        }
    }

    $(window).bind('resize', function () { redimensionar(); });
    // window.onresize = redimensionar;
    redimensionar();
    $('#menunav .menuprodutos').bind('click', function () {
        if ($('#menunav .menuprodutos').data('click')) {
            return true;
        }
        $('#menunav .menuprodutos').data('click', true);
        $('#menunav2').slideToggle();
        return false;
    });

    // rebind_img_js_detalhe();

    $('img.js-detalhex').on('swiperight', swiperightHandler);

    // $('.abre-mobile').bind('click',function(){
    //     if($('#menu-mobile').hasClass('hidden-xs')){
    //         $('#menu-mobile').hide().removeClass('hidden-xs');
    //         $('#menu-mobile').slideDown();
    //     }
    //     else {
    //         $('#menu-mobile').slideUp('fast');
    //         $('#menu-mobile').addClass('hidden-xs');
    //     }
    // });

    /*	LOGIN FORM MENU */
    $('#formlogin').ajaxForm({
        dataType: 'json'
        , beforeSend: function () {
            $('#formlogin').attr('disabled', true).css('opacity', .7);
            $('#d-erro').hide().html('');
        }
        , success: function (out) {
            // console.log(out);
            if (out[0] == 1) {
                window.location.href = new String(out[3]);
            }
            else {
                // set_erro();
                $('#d-erro').html(out[1]).slideDown();
                $('#formlogin').attr('disabled', false).css('opacity', 1);
            }
        }
    });
    // Acerta largura dos itens principais do menu de categorias

    // var menu_categorias = $('.menu-categorias');
    // var menu_categorias = $('.menu-categorias-pai');

    // menu_categorias.find('li.menu-categorias-pai-item').css('width', (menu_categorias.width() / menu_categorias.find('li.menu-categorias-pai-item').length) + 'px');

    // var maxHeight = Math.max.apply(null, $(".menu-categorias-pai .menu-categorias-filho").map(function(){
    //     return $(this).outerHeight();
    // }).get());

    // $('.menu-categorias-wrap .menu-categorias-pai .menu-categorias-filho').css('min-height',maxHeight);
    // addSubMenu($('.menu-categorias-pai li.menu-categorias-pai-item'),$('.menu-categorias-pai ul.menu-categorias-filho'));

    // ABRE LOGIN
    // var y=1;
    // $('.s-login').bind('click',function(){
    //     if(y){
    //         $("#resumo_car").hide();
    //         $('.dados-login').show();
    //         $('.dados-logado').show();
    //         y=0;
    //     }else{
    //         $('.dados-login').hide();
    //         $('.dados-logado').hide();
    //         $('#esqueciSenha').hide();
    //         $('.conteudo-login').show();
    //         y=1;
    //     }
    // });

    //ABRE SACOLA
    // var x = 1;
    // $("#sacola").click(function(){
    //     if(x){
    //         $("#resumo_car").show();
    //         $('.dados-login').hide();
    //         x=0;
    //     }else{
    //         $("#resumo_car").hide();
    //         x=1;
    //     }
    // });

    // $(".categoria-mobi").children("ul").children("li").children("a").bind("click",function(e){
    //     _id = $(this).data("id");
    //     if(elem = $(".categoria-mobi").children("ul").children("li").children(".menu_categorias_filho_"+_id)){
    //         /** Abrir sub-categorias **/
    //         $(elem).addClass('sub_menu');
    //         e.preventDefault();
    //     }

    // });

    //MAXIMO INPUT BUSCA
    var buscar = 1;
    $('.input_busca_form').click(function () {
        if (buscar) {
            $('.d-menu-busca').addClass('super-busca');
            $('.fundo-menu').addClass('aberto-fundo-busca');
            buscar = 0;
        }
    });

    $('.fundo-menu').click(function () {
        $('.d-menu-busca').removeClass('super-busca');
        $('.fundo-menu').removeClass('aberto-fundo-busca');
        buscar = 1;
    });

    /* CONTADOR de CARACTER v1.0 By Naza */
    $("._count").each(function () { setCounts(this); });

    $("._count").bind("keyup", function () {
        setCounts(this);
        if (_caracs >= _count) this.value = this.value.substring(0, _count);
    });

});

function swiperightHandler(event) {
    // console.log(1);

    var obj = $(event.target);
    // console.log(obj);

    if (obj.data('src1')) {
        var indice = new Number(obj.data('indice'));
        var src = 'src' + indice;
        var newImg = new Image;

        if (!obj.data(src)) {
            src = 'src1';
            indice = 1;
        }
        else {
            indice++;
        }

        obj.data('indice', indice);

        newImg.onload = function () {
            obj.attr('src', this.src);
            obj.animate({ opacity: 1 }, 100);
        };

        obj.animate({ opacity: .9 }, 100);
        newImg.src = obj.data(src);

    }

}
function setCounts(el) {
    _count = eval($(el).data("count"));
    _caracs = eval(el.value.length);
    _name = el.name.replace(/[\[\]]/g, "_");
    _rest = (_count - _caracs) < 0 ? 0 : (_count - _caracs);
    if ($("." + _name).size() > 0) {
        $("." + _name).html("Caracteres restantes : " + _rest + "");
    } else {
        $(el).after("<p class='" + _name + "'>Caracteres restantes : " + _rest + "</p>");
    }
}
/* ## */

/** busca site */
function buscar() {
    if (el = document.getElementById("_busca_form")) {
        er = new RegExp(/show/g);
        if (!er.test(el.className)) {
            el.classList.add("show");
            if (input = document.getElementById("input_busca_form")) input.focus();
        } else {
            el.classList.remove("show");
        }
    }
}

function abreMenuCategoria(elem, e) {
    e.preventDefault();
    if (container = document.getElementById("menu_categorias")) {
        var er = new RegExp(/show/g);
        var _class_name = "show_menu_categoria_height";
        var _head = document.getElementsByTagName("head")[0];
        if (!er.test(container.className)) {  /* TESTA SE MENU ESTÁ ABERTO */
            if (!(style_h = document.getElementById("show_menu_categoria_height"))) { /** TESTE SE ESTILO COM ALTURA FOI CARREGADO */
                var _class_style = "." + _class_name + "{height:" + container.childNodes[0].offsetHeight + "px;}";/* CRIA ESTILO COM ALTURA DO MENU CARREGADO COM AS CATEGORIAS */
                /** TRECHO ABAIXO CRIA BLOCO STYLE NO HEAD DO SITE E ADICIONA O ESTILO CRIADO ACIMA, PARA A ALTURA DO MENU DE CATEGORIAS */
                ((head, el, class_style) => { style = document.createElement(el); style.id = _class_name; style.innerHTML = class_style; head.appendChild(style); })
                    (_head, "STYLE", _class_style);
                /** */
            }
            container.classList.add("show");
            container.classList.add(_class_name);
        } else {
            container.classList.remove("show");
            container.classList.remove(_class_name);
        }
    }
}


/*** LOGIN  ***/
$(document).ready(function () {
    $('#formlogin').ajaxForm({
        dataType: 'json'
        , type: 'POST'
        , success: function (out) {
            if (out.status) {
                $('#formlogin_MSG').html(out.msg).addClass('alert-success').fadeIn();
                //$('#news_bt_marketing').attr('disabled', true).val('OK, MENSAGEM ENVIADA');
                $('#news_bt_marketing').attr('disabled', false).val('ENVIAR');
                document.getElementById("formlogin").reset();
                setTimeout(function () {
                    location.reload();
                }, 800);
            }
            else {
                $('#formlogin_MSG').html(out.msg).addClass('alert-danger').fadeIn();
                $('#news_bt_marketing').attr('disabled', false).val('ENVIAR');
                setTimeout(function () {
                    $('#formlogin_MSG').fadeOut().html("").addClass('alert-success');
                }, 1700);
            }
        }
        , beforeSend: function () {
            $('#news_bt_marketing').attr('disabled', true).val('AGUARDE...');
            $('#formlogin_MSG').hide().removeClass('alert-danger').removeClass('alert-success');
        }
        , error: function () {
            $('#formlogin_MSG').html('Falha ao tentar salvar e-mail.').addClass('alert-danger').fadeIn();
            $('#news_bt_marketing').attr('disabled', false).val('ENVIAR');
        }
    });

    // Abre esqueci senha
    $('.a_esq_senha').click(function () {
        $('.conteudo-login').hide();
        $('#esqueciSenha').show();
    });


});

/*** MINHA CONTA ***/
function loadItens(id) {

    display = $(".js-itens-" + id).css('display');

    if ($(".js-itens-" + id).html() == '') {
        $(".js-itens-" + id).html('Aguarde ...');
    }

    if (display == 'none') {
        $(".js-itens-" + id).show('slow');
        if ($(".js-itens-" + id).html() == '' || $(".js-itens-" + id).html() == 'Aguarde ...') {
            $.ajax({
                url: index + 'minhascompras/?get_itens=' + id
                , success: function (out) {
                    $(".js-itens-" + id).html(out);
                }
            });
        }
    } else {
        $(".js-itens-" + id).hide('slow');
    }
}
function abreOrcamento() {

}

// $(document).ready(function(){
//     $(".h_proposta").bind("click",function(){
//         id = $(this).data('id');
//         $.ajax({
//             url: index+'minhascompras/?get_proposta='+id
//             ,dataType : 'json'
//             ,success:function(out){
//                 if(out['status']==1){
//                     $('#box_orcamento_'+out['id']).show();
//                     $('#orcamento_'+out['id']).html(out['msg']);
//                 }

//                 if(out['status']==0){
//                     //alert(out['msg']);
//                     Swal.fire({
//                         //icon: 'success',
//                         title: 'Ops...',
//                         text: out['msg'],
//                         //footer: '<a href>Why do I have this issue?</a>'
//                       })
//                 }
//             }
//         });
//     });

//     swiperPromocional();

// });
function swiperPromocional() {
    if (document.getElementsByClassName("produtos_selecionados").length > 0) {
        var produtosselecionados = new Swiper('.produtos_selecionados', {
            slidesPerView: 1,
            spaceBetween: 20,
            loop: false,
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            }
        });
    }
};
$(document).ready(function () {
    var _pagina = $("#vermais_vistos").data("pagina");
    $("#vermais_vistos").bind("click", function () {
        _indice = $(this).data("indice");
        $.ajax({
            url: "{index}getMoreProdVistos/" + _indice
            , dataType: "json"
            , success: function (out) {
                //console.log(out);
                $("#produtos_vistos").append(out.produtos);
                if (out.pagina > _pagina) {
                    $("#vermais_vistos").remove();
                }

                $("#vermais_vistos").data("indice", out.pagina);
                //$("#produtos_vistos");
            }
            , error: function () {
                console.log("Ocorreu um erro.");
            }
        });
    });


    /*** ABRE LOGIN RAPIDO ****/
    $('#finaliza_desconectado').click(function () {
        //    $('.fundo-menu').fadeIn();
        $('.container-login-rapido').show();
        $('html, body').animate({ scrollTop: 750 }, 'slow');
    });

    /*** FORM NEWSLETTER RODAPE */
    $('#formCadastraNewsletter').ajaxForm({
        dataType: 'json'
        , type: 'POST'
        , success: function (out) {
            if (out.status) {
                $('#formCadastraNewsletter_MSG').html(out.msg).addClass('alert-success').fadeIn();
                //$('#news_bt_marketing').attr('disabled', true).val('OK, MENSAGEM ENVIADA');
                $('#news_bt_marketing').attr('disabled', false).val('');
                document.getElementById("formCadastraNewsletter").reset();
            }
            else {
                $('#formCadastraNewsletter_MSG').html(out.msg).addClass('alert-danger').fadeIn();
                $('#news_bt_marketing').attr('disabled', false).val('');
            }
        }
        , beforeSend: function () {
            $('#news_bt_marketing').attr('disabled', true).val('AGUARDE...');
            $('#formCadastraNewsletter_MSG').hide().removeClass('alert-danger').removeClass('alert-success');
        }
        , error: function (error) {
            console.log(error);
            $('#formCadastraNewsletter_MSG').html('Falha ao tentar salvar e-mail.').addClass('alert-danger').fadeIn();
            $('#news_bt_marketing').attr('disabled', false).val('');
        }
    });

    // $('.d-menu').on('mouseenter',function(){
    //     $('.menu-prod').slideToggle();
    // });


    // $('.d-menu').click(function(){
    //     $('.menu-prod').slideToggle();
    // });


    // $('.link_pai').click(function(event){
    //     if($(this).hasClass('li_menu_prod')){
    //         id = $(this).data('id');
    //         $('.sub_filho_'+id).addClass('active_sub');
    //         event.preventDefault();
    //         //alert('deu certo');
    //     }
    //     else{
    //         alert('nao deu certo');
    //     }
    // });
    // $('.volta_sub').click(function(){
    //     $('.sub_filho_'+id).removeClass('active_sub');
    // });

    $(document).ready(function () {
        $('#formBriefing').ajaxForm({
            dataType: 'json'
            , type: 'POST'
            , success: function (out) {
                if (out.status) {
                    $('#formBriefing_MSG').html(out.msg).addClass('alert-success').fadeIn();
                    //$('#news_bt_marketing').attr('disabled', true).val('OK, MENSAGEM ENVIADA');
                    $('#bt_brief').attr('disabled', false).val('ENVIAR MENSAGEM');
                    document.getElementById("formBriefing").reset();
                }
                else {
                    for (var key in out.error) {
                        _class = 'briefing' + key;
                        $("." + _class).remove();
                        $(".m-ajax[name='briefing[" + key + "]']").addClass('alert-danger').after("<p class='briefing" + key + "' style='color:#a94442;'>" + out.error[key] + "</p>");
                    }

                    //$('#formBriefing_MSG').html(out.msg).addClass('alert-danger').fadeIn();
                    $('#bt_brief').attr('disabled', false).val('ENVIAR');
                }
            }
            , beforeSend: function () {
                $('#bt_brief').attr('disabled', true).val('AGUARDE...');
                $('#formBriefing_MSG').hide().removeClass('alert-danger').removeClass('alert-success');
            }
            , error: function () {
                $('#formBriefing_MSG').html('Falha ao tentar enviar briefing.').addClass('alert-danger').fadeIn();
                $('#bt_brief').attr('disabled', false).val('ENVIAR');
            }
        });


        $(".m-ajax").bind("focus", function () {
            $(this).removeClass("alert-danger");
            _class = this.name.replace(/[\[\]]/g, "");
            $("." + _class).remove();

        });
    });

    // FECHA E ABRE FILTRO LISTAGEM

    $('.fechar_filtro').click(function () {
        $('.filtro').fadeOut();
    });
    $('.abre-filtro').click(function () {
        $('.filtro').fadeIn();
    });
    $('.filtrar-subcategoira').click(function () {
        $('.d_menu_listagem').slideToggle();
        $('.img-cores').slideUp();
    });
    $('.filtro-cor-mobile').click(function () {
        $('.img-cores').slideToggle();
        $('.d_menu_listagem').slideUp();
    });


    // FAQ
    var pergun_clicado = 0;
    $('.pergunta').bind('click', function (e) {
        pergunta = $(this).data('id');
        resposta = $('.resposta_' + pergunta).data('id');

        // $('.pergunta_'+pergunta).removeClass('selecionado');

        if (resposta == pergunta && pergun_clicado != pergunta) {
            pergun_clicado = pergunta;
            e.preventDefault();

            // $('.resposta').each(function(){
            //     $(this).slideUp();
            // });

            resposta_a = $('.resposta_' + pergunta).data('id');
            //$('.resposta_'+pergunta).slideToggle();
            $('.resposta_' + pergunta).slideDown();
            $('.icon_angle_' + resposta_a).addClass('fa-angle-up');
            $('.icon_angle_' + resposta_a).removeClass('fa-angle-down');

        } else {
            resposta_b = $('.resposta_' + pergunta).data('id');
            $('.resposta_' + resposta_b).slideUp();
            $('.icon_angle_' + resposta_b).removeClass('fa-angle-up');
            $('.icon_angle_' + resposta_b).addClass('fa-angle-down');
            e.preventDefault();
            pergun_clicado = 0;
        }
    });

});

var debounce;
function smartSearch(elem) {

    clearTimeout(debounce);

    $("#search_result").html('<span style="padding:10px;font-size:.9em;display:inline-block;">Carregando ...</span>').show();

    debounce = setTimeout(function () {
        $.ajax({
            url: path + "ajax.php/productHint/" + elem.value
            , method: "GET"
            , dataType: "json"
            , beforeSend: function () { }
            , success: function (out) {
                $("#search_result").html(out.html);
                if (out.status) $("#search_result").show();
                else $("#search_result").hide();
            }
            , complete: function () { }
        });
    }, 700);
}
function smartSearch2(elem) {
    $.ajax({
        url: path + "ajax.php/productHint/" + elem.value
        , method: "GET"
        , dataType: "json"
        , beforeSend: function () { }
        , success: function (out) {
            $("#search_result2").html(out.html);
            if (out.status) $("#search_result2").show();
            else $("#search_result2").hide();
        }
        , complete: function () { }
    });
}
/*** CLIENTES SATISFEITOS ***/
if (document.getElementById("slideClientes")) {
    var slideClientes = new Swiper('#slideClientes', {
        autoplay: {
            delay: 5000,
            disableOnInteraction: false,
        },
        slidesPerView: 5,
        loop: {
            el: true,
        },

    });
}

//MENU CATEGORIA DESK
//  $('.pais').mouseover(function(){
//     var id_pai = $(this).data('id');
//     $(this).addClass('selectedmenu');
//     $('.menu-categorias-filho').each(function(){
//         //console.log($(this).data('id'));
//         if($(this).data('filho') == id_pai){
//             $(this).show();
//         }else{
//             $(this).hide();
//         }
//     })

//     $('.menu-categorias-filho2').each(function(){
//         //console.log($(this).data('id'));
//         if($(this).data('filho') == id_pai){
//             $(this).show();
//         }else{
//             $(this).hide();
//         }
//     })

//     $('.menu-categorias-imagem').each(function(){
//         if($(this).data('img') == id_pai){
//             $(this).show();
//         }else{
//             $(this).hide();
//         }
//     })
// })
//  $('.pais').mouseout(function(){
//     $(this).removeClass('selectedmenu');
// });

// $('.menu-categorias-filho').mouseover(function(){
//     var pai = $(this).data('filho');
//     $("#"+pai).addClass('selectedmenu');
// });
// $('.menu-categorias-filho2').mouseover(function(){
//     var pai = $(this).data('filho');
//     $("#"+pai).addClass('selectedmenu');
// });

// $('.menu-categorias-filho').mouseout(function(){
//     var pai = $(this).data('filho');
//     $("#"+pai).removeClass('selectedmenu');
// });
// $('.menu-categorias-filho2').mouseout(function(){
//     $(this).addClass('selectedmenu');
// });


$('.menu-categorias-filho2').mouseover(function () {
    $(this).addClass('selectedsubmenu');
});

$('.menu-categorias-filho2').mouseout(function () {
    $(this).removeClass('selectedsubmenu');
});


//*** CADASTRO */
$(document).ready(function () {

    $('#formlogin').ajaxForm({
        dataType: 'json'
        , beforeSend: function () {
            $('#formlogin').attr('disabled', true).css('opacity', .7);
            $('#d-erro-1').hide().html('');
        }
        , success: function (out) {
            if (out.status) {
                window.location.href = new String(out.url_redirect);
            }
            else {
                // set_erro();
                $('#d-erro-1').html(out.msg).slideDown();
                $('#formlogin').attr('disabled', false).css('opacity', 1);
            }
        }
    });
});

// $(document).ready(function(){
//     if(document.getElementById("swiper-marcas")){
//         var swiper = new Swiper('#swiper-marcas', {
//             slidesPerView: 5,
//             spaceBetween: 30,
//             navigation: {
//                 nextEl: '.swiper-button-next',
//                 prevEl: '.swiper-button-prev',
//             },
//             breakpoints:{
//                 991: {
//                     slidesPerView: 2,
//                     spaceBetween: 0
//                 },
//                 510:{
//                     slidesPerView: 2,
//                     spaceBetween: 0
//                 }
//             },
//             centeredSlides: true,
//             loop: true,
//             autoplay: {
//                         delay: 5000,
//                 disableOnInteraction: false,
//             },
//         });
//     }

// });

// function abreBuscaMobile(){
//     $('.d-form-mobile').slideToggle();
// }
// $('.abremenumobile').click(function(){
//     $('.header-menu-mobile').slideToggle();
// });

// function AbreMenuCat(){
//     $('.sub-categoria').slideToggle();
// }

function verificaProd() {
    var win = $(this);
    if (win.width() <= 991) {
        //$('.produto').addClass('mprod');
        $('.mprod').removeClass('produto');
    } else {
        $('.mprod').addClass('produto');
        // $('.produto').removeClass('mprod');
    }
}
$(window).resize(function () {
    verificaProd();
});
$(window).on('load', function () {
    verificaProd();
});
if ($(window).width() <= 991) {


    // removeClassProd();

};


function goBack() {
    window.history.back();
}

// Abre pop do compartilhamento do twitter na pagina de post
$('.window').bind("click", function () {
    href = this.href;
    window.open(href, '', 'width=auto,resizable=yes,scrollbars=yes,status=no,titlebar=no,toolbar=no,height=400');
    return false;
});

if (typeof Swiper === "function") {

    var swiperLan = new Swiper('#swiper-lanc', {
        slidesPerView: 2,
        spaceBetween: 0,
        loop: false,
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },
    });

    var swiperPromo = new Swiper('#swiper-promo', {
        slidesPerView: 2,
        spaceBetween: 0,
        loop: false,
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },
    });

}


function initOwlCarousel() {
    if ($(".owl-carousel").size() > 0) {
        setTimeout(function () {
            $(".owl-carousel").owlCarousel({
                // Most important owl features
                items: 1,
                itemsDesktop: [1201, 4],
                itemsDesktopSmall: [980, 3],
                itemsTablet: [768, 2],
                itemsTabletSmall: false,
                itemsMobile: [479, 1],
                singleItem: true,
                nav: true,
                dots: false,
                navText: ["<i class='fa fa-long-arrow-left'></i>", "<i class='fa fa-long-arrow-right'></i>"],
            });
        }, 500);
    }
}

function destroyOwlCarousel() {
    if (typeof owlCarousel === "function") {
        var owl = $(".owl-carousel");
        owl.owlCarousel();
        owl.data('owlCarousel').destroy();
    }
}

function mascPhone(a, c) {
    //mask={definitions:{9:"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"},autoclear:!0,dataName:"rawMaskFn",placeholder:"_"};
    mask = '#### ####-####';
    var patrn = /^\([1-9]/;
    8 != a.keyCode && 9 != a.keyCode && (("" == c.value || 14 <= c.value.length) && $("#" + c.id).keyup(function () {
        14 == this.value.length && "-" != this.value.charAt(9) && (this.value = this.value.replace("-", ""), this.value = [this.value.slice(0, 9), "-", this.value.slice(9)].join(""));
        15 == this.value.length && "-" != this.value.charAt(10) && (this.value = this.value.replace("-", ""), this.value = [this.value.slice(0, 10), "-", this.value.slice(10)].join(""))
    }),
        "" == c.value ? c.value = "(" : 1 == c.value.length && "(" != c.value[0] ? c.value = "(" + c.value : 3 == c.value.length && (c.value += ")"), c.value.match(patrn) ? $("#" + c.id).attr("maxlength", "15") : $("#" + c.id).attr("maxlength", "14"));
    window.event ? _TXT = a.keyCode : a.which && (_TXT = a.which); if (47 < _TXT && 58 > _TXT) {
        var f = c.value.length, d = mask.substring(0, 1), f = mask.substring(f); f.substring(0, 1) != d && (c.value += f.substring(0, 1)); return !0;
    }
    return 8 != _TXT ? !1 : !0;
}

function formatar(mascara, documento, event, sonum) {
    if (event.keyCode != 8) {
        if (sonum) {
            documento.value = documento.value.replace(/[a-z]/ig, '');
        }
        var i = documento.value.length;
        var saida = mascara.substring(0, 1);
        var texto = mascara.substring(i)
        if (texto.substring(0, 1) != saida) {
            documento.value += texto.substring(0, 1);
        }
    }
}

function numeroFormat(elem) {
    valor = elem.value.replace(/[a-z \.]/ig, '');
    len = valor.length;
    if (len > 2) {
        aux = "";
        for (j = 0, i = len; i >= 0; i--) {
            if (j == 4) {
                aux = '.' + aux;
                j = 2;
            } else j++;
            aux = valor.charAt(i) + aux;
        }
        valor = aux;
    }

    elem.value = valor;
}

$(document).ready(function () {

    if (typeof packery === 'function') {
        $('.grid').packery({
            itemSelector: '.grid-item',
            gutter: 0,
            originLeft: true
        });
    }

    initOwlCarousel();

    // var $doc = $('html, body');
    // $('a').click(function() {
    //     $doc.animate({
    //         scrollTop: $( $.attr(this, 'href') ).offset().top
    //     }, 500);
    //     return false;
    // });

    $(".nav-tabs li a").click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    })

    $('[data-toggle="tooltip"]').tooltip();


    $('.mynav li a').on('click', function (e) {
        e.preventDefault();
        $(this).tab('show');


        $('input[type="number"]').niceNumber({
            autoSize: false
        });

    });




    $('[data-toggle="tooltip"]').tooltip();

});
// primeiro carrega o swiper-promo para depois esconder a div para que funcione
setTimeout(function () {
    $('#_promocao').css('display', 'none');
}, 500
);

function replaceAll(str, de, para) {
    var pos = str.indexOf(de);
    while (pos > -1) {
        str = str.replace(de, para);
        pos = str.indexOf(de);
    }
    return (str);
}

function popup(p_url, p_largura, p_altura, extra) {
    if (!p_largura) p_largura = window.outerWidth;
    if (!p_altura) p_altura = window.outerHeight;

    x = window.open(p_url, 'p' + new Date().getSeconds(), 'width=' + p_largura + ',height=' + p_altura + (extra ? ',' + extra : '') + ',resizable=no,scrollbars=1');
    try { x.focus(); }
    catch (e) {
        alert('por favor, desabilite o bloqueador de pop-ups para visualizar esta janela');
    }
}
function int_val(x) {
    //alert('de'+x);
    x = new String(x);
    x = x.replace(/[a-z]/ig, '');
    //console.log(x);
    //x = new Number(x);
    //alert('para'+x);
    return x;
}

$(document).ready(function () {
    $('.link_').mouseover(function () {
        if ($(window).width() > 991) {
            var link = $(this).data('id');
            $('.sub_' + link).css('display', 'block');

            $('.grid').packery({
                itemSelector: '.grid-item',
                columnWidth: '.grid-sizer',
                percentPosition: true,
                gutter: 0
            });
        };
    })
        .mouseleave(function () {
            if ($(window).width() > 991) {
                $('.sub-menu').css('display', 'none');
            }
        });

    if ($(window).width() <= 991) {
        $('.d1-menu-sub').removeClass('grid');
        $('.d2-menu-sub').removeClass('grid-item');
        $('.menu-s').removeClass('grid-item-content');
    }

});

function buscaCepNovo(obj) {
    if (obj.value != '') {
        cep = obj.value.replace('-', '');
        $.ajax({
            url: 'https://viacep.com.br/ws/' + cep + '/json/?callback=?'
            , method: 'POST'
            , dataType: 'json'
            , success: function (out) {
                $('input[name=\'cadastro[logradouro]\']').val(out.logradouro);
                $('input[name=\'cadastro[bairro]\']').val(out.bairro);
                $('input[name=\'cadastro[cidade]\']').val(out.localidade);
                $('select[name=\'cadastro[uf]\']').val(out.uf);

                $('input[name=\'cadastro[numero]\']').focus();
            }
            , beforeSend: function () {
                $('input[name=\'cadastro[logradouro]\']').val('Aguarde ...');
                $('input[name=\'cadastro[bairro]\']').val('Aguarde ...');
                $('input[name=\'cadastro[cidade]\']').val('Aguarde ...');
                $('select[name=\'cadastro[uf]\']').val('Aguarde ...');
            },
            error: function () {
                alert('Houve um erro ao buscar CEP. Preencha manualmente.');
            }
        });
    }


}

$('input[name=\'cadastro[cep]\']').bind('blur', function () {

    buscaCepNovo(this);
});

// $("#finaliza_desconectado").on("click",function(){
//     $("#identificacao_finaliza").slideToggle();
//     $([document.documentElement, document.body]).animate({
//     scrollTop: $("#identificacao_finaliza").offset().top
//     }, 1000);
// });

$(document).ready(function () {
    $('.hassub').hover(function () {
        $(this).children('._subcat').css('left', $(this).position().left);
    })
    $("#botao-cookie").bind("click", function () {
        $.ajax({
            url: index + "set_cookie",
            success: function (out) {
                $(".cookie-div").fadeOut();
            }
        });
    });

    // $('.hassub').children('._subcat').hover(function(){
    //     $(this).show();
    // })
});