$(document).ready(function () {
    $('body').show();
    input_effect();
    //MENU LATERAL
    $('.menu_lateral_button').click(function () {
        var active = $(this).attr('active');
        $('.menu_lateral').attr('active', active)
    });
    var optionsNewsLetter = {
        form_name: "Newsletter",
        table: "hbrd_cms_newsletters",
        form: 7,
        custom_verify: {
            nome: {
                type: "attention",
                message: "Preencha o campo nome"
            },
            email: {
                type: "attention",
                call: "validaEmail",
                message: "Preencha o campo e-mail com um endereço válido"
            }
        },
        not_required: {
            telefone: 0,checkbox1: 0, checkbox2: 0,
        }
    };
    $form = $("form#newsletters");
    $form.makeclickform(optionsNewsLetter);
    if (pagina == 'home') {

        //BANNER CAROUSEL
        var carousel_topo = $('section.home_banner .carousel');
        carousel_topo.slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            dots: true,
            arrows: false,
            autoplay: true,
            autoplaySpeed: 5000,
            pauseOnHover: false,
            appendDots: 'section.home_banner .dots',
            // fade: true
        });

        $('section.home_banner .arrows button').click(function () {
            var direction = $(this).attr('class');
            carousel_topo.slick(direction);
        });


        //CAROUSEL MODELOS
        var carousel_modelos = $('section.home_modelos .carousel_content .carousel');
        carousel_modelos.slick({
            slidesToShow: 3,
            slidesToScroll: 3,
            dots: true,
            arrows: false,
            appendDots: 'section.home_modelos .carousel_content .dots',
            autoplay: true,
            autoplaySpeed: 4000,
            responsive: [
                {
                    breakpoint: 1151,
                    settings: {
                        slidesToShow: 2,
                        slidesToScroll: 2
                    }
                },
                {
                    breakpoint: 851,
                    settings: {
                        slidesToShow: 1,
                        slidesToScroll: 1
                    }
                }
            ]
        });
        $('section.home_modelos .carousel_content .arrows button').click(function () {
            var direction = $(this).attr('class');
            carousel_modelos.slick(direction);
        });
        //CAROUSEL OFERTAS
        var carousel_ofertas = $('section.home_ofertas .right_content .carousel');
        carousel_ofertas.slick({
            slidesToShow: 3,
            slidesToScroll: 3,
            dots: true,
            arrows: false,
            variableWidth: true,
            appendDots: 'section.home_ofertas .right_content .dots',
            autoplay: true,
            autoplaySpeed: 4000,
            responsive: [
                {
                    breakpoint: 1651,
                    settings: {
                        slidesToShow: 2,
                        slidesToScroll: 2
                    }
                },
                {
                    breakpoint: 1201,
                    settings: {
                        slidesToShow: 1,
                        slidesToScroll: 1
                    }
                }
            ]
        });
        //CAROUSEL BLOG
        var carousel_blog = $('section.home_blog .carousel');
        carousel_blog.slick({
            slidesToShow: 3,
            slidesToScroll: 3,
            dots: false,
            arrows: false,
            infinite: false,
            autoplay: true,
            autoplaySpeed: 4000,
            responsive: [
                {
                    breakpoint: 1221,
                    settings: {
                        variableWidth: true,
                        slidesToShow: 2,
                        slidesToScroll: 2
                    }
                },
                {
                    breakpoint: 701,
                    settings: {
                        variableWidth: true,
                        slidesToShow: 1,
                        slidesToScroll: 1
                    }
                }
            ]
        });
    }
    if (pagina == 'busca') {
        $('section.novos_lista_filtro button.filtrar_busca').click(function () {
            var filtro = $('section.novos_lista_filtro form');
            var status = filtro.attr('active');
            if (status == 'false')
                filtro.attr('active', 'true');
            else
                filtro.attr('active', 'false');
        });
    }
    if (pagina == 'veiculo') {
        //CAROUSEL GALERIA
        var galeria = $('section.novo_interna_info .content .left .carousel_content .carousel');
        galeria.slick({
            slidesToShow: 1,
            slidesToScroll: 1,
            dots: true,
            arrows: false,
            variableWidth: false,
            autoplay: true,
            infinite: false,
            autoplaySpeed: 3000,
            pauseOnHover: false,
            appendDots: 'section.novo_interna_info .content .left .carousel_content .dots'
        });
        new photoswipe_init('.galeria_swipe');
        //OPEN FORM
        var button_form = $('section.novo_interna_info .content .right button.open_form');
        button_form.click(function () {
            $('section.novo_interna_info .content .right').attr('active', 'true');
        });
        var close_form = $('section.novo_interna_info .content .right .form_content button.fechar');
        close_form.click(function () {
            $('section.novo_interna_info .content .right').attr('active', 'false');
        });
        //OFERTA CAROUSEL
        var oferta_carousel = $('section.novo_interna_ofertas .carousel');
        oferta_carousel.slick({
            slidesToShow: 3,
            slidesToScroll: 3,
            dots: false,
            arrows: false,
            autoplay: true,
            autoplaySpeed: 5000,
            responsive: [
                {
                    breakpoint: 1301,
                    settings: {
                        slidesToShow: 2,
                        slidesToScroll: 2,
                        variableWidth: true
                    }
                },
                {
                    breakpoint: 701,
                    settings: {
                        slidesToShow: 1,
                        slidesToScroll: 1,
                        variableWidth: true
                    }
                }
            ]
        });
        var options = {
            form_name: "Cadastro Hotsite - " + hotsite_name,
            table: "hbrd_desk_veiculos_cadastros",
            form: hotsite_form_cadastro,
            custom_verify: {
                nome: {
                    type: "attention",
                    message: "Preencha o campo nome"
                },
                email: {
                    type: "attention",
                    call: "validaEmail",
                    message: "Preencha o campo e-mail com um endereço válido"
                },
                telefone: {
                    type: "attention",
                    message: "Preencha o campo telefone"
                }
            },
            not_required: {
                checkbox1: 0, checkbox2: 0,
            }
        };
        $form = $("form[name=form_default]");
        $form.makeclickform(options);
        // recaptcha
        $('.novo_interna_info form').on('submit', (e) => {
            e.preventDefault();
            $('.novo_interna_info .clickformsubmit').trigger('click');
        })
        if (!navigator.share) $('.share').hide();
    }
    if (pagina == 'empresa') {
        new photoswipe_init('.foto_galeria');
    }
    if (pagina == 'compramos') {
        function readURL(input, id) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $img = $('<img/>').attr('src', e.target.result);
                    $('label[for="' + id + '"]').css({ 'background-image': 'url(' + e.target.result + ')' });
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
        $('section.form_content form .fotos .item_foto input').on("change", function () {
            var id = $(this).attr('id');
            readURL(this, id);
        });
        $('[name=marca]').on('change', function () {
            $.get(scripts_path + 'get-modelos.php?id=' + $(this).val())
                .then(data => { console.log(data) });
        })
        var options = {
            form_name: "Compramos seu veiculo",
            table: "hbrd_desk_compramos",
            form: 4,
            custom_verify: {
                nome: {
                    type: "attention",
                    message: "Preencha o campo nome"
                },
                email: {
                    call: "validaEmail",
                    message: "Preencha este campo com um E-mail válido"
                },
                telefone: {
                    type: "attention",
                    message: "Preencha o campo telefone"
                },
            },
            not_required: {
                checkbox1: 0, checkbox2: 0,
            }
        };
        $form = $("form[name=form_default]");
        $form.makeclickform(options);
        $('#carousel_depoimento').slick({
            infinite: true,
            slidesToShow: 1,
            slidesToScroll: 1,
            dots: true,
            appendDots: $('#dots_depoimento'),
            arrows: true,
            prevArrow: $('#arrows_depoimento button.prev'),
            nextArrow: $('#arrows_depoimento button.next'),
            autoplay: true,
            autoplaySpeed: 5000,
        });
    }
    if (pagina == 'trabalhe-conosco') {
        $('#curriculo').change(function (e) {
            var name = e.target.files[0].name;
            $('label[for="curriculo"] div').text(name);
        });
        var options = {
            form_name: "Trabalhe Conosco",
            table: "hbrd_desk_trabalhe_conosco",
            form: 3,
            custom_verify: {
                nome: {
                    type: "attention",
                    message: "Preencha o campo nome"
                },
                email: {
                    call: "validaEmail",
                    message: "Preencha este campo com um E-mail válido"
                },
                celular: {
                    type: "attention",
                    message: "Selecione o celular"
                },
                curriculo: {
                    type: "attention",
                    message: "Anexe a currículo",
                    upload: ["doc", "pdf", "docx"]
                },
                area_interesse: {
                    type: "attention",
                    message: "Selecione o campo area_interesse"
                },
            },
            not_required: {
                telefone: 0, mensagem: 0,checkbox1: 0, checkbox2: 0,
            }
        };
        $form = $("form[name=form_default]");
        $form.makeclickform(options);
    }
    if (pagina == 'fale-conosco') {
        var options = {
            form_name: "Fale Conosco",
            table: "hbrd_desk_contatos",
            form: 2,
            custom_verify: {
                nome: {
                    type: "attention",
                    message: "Preencha o campo nome"
                },
                email: {
                    call: "validaEmail",
                    message: "Preencha este campo com um E-mail válido"
                },
                assunto: {
                    type: "attention",
                    message: "Selecione o assunto"
                },
                mensagem: {
                    type: "attention",
                    message: "Preencha o campo mensagem"
                },
                telefone: {
                    type: "attention",
                    message: "Preencha o campo telefone"
                },
            },
            not_required: {
                teste: 0,checkbox1: 0, checkbox2: 0,
            }
        };
        $form = $("form[name=form_default]");
        $form.makeclickform(options);
    }
    if (pagina == 'financiamento') {
        var options = {
            form_name: "Financiamento",
            table: "hbrd_desk_financiamento",
            form: 5,
            custom_verify: {
                nome: { type: "attention", message: "Preencha o campo nome" },
                // dt_nascimento: { type: "attention", message: "Preencha o campo data de nascimento" },
                // rg: { type: "attention", message: "Preencha o campo RG" },
                // cpf: { type: "attention", message: "Preencha o campo CPF" },
                // nome_mae: { type: "attention", message: "Preencha o campo nome da mãe" },
                // endereco: { type: "attention", message: "Preencha o campo endereço" },
                cidade: { type: "attention", message: "Preencha o campo cidade" },
                celular: { type: "attention", message: "Preencha o campo celular" },
                // trab_empresa: { type: "attention", message: "Preencha o campo nome da empresa" },
                // trab_cargo: { type: "attention", message: "Preencha o campo cargo" },
                // trab_renda: { type: "attention", message: "Preencha o campo renda" },
                // trab_tempo: { type: "attention", message: "Preencha o campo tempo de empresa" },
                // trab_endereco: { type: "attention", message: "Preencha o campo endereço da empresa" },
                // trab_telefone: { type: "attention", message: "Preencha o campo telefone da empresa" },
            },
            not_required: {
                mensagem: 0, telefone: 0,checkbox1: 0, checkbox2: 0,
            }
        };
        $form = $("form[name=form_default]");
        $form.makeclickform(options);
    }
    if (pagina == 'noticias') {
        $("#form-busca").submit(function (e) {
            e.preventDefault();
            var filtros = $.param($(this).serializeArray().filter((x) => x.value));
            location.replace(`${urlNoticias}?${filtros}`);
        });
        $('form select').on('change', () => {
            $("#form-busca").trigger('submit');
        })
        new photoswipe_init('.foto_galeria');
    }
    if (pagina == 'home' || pagina == 'busca') {
        $("#form-busca").submit(function (e) {
            e.preventDefault();
            var filtros = $.param($(this).serializeArray().filter((x) => x.value));
            location.replace(`${urlbusca}?${filtros}`);
        });
        $('#form-busca [name=marca]').on('change', function () {
            $.get(scripts_path + 'get-modelos.php?marca=' + $(this).val())
                .then(data => {
                    let strOpt = '<option selected hidden value="">Modelo</option>';
                    data.forEach(x => {
                        strOpt += `<option value="${x.modelo_descricao}">${x.modelo_descricao}</option>`;
                    })
                    $('form [name=modelo]').html(strOpt);
                });
        })
    }
    if (pagina == 'financiamento') {
        // $("#form-busca").submit(function (e) {
        //     e.preventDefault();
        //     var filtros = $.param($(this).serializeArray().filter((x) => x.value));
        //     location.replace(`${urlbusca}?${filtros}`);
        // });
        $('[name=marca]').on('change', function () {
            $.get(scripts_path + 'get-modelos.php?marca=' + $(this).val())
                .then(data => {
                    let strOpt = '<option selected hidden value="">Modelo</option>';
                    data.forEach(x => {
                        strOpt += `<option value="${x.modelo_descricao}">${x.modelo_descricao}</option>`;
                    })
                    $('form [name=modelo]').html(strOpt);
                });
        })
    }
    function input_effect() {
        $('div.input_content input, div.input_content select').focusin(function () {
            $(this).parent().attr('data-status', 'foco');
        });
        $('div.input_content input, div.input_content select').focusout(function () {
            if ($(this).val() == '') {
                $(this).parent().attr('data-status', 'vazio');
            }
            else {
                $(this).parent().attr('data-status', 'cheio');
            }
        });
        var itens = $('div.input_content input');
        itens.each(function () {
            if ($(this).val() == '') {
                $(this).parent().attr('data-status', 'vazio');
            }
            else {
                $(this).parent().attr('data-status', 'cheio');
            }
        });
        itens = $('div.input_content select');
        itens.each(function () {
            if ($(this).val() == '') {
                $(this).parent().attr('data-status', 'vazio');
            }
            else {
                $(this).parent().attr('data-status', 'cheio');
            }
        });
    }
    //MASCARAS
    var celular = function (val) {
        return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
    },
        spOptions = {
            onKeyPress: function (val, e, field, options) {
                field.mask(celular.apply({}, arguments), options);
            }
        };
    $('[mask="telefone"]').mask(celular, spOptions);
    $('[mask="preco"]').mask("###.##0,00", { reverse: true });
    $('[mask="number"]').mask("##############################");
    $('[mask="data"]').mask("00/00/0000", { placeholder: "__/__/____" });
    $('[mask="cpf"]').mask('000.000.000-00');

    if (!localStorage.getItem("politica")) {
        setTimeout(() => $('section.politica_modal').attr('active', 'true'), 2000);
    }

});
function verifyCallback() {
    $("button[disabled]").prop("disabled", false);
}
function onloadCallback() {
    grecaptcha.render('recaptcha', {
        'sitekey': recaptchakey,
        'callback': verifyCallback
    });
}
function shared(url) {
    if (navigator.share) {
        navigator.share({ url: url });
    }
}

function aceitartermos() {
    localStorage.setItem("politica", 1);
    $('section.politica_modal').attr('active', 'false');
}