$(document).ready(function() {

    let base = $('base').attr('href');

    $('.whatsapp-form .action .close').click(function(e) {
        e.preventDefault();
        $('.whatsapp-form .action hgroup').hide();

        $('.whatsapp-form .action .btn-floating').hover(function() {
            $('.whatsapp-form .action hgroup').slideDown();
        }, function() {
            $('.whatsapp-form .action hgroup').slideUp();
        });
    });

    $('.whatsapp-form .action .btn-floating').click(function(e) {
        e.preventDefault();
        $('.whatsapp-form .form').slideDown();
        $('.whatsapp-form .action').slideUp();
    });

    $('.whatsapp-form .form .close').click(function(e) {
        e.preventDefault();
        $('.whatsapp-form .action').slideDown();
        $('.whatsapp-form .form').slideUp();
    });

    lightGallery(document.getElementById('gallery'), {
        plugins: [lgZoom, lgThumbnail],
        speed: 500,
        licenseKey: '0000-0000-000-0000'
    });

    // Mascaras

    var SPMaskBehavior = function(val) {
            return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
        },
        spOptions = {
            onKeyPress: function(val, e, field, options) {
                field.mask(SPMaskBehavior.apply({}, arguments), options);
            }
        };
    $('.phone').mask(SPMaskBehavior, spOptions);
    $('.mask').mask('# ##0.00', { reverse: true });

    var SPMaskBehavior = function(val) {
        return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
    },
    spOptions = {
        onKeyPress: function(val, e, field, options) {
            field.mask(SPMaskBehavior.apply({}, arguments), options);
        }
    };

    $('#Telefone').mask(SPMaskBehavior, spOptions);

    $('.number .minus').click(function(e) {
        e.preventDefault();
        let actual = $(this).parent().siblings().val();
        let min = parseInt($(this).parent().siblings().attr('min'));
        if (actual > min) {
            actual--;
            $(this).parent().siblings().val(actual);
        }
    });

    $('input[name="check"]').change(function(e) {
        e.preventDefault();
        let value = '';
        $('input[name="check"]:checked').each(function(index, element) {
            value += `${element.value} `;
        });
        $(this).parent().parent().siblings('input').val(value);
    });

    $('.number .plus').click(function(e) {
        e.preventDefault();
        let actual = $(this).parent().siblings().val();
        let max = parseInt($(this).parent().siblings().attr('max'));
        if (actual < max) {
            actual++;
            $(this).parent().siblings().val(actual);
        }
    });

    $('.next').click(function(e) {
        e.preventDefault();
        let count = $('.headline .steps');
        let actual = ($('label.active').attr('id') == undefined) ? $('label.active').attr('id') : $('label.active').attr('id').split('-');
        if (actual == undefined) {
            $('.foot').addClass('active');
            $('#step-1').slideUp();
            $('#step-2').slideDown();
            $('#step-2').addClass('active');
        } else if (actual != undefined && parseInt(actual[1]) < count.length) {
            $('.foot').addClass('active');
            $('.foot .prev').show();
            $(`#step-${actual[1]}`).slideUp();
            $(`#step-${actual[1]}`).removeClass('active');
            $(`#step-${parseInt(actual[1]) + 1}`).slideDown();
            $(`#step-${parseInt(actual[1]) + 1}`).addClass('active');
        } else {
            $('.headline .steps').slideDown();
            $('.headline .steps').addClass('active');
            $('.headline .foot hgroup').slideUp();
            $('.headline .btn').slideDown();
        }
    });

    $('.prev').click(function(e) {
        e.preventDefault();
        let actual = $('label.active').attr('id').split('-');
        if (parseInt(actual[1]) - 1 > 1) {
            $(`#step-${actual[1]}`).slideUp();
            $(`#step-${actual[1]}`).removeClass('active');
            $(`#step-${parseInt(actual[1]) - 1}`).slideDown();
            $(`#step-${parseInt(actual[1]) - 1}`).addClass('active');
        } else {
            $('.foot .prev').hide();
            $('.foot').removeClass('active');
            $(`#step-${actual[1]}`).slideUp();
            $(`#step-${actual[1]}`).removeClass('active');
            $(`#step-${parseInt(actual[1]) - 1}`).slideDown();
            $(`#step-${parseInt(actual[1]) - 1}`).addClass('active');
        }
    });

    // Instagram

    if ($('#userInsta').is(':visible')) {
        $.instagramFeed({
            'username': $('#userInsta').text(),
            'container': "#instagram",
            'display_profile': false,
            'display_biography': false,
            'display_gallery': true,
            'display_igtv': false,
            'get_raw_json': true,
            'styling': true,
            'items': 6,
            'items_per_row': 6,
            'margin': 1,
            'host': 'https://images' + ~~(Math.random() * 3333) + '-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=https://www.instagram.com/',
            'max_tries': 8,
            'cache_time': 360
        });

        function toDataURL(url, callback) {
            var xhr = new XMLHttpRequest();
            xhr.onload = function() {
                var reader = new FileReader();
                reader.onloadend = function() {
                    callback(reader.result);
                }
                reader.readAsDataURL(xhr.response);
            };
            xhr.open('GET', url);
            xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
            xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
            xhr.setRequestHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
            xhr.responseType = 'blob';
            xhr.send();
        }

        setTimeout(() => {
            $('.instagram_gallery a').each(function(index, element) {
                let image = $(this).find('img').attr('src');
                toDataURL(image, function(dataUrl) {
                    console.log('RESULT:', dataUrl)
                })
                $.ajax({
                    type: "POST",
                    url: `${base}helper/instagram`,
                    data: {
                        url: image
                    },
                    success: function(response) {
                        $(element).find('img').attr('src', response);
                        $(element).find('img').css('display', 'block');
                    }
                });
            });
        }, 5000);
    }

    let owl = $('.services .owl-carousel').owlCarousel({
        items: 1,
        loop: false,
        margin: 10,
        nav: true,
        navText: ["Anterior", "Próximo"],
        onInitialized: function() {
            $(".double button") // seleciona os botões
                .click(function() {
                    var idx = $(this).parent().children().index(this); // pega o índice do botão clicado
                    owl.trigger((idx == 1 ? 'next' : 'prev') + '.owl.carousel'); // atribui o evento ao devido botão
                });
        }
    });

    $('.depoimentos .owl-carousel').owlCarousel({
        items: 1,
        loop: false,
        margin: 10,
        nav: true,
        navText: ["<span class='fa fa-long-arrow-alt-left'></span>", "<span class='fa fa-long-arrow-alt-right'></span>"]
    });

    $('.collapsible li').click(function(e) {
        e.preventDefault();
        let id = $(this).parent().attr('id');
        if (id == 'double-1') {
            $('#double-2 .active .collapsible-body').slideUp();
            $('#double-2 li').removeClass('active');
            $('#double-2 .collapsible-header').removeClass('active');
        } else if (id == 'double-2') {
            $('#double-1 .active .collapsible-body').slideUp();
            $('#double-1 li').removeClass('active');
            $('#double-1 .collapsible-header').removeClass('active');
        }
    });

    let time;
    let lado = 150;
    let tempo = setInterval(function() {
        time = $('.time h3').html();
        time = time - 1;
        $('.time h3').html(`${time}`);

        lado = lado - 10;
        $('.thanks aside').css('transform', `translateX(${lado}%)`);
    }, 1000);

    setTimeout(function(argument) {
        clearInterval(tempo);
        $('.thanks aside').css('transform', `translateX(0%)`);
    }, 10000);


    // Efeito de Collapsible

    var active = $('.collapsible .collapsible-header.active');
    $(active).find('.svg').html(`<svg class="svg-inline--fa fa-minus-square fa-w-14" aria-hidden="true" 
    data-prefix="fa" data-icon="minus-square" role="img" xmlns="http://www.w3.org/2000/svg" 
    viewBox="0 0 448 512" data-fa-i2svg=""><path fill="currentColor" d="M400 32H48C21.5 32 0 53.5 0 
    80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zM92 
    296c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h264c6.6 0 12 5.4 12 12v56c0 6.6-5.4 12-12 12H92z">
    </path></svg>`);

    $('.collapsible .collapsible-header').click(function(event) {

        setTimeout(function() {
            $(active).find('.svg').html(`<svg class="svg-inline--fa fa-plus-square fa-w-14" aria-hidden="true" 
            data-prefix="fa" data-icon="plus-square" role="img" xmlns="http://www.w3.org/2000/svg" 
            viewBox="0 0 448 512" data-fa-i2svg=""><path fill="currentColor" d="M400 32H48C21.5 32 0 
            53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zm-32 252c0 
            6.6-5.4 12-12 12h-92v92c0 6.6-5.4 12-12 12h-56c-6.6 0-12-5.4-12-12v-92H92c-6.6 
            0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h92v-92c0-6.6 5.4-12 12-12h56c6.6 0 12 5.4 12 
            12v92h92c6.6 0 12 5.4 12 12v56z"></path></svg>`);

            $('.collapsible .collapsible-header.active .svg').html(`<svg class="svg-inline--fa fa-minus-square fa-w-14" 
            aria-hidden="true" data-prefix="fa" data-icon="minus-square" role="img" 
            xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" data-fa-i2svg="">
            <path fill="currentColor" d="M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 
            0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zM92 296c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 
            12-12h264c6.6 0 12 5.4 12 12v56c0 6.6-5.4 12-12 12H92z"></path></svg>`);

            active = $('.collapsible .collapsible-header.active');
        }, 200);
    });
});