//Objeto padrao chambarelli
var app = {
    init: function() {
        app.loadSticky();
        app.anchor();
        app.slideToDiv();
        window.onscroll = function() {app.loadSticky();}; 
        app.loadToUp();
        app.adjustsForm();
        app.galeria('.carrossel', {"small":1,"medium":2,"large":3}, false, true, true, true, true, false, false, false, false, '',false, false);

        window.resize = function() {app.menuMarcaAtivo();};
    },
    adjustsForm: function(){
        jQuery('.navbar-toggler').on('click',function(){
            jQuery(this).toggleClass('collapsed');
            jQuery('#navbarCollapse').toggleClass('in');
            jQuery('section.header').toggleClass('open');
        });
        if(jQuery('.has-sub .item')) {
            jQuery(".has-sub .item").on("click", function (e) {
                e.preventDefault();
                if(!jQuery(this).closest('.has-sub').hasClass('open')){
                    jQuery(".has-sub.open").find("ul").slideToggle();
                    jQuery(".has-sub").removeClass('open');
                }
                jQuery(this).closest('.has-sub').toggleClass('open');
                //jQuery(".has-sub ul").not($(this).next("ul")).slideUp();
                jQuery(this).next("ul").slideToggle();
            });
        }
        if(jQuery('form')) {
            jQuery('form').attr("autocomplete","off");
        }
        jQuery('form').submit(function( e ) {
            var values = this.elements;
            if(values['curriculo']){
                if(jQuery(values['curriculo']).val()===''){
                    jQuery(this).find('.obrig-curriculo').removeClass('d-none');
                }else{
                    jQuery(this).find('.obrig-curriculo').addClass('d-none');
                }
            }
        });
        if(jQuery('form.wpcf7')) {
            jQuery('#file').change(function () {
                var filename = $('#file').val();
                var urlsplit = filename.split("\\");
                var lastpart = urlsplit[urlsplit.length - 1];
                $('label[for="file"]').html(lastpart);
                jQuery('.obrig-curriculo').addClass('d-none');
            });
        }
        jQuery('.box-publicacoes .posts-home .item-post').on('mouseenter',function(){
            var id = jQuery(this).data('nome');
            jQuery('.box-publicacoes .image-posts .div-img,.box-publicacoes .posts-home .item-post').removeClass('open');
            jQuery(this).addClass('open');
            jQuery('.box-publicacoes .image-posts .div-img[data-nome="'+id+'"]').addClass('open');
        });
        if(jQuery('.box-expertise').length){
            jQuery('[data-toggle="collapse"]').on('click', function () {
                const target = jQuery(this).data('target');
                jQuery('.collapse').not(target).collapse('hide');
            });
        }
    },
    loadSticky: function () {
        var height = jQuery(window).scrollTop(),
            heightW = jQuery(window).height(),
            width = jQuery(window).width(),
            navbar = jQuery("section.header")
        if( height > 1 ){
            navbar.addClass("sticky");
        }else{
            navbar.removeClass("sticky");
        }
        if(height > 200 ){
            jQuery('.to-top').addClass('show');
        }else{
            jQuery('.to-top').removeClass('show');
        }
        jQuery('.header-languages a').one('click',function(){
            jQuery(this).addClass('baixo');
        });
    },
    anchor : function(link){
        var desconto = 0,
            width = jQuery(window).width();
        if(link!=undefined) {
            var link = link.replace("#", "");
        }
        var linkT = link;
        desconto += jQuery('section.header').height();
        if(jQuery('body').hasClass('admin-bar')){
            desconto += jQuery('#wpadminbar').height();
        }
        console.log(link);
        if(link) {
            var scroll = (jQuery("." + link).offset().top)+1;
            console.log(link+'-'+scroll);
            jQuery('html, body').animate({
                scrollTop: (scroll - desconto)
            }, 100);
            history.pushState(
                '', '',
                window.location.origin + window.location.pathname + "#" + linkT
            );
        };
        return false;
    },
    slideToDiv : function(){
        var hash = window.location.hash;
        var link = hash.replace("#", "");
        if((hash.length && jQuery('.'+link).length)){
            setTimeout(function(){
                app.anchor(hash);
            }, 1000);
        };
        jQuery('.click-anchor').click( function(e) {
            e.preventDefault();
            var link = jQuery(this).attr('href'),
                pathlink = jQuery(this)[0].pathname,
                hash = jQuery(this)[0].hash,
                endereco = window.location.pathname;
            if(pathlink==endereco){
                if(hash) {
                    app.anchor(hash);
                }else{
                    window.location.href = link;
                }
            }else{
                window.location.href = link;
            }
        });
        jQuery('#menu-menu-footer a,.div-out-menu a:not([href="#"])').click( function(e) {
            e.preventDefault();
            var link = jQuery(this).attr('href'),
                pathlink = jQuery(this)[0].pathname,
                hash = jQuery(this)[0].hash,
                endereco = window.location.pathname,
                s = getUrlParameter('s');
            if(pathlink==endereco && s===false){
                if(hash) {
                    app.anchor(hash);
                    jQuery('.navbar-toggler').click();
                }else{
                    window.location.href = link;
                }
            }else{
                window.location.href = link;
            }
        });
        //jQuery('.link-contato').removeClass('active');
        var desconto = jQuery('section.header').height(),
            width = jQuery(window).width();
        if(jQuery('body').hasClass('admin-bar')){
            desconto += jQuery('#wpadminbar').height();
        }
    },
    loadToUp : function(){
        jQuery('.to-top').click( function(e) {
            e.preventDefault();
            document.body.scrollIntoView({behavior: 'smooth', block: 'start'});
            return false;
        });
    },
    galeria:function(elemento, qtd, nav, dots, loop, autoplay, hoverPause, animateIn, animateOut, dotNumero, animaItem, animation, dotThumb, drag, contaSlide = false, adjustReload = false){
        if(jQuery(elemento).html() != undefined) {
            var $owl = jQuery(elemento),
                effect = animation,
                outIndex,
                isDragged = true;

            $owl.addClass(animation);

            $owl.owlCarousel({
                loop: loop,
                autoplay: autoplay,
                animateOut: animateOut,
                animateIn: animateIn,
                nav: nav,
                dots: dots,
                autoplayHoverPause: hoverPause,
                responsive: {
                    0: {
                        items: qtd.small
                    },
                    600: {
                        items: qtd.medium
                    },
                    1000: {
                        items: qtd.large
                    }
                }
            });
            if(nav==true){
                $(elemento+" .owl-nav").ready(function () {
                    $(elemento+" .owl-nav button").each(function(){
                        jQuery(this).attr('aria-label','Nav');
                    });
                });
                jQuery(elemento).find('.owl-nav button').attr('aria-label','Nav');
            }
            if(dots==true){
                $(elemento+" .owl-dots").ready(function () {
                    $(elemento+" .owl-dots .owl-dot").each(function(){
                        jQuery(this).attr('aria-label','Dot');
                    });
                });
            }

            $owl.on('change.owl.carousel', function (event) {
                outIndex = event.item.index;
                if(autoplay==false) {
                    $(elemento).trigger('stop.owl.autoplay');
                }
            });
            $owl.on('changed.owl.carousel', function (event) {
                var inIndex = event.item.index,
                    dir = outIndex <= inIndex ? 'Next' : 'Prev';

                var animation = {
                    moveIn: {
                        item: $('.owl-item', $owl).eq(inIndex),
                        effect: effect + 'In' + dir
                    },
                    moveOut: {
                        item: $('.owl-item', $owl).eq(outIndex),
                        effect: effect + 'Out' + dir
                    },
                    run: function (type) {
                        var animationEndEvent = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend',
                            animationObj = this[type],
                            inOut = type == 'moveIn' ? 'in' : 'out',
                            animationClass = 'animated owl-animated-' + inOut + ' ' + animationObj.effect,
                            $nav = $owl.find('.owl-prev, .owl-next, .owl-dot, .owl-stage');


                        animationObj.item.stop().addClass(animationClass).one(animationEndEvent, function () {
                            // remove class at the end of the animations
                            animationObj.item.removeClass(animationClass);
                            $nav.css('pointerEvents', 'auto');
                        });
                    }
                };
                if (!isDragged) {
                    animation.run('moveOut');
                    animation.run('moveIn');
                }
                if(contaSlide===true){
                    var ind = jQuery(this).attr('index-carr');
                    var num  = parseInt($('.owl-item', this).eq(inIndex).find('.item-num').attr('num'));
                    var numeroFormatado = num < 10 ? '0' + num : num;
                    jQuery(elemento+'-num-slide[index-carr="'+ind+'"] .current').html(numeroFormatado);
                }
            });
            $owl.on('drag.owl.carousel', function (event) {
                isDragged = true;
            });

            $owl.on('dragged.owl.carousel', function (event) {
                isDragged = false;
            });

            if (jQuery(window).width() >= 991) {
                $owl.trigger('stop.owl.autoplay');
            }
            /**
             * Get Animation Name from the class 'owl-carousel',
             * animation name begins with fx...
             */
            function getAnimationName() {
                var re = /fx[a-zA-Z0-9\-_]+/i,
                    matches = re.exec($owl.attr('class'));

                return matches !== null ? matches[0] : matches;
            }

            if(dotThumb==true) {
                $owl.on('change.owl.carousel', function (event) {

                    var current = event.item.index+1;
                    var src = $(event.target).find(".owl-item").eq(current).find('.item').attr('number');
                    jQuery(elemento+"-count-slide .number").html(src);
                    //console.log(src);
                });
            }
            if (animaItem == true) {
                carrossel.on('changed.owl.carousel', function (event) {
                    console.log('Animação');
                })
            };
            if (dotNumero == true) {
                var i = 1,
                    num = "";
                jQuery(elemento + " .owl-dots .owl-dot").each(function () {
                    num = "";
                    if ((i < 10)) {
                        num = "0";
                    }
                    jQuery(this).html(num + i);
                    i++;
                });
            };
            if (adjustReload == true) {
                jQuery(elemento).trigger('refresh.owl.carousel');
            }
        }
    },
    setCookie:function(name,value,days) {
        console.log('setcookie');
        var expires = "";
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days*24*60*60*1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + (value || "")  + expires + "; path=/";
    },
    getCookie :function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    },
    eraseCookie: function (name) {
        document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    },
};
function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
        }
    }
    return false;
}
jQuery("document").ready(function ($) {
    app.init();
    $('.phone-mask').mask('(00) 0000-00009');
    $('.phone-mask').blur(function(event) {
        if($(this).val().length == 15){ // Celular com 9 dígitos + 2 dígitos DDD e 4 da máscara
            $(this).mask('(00) 00000-0009');
        } else {
            $(this).mask('(00) 0000-00009');
        }
    });
    ScrollReveal().reveal('.rev-mostra,.anima-content p,.anima-content li,.anima-content h1,.anima-content h2,.anima-content h3,.anima-content h4,.anima-content h5,.anima-content h6', {
        //reset: true,
        viewFactor: 0.5,
        duration: 800,
        distance: '50px',
        origin: 'bottom',
        easing: 'ease-in-out'
    });
});