(function($) {

	"use strict";


    /*------------------------------------------
        = ALL ESSENTIAL FUNCTIONS
    -------------------------------------------*/

    // Toggle mobile navigation
    function toggleMobileNavigation() {
        var navbar = $(".navigation-holder");
        var openBtn = $(".navbar-header .open-btn");
        var closeBtn = $(".navigation-holder .close-navbar");
        var body = $(".page-wrapper");

        openBtn.on("click", function() {
            if (!navbar.hasClass("slideInn")) {
                navbar.addClass("slideInn");
                body.addClass("body-overlay");
            }
            return false;
        })

        closeBtn.on("click", function() {
            if (navbar.hasClass("slideInn")) {
                navbar.removeClass("slideInn");
            }
            body.removeClass("body-overlay");
            return false;
        })
    }

    toggleMobileNavigation();


    // Function for toggle class for small menu
    function toggleClassForSmallNav() {
        var windowWidth = window.innerWidth;
        var mainNav = $("#navbar > ul");

        if (windowWidth <= 991) {
            mainNav.addClass("small-nav");
        } else {
            mainNav.removeClass("small-nav");
        }
    }

    toggleClassForSmallNav();


    // Function for small menu
    function smallNavFunctionality() {
        var windowWidth = window.innerWidth;
        var mainNav = $(".navigation-holder");
        var smallNav = $(".navigation-holder > .small-nav");
        var subMenu = smallNav.find(".sub-menu");
        var megamenu = smallNav.find(".mega-menu");
        var menuItemWidthSubMenu = smallNav.find(".menu-item-has-children > a");

        if (windowWidth <= 991) {
            subMenu.hide();
            megamenu.hide();
            menuItemWidthSubMenu.on("click", function(e) {
                var $this = $(this);
                $this.siblings().slideToggle();
                 e.preventDefault();
                e.stopImmediatePropagation();
            })
        } else if (windowWidth > 991) {
            mainNav.find(".sub-menu").show();
            mainNav.find(".mega-menu").show();
        }
    }

    function initKefuWidget() {
        if (typeof Kefu !== "function" || !document.body || document.querySelector(".kefubox")) {
            return;
        }

        new Kefu({
            tel: "0535－2106025",
            qq: "278294683",
            wechatPerson: {
                state: false,
                imgURL: "./imgs/2wm.png"
            },
            wechatofficial: {
                state: true,
                imgURL: "assets/images/wechat.webp"
            }
        });
    }

    smallNavFunctionality();
    initKefuWidget();


    // Parallax background
    function bgParallax() {
        if ($(".parallax").length) {
            $(".parallax").each(function() {
                var height = $(this).position().top;
                var resize     = height - $(window).scrollTop();
                var doParallax = -(resize/5);
                var positionValue   = doParallax + "px";
                var img = $(this).data("bg-image");

                $(this).css({
                    backgroundImage: "url(" + img + ")",
                    backgroundPosition: "50%" + positionValue,
                    backgroundSize: "cover"
                });
            });
        }
    }

    function getSlideBackgroundUrls() {
        var backgroundUrls = [];

        $(".hero-slider .slide-bg-image[data-background]").each(function() {
            var backgroundUrl = $(this).data("background");

            if (backgroundUrl && $.inArray(backgroundUrl, backgroundUrls) === -1) {
                backgroundUrls.push(backgroundUrl);
            }
        });

        return backgroundUrls;
    }

    function waitForHeroBackgrounds(onComplete) {
        var backgroundUrls = getSlideBackgroundUrls();
        var remaining = backgroundUrls.length;
        var hasCompleted = false;

        function finish() {
            if (hasCompleted) {
                return;
            }

            hasCompleted = true;
            onComplete();
        }

        if (!remaining) {
            finish();
            return;
        }

        // Allow enough time for large hero backgrounds on slower networks
        // before falling back to the default loading timeout.
        var fallbackTimer = setTimeout(finish, 8000);

        $.each(backgroundUrls, function(index, backgroundUrl) {
            var image = new Image();
            var resolved = false;

            function markResolved() {
                if (resolved) {
                    return;
                }

                resolved = true;
                remaining -= 1;

                if (!remaining) {
                    clearTimeout(fallbackTimer);
                    finish();
                }
            }

            image.onload = markResolved;
            image.onerror = markResolved;
            image.src = backgroundUrl;

            if (image.complete) {
                markResolved();
            }
        });
    }

    function getHeroInterleaveOffset() {
        var windowWidth = window.innerWidth;

        if (windowWidth <= 480) {
            return 0;
        }

        if (windowWidth <= 767) {
            return 0.05;
        }

        if (windowWidth <= 991) {
            return 0.08;
        }

        return 0.12;
    }

    // DATA BACKGROUND IMAGE
    var sliderBgSetting = $(".slide-bg-image");
    sliderBgSetting.each(function(indx){
        var backgroundUrl = $(this).attr("data-background");
        var $slide = $(this).closest(".swiper-slide");

        if (backgroundUrl){
            $(this).css("background-image", "url(" + backgroundUrl + ")");

            if ($slide.length) {
                $slide.css({
                    "background-image": "url(" + backgroundUrl + ")",
                    "background-position": "center center",
                    "background-repeat": "no-repeat",
                    "background-size": "cover"
                });
            }
        }
    });


    // HERO SLIDER
    var heroSwiper = null;
    var heroSlideCount = 0;
    var heroAutoplayOptions = {
        delay: 6500,
        disableOnInteraction: false,
        stopOnLastSlide: false
    };

    function applyHeroInterleave(swiper) {
        if (!swiper || !swiper.slides) {
            return;
        }

        var interleaveOffset = getHeroInterleaveOffset();
        var innerOffset = (swiper.width || 0) * interleaveOffset;

        for (var i = 0; i < swiper.slides.length; i++) {
            var slideProgress = Math.max(Math.min(swiper.slides[i].progress || 0, 1), -1);
            var innerTranslate = slideProgress * innerOffset;
            var slideInner = swiper.slides[i].querySelector(".slide-inner");

            if (slideInner) {
                slideInner.style.transform =
                    "translate3d(" + innerTranslate + "px, 0, 0)";
            }
        }
    }

    function initHeroSlider() {
        if (heroSwiper) {
            return heroSwiper;
        }

        if (typeof Swiper !== "function" || !jQuery(".hero-slider .swiper-container").length) {
            return null;
        }

        var $heroSlider = jQuery(".hero-slider .swiper-container");
        var totalSlides = $heroSlider.find(".swiper-slide").length;
        var shouldLoop = totalSlides > 1;

        heroSlideCount = totalSlides;

        var swiperOptions = {
            loop: shouldLoop,
            initialSlide: 0,
            preloadImages: true,
            updateOnImagesReady: true,
            speed: 1000,
            parallax: true,
            autoplay: false,
            watchSlidesProgress: true,
            pagination: {
                el: '.swiper-pagination',
                clickable: true,
            },

            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },

            on: {
                init: function() {
                    applyHeroInterleave(this);
                },

                progress: function() {
                    applyHeroInterleave(this);
                },

                touchStart: function() {
                  var swiper = this;
                  for (var i = 0; i < swiper.slides.length; i++) {
                    swiper.slides[i].style.transition = "";
                  }
                },

                setTransition: function(speed) {
                    var swiper = this;
                    for (var i = 0; i < swiper.slides.length; i++) {
                        swiper.slides[i].style.transition = speed + "ms";
                        var slideInner = swiper.slides[i].querySelector(".slide-inner");

                        if (slideInner) {
                            slideInner.style.transition = speed + "ms";
                        }
                    }
                }
            }
        };

        if (shouldLoop) {
            swiperOptions.loopedSlides = totalSlides;
        }

        heroSwiper = new Swiper(".hero-slider .swiper-container", swiperOptions);
        applyHeroInterleave(heroSwiper);

        return heroSwiper;
    }

    function resetHeroToFirstSlide() {
        if (!heroSwiper) {
            return;
        }

        if (heroSwiper.params && heroSwiper.params.loop && typeof heroSwiper.slideToLoop === "function") {
            heroSwiper.slideToLoop(0, 0, false);
        } else if (typeof heroSwiper.slideTo === "function") {
            heroSwiper.slideTo(0, 0, false);
        }

        if (typeof heroSwiper.updateProgress === "function") {
            heroSwiper.updateProgress();
        }

        if (typeof heroSwiper.updateSlidesClasses === "function") {
            heroSwiper.updateSlidesClasses();
        }

        applyHeroInterleave(heroSwiper);
    }

    function startHeroAutoplay() {
        resetHeroToFirstSlide();

        if (!heroSwiper || heroSlideCount <= 1 || !heroSwiper.autoplay || typeof heroSwiper.autoplay.start !== "function") {
            return;
        }

        heroSwiper.params.autoplay = $.extend({}, heroAutoplayOptions);
        heroSwiper.autoplay.start();
    }



    /*------------------------------------------
        = HIDE PRELOADER
    -------------------------------------------*/
    function hidePreloader(onHidden) {
        $('.preloader').delay(100).fadeOut(500, function() {

            //active wow
            if (wow) {
                wow.init();
            }

            if (typeof onHidden === "function") {
                onHidden();
            }


        });
    }

    function preloader() {
        if($('.preloader').length) {
            waitForHeroBackgrounds(function() {
                initHeroSlider();
                resetHeroToFirstSlide();
                hidePreloader(startHeroAutoplay);
            });
            return;
        }

        initHeroSlider();
        resetHeroToFirstSlide();
        startHeroAutoplay();
    }


    /*------------------------------------------
        = WOW ANIMATION SETTING
    -------------------------------------------*/
    var wow = null;
    if (typeof WOW === "function") {
        wow = new WOW({
            boxClass:     'wow',      // default
            animateClass: 'animated', // default
            offset:       0,          // default
            mobile:       true,       // default
            live:         true        // default
        });
    }


    /*------------------------------------------
        = ACTIVE POPUP IMAGE
    -------------------------------------------*/
    if ($(".fancybox").length) {
        $(".fancybox").fancybox({
            openEffect  : "elastic",
            closeEffect : "elastic",
            wrapCSS     : "project-fancybox-title-style"
        });
    }


    /*------------------------------------------
        = POPUP VIDEO
    -------------------------------------------*/
    if ($(".video-btn").length) {
        $(".video-btn").on("click", function(){
            $.fancybox({
                href: this.href,
                type: $(this).data("type"),
                'title'         : this.title,
                helpers     : {
                    title : { type : 'inside' },
                    media : {}
                },

                beforeShow : function(){
                    $(".fancybox-wrap").addClass("gallery-fancybox");
                }
            });
            return false
        });
    }


    /*------------------------------------------
        = ACTIVE GALLERY POPUP IMAGE
    -------------------------------------------*/
    if ($(".popup-gallery").length) {
        $('.popup-gallery').magnificPopup({
            delegate: 'a',
            type: 'image',

            gallery: {
              enabled: true
            },

            zoom: {
                enabled: true,

                duration: 300,
                easing: 'ease-in-out',
                opener: function(openerElement) {
                    return openerElement.is('img') ? openerElement : openerElement.find('img');
                }
            }
        });
    }


    /*------------------------------------------
        = FUNCTION FORM SORTING GALLERY
    -------------------------------------------*/
    function sortingGallery() {
        if ($(".sortable-gallery .gallery-filters").length) {
            var $container = $('.gallery-container');
            $container.isotope({
                filter:'*',
                animationOptions: {
                    duration: 750,
                    easing: 'linear',
                    queue: false,
                }
            });

            $(".gallery-filters li a").on("click", function() {
                $('.gallery-filters li .current').removeClass('current');
                $(this).addClass('current');
                var selector = $(this).attr('data-filter');
                $container.isotope({
                    filter:selector,
                    animationOptions: {
                        duration: 750,
                        easing: 'linear',
                        queue: false,
                    }
                });
                return false;
            });
        }
    }

    sortingGallery();


    /*------------------------------------------
        = MASONRY GALLERY SETTING
    -------------------------------------------*/
    function masonryGridSetting() {
        if ($('.masonry-gallery').length) {
            var $grid =  $('.masonry-gallery').masonry({
                itemSelector: '.grid-item',
                columnWidth: '.grid-item',
                percentPosition: true
            });

            $grid.imagesLoaded().progress( function() {
                $grid.masonry('layout');
            });
        }
    }

    // masonryGridSetting();


    /*------------------------------------------
        = STICKY HEADER
    -------------------------------------------*/
    // Function for clone an element for sticky menu
    function cloneNavForSticyMenu($ele, $newElmClass) {
        $ele.addClass('original').clone().insertAfter($ele).addClass($newElmClass).removeClass('original');
    }

    // clone home style 1 navigation for sticky menu
    if ($('.site-header .navigation').length) {
        cloneNavForSticyMenu($('.site-header .navigation'), "sticky-header");
    }

    var lastScrollTop = '';

    function stickyMenu($targetMenu, $toggleClass) {
        var st = $(window).scrollTop();
        var mainMenuTop = $('.site-header .navigation');

        if ($(window).scrollTop() > 1000) {
            if (st > lastScrollTop) {
                // hide sticky menu on scroll down
                $targetMenu.removeClass($toggleClass);

            } else {
                // active sticky menu on scroll up
                $targetMenu.addClass($toggleClass);
            }

        } else {
            $targetMenu.removeClass($toggleClass);
        }

        lastScrollTop = st;
    }


    /*------------------------------------------
        = HEADER SEARCH AREA
    -------------------------------------------*/
    if ($(".header-search-area").length) {
        var serachFormBox = $(".header-search-area .header-search-form");
        var openSeachBtn = $(".header-search-area .open-btn");
        
        $(document.body).append(serachFormBox);
        serachFormBox.hide();

        openSeachBtn.on("click", function(e) {
            serachFormBox.fadeIn();
            return false;
        });

        serachFormBox.on("click", function() {
            serachFormBox.fadeOut();
            return false;
        }).find(".form").on("click", function(e) {
            e.stopPropagation();
        })
    }


    /*------------------------------------------
        = PROGRESS BAR
    -------------------------------------------*/
    function progressBar() {
        if ($(".progress-bar").length) {
            var $progress_bar = $('.progress-bar');
            $progress_bar.appear();
            $(document.body).on('appear', '.progress-bar', function() {
                var current_item = $(this);
                if (!current_item.hasClass('appeared')) {
                    var percent = current_item.data('percent');
                    current_item.css('width', percent + '%').addClass('appeared').parent().append('<span>' + percent + '%' + '</span>');
                }
                
            });
        };
    }
    progressBar();


    /*------------------------------------------
        = FUNFACT
    -------------------------------------------*/
    if ($(".odometer").length) {
        $('.odometer').appear();
        $(document.body).on('appear', '.odometer', function(e) {
            var odo = $(".odometer");
            odo.each(function() {
                var countNumber = $(this).attr("data-count");
                $(this).html(countNumber);
            });
        });
    }


    /*------------------------------------------
        = PORTFOLIO SLIDER
    -------------------------------------------*/
    if ($(".portfolio-slider").length) {
        $(".portfolio-slider").owlCarousel({
            autoplay: false,
            smartSpeed: 300,
            margin: 0,
            loop:true,
            autoplayHoverPause:true,
            dots: false,
            responsive: {
                0 : {
                    items: 1
                },

                500 : {
                    items: 2
                },

                768 : {
                    items: 3
                },

                992 : {
                    items: 4
                }
            }
        });
    }


    /*------------------------------------------
        = PARTNERS SLIDER
    -------------------------------------------*/
    if ($(".partners-slider").length) {
        $(".partners-slider").owlCarousel({
            autoplay:true,
            smartSpeed: 300,
            margin: 30,
            loop:true,
            autoplayHoverPause:true,
            dots: false,
            responsive: {
                0 : {
                    items: 2
                },

                550 : {
                    items: 3
                },

                992 : {
                    items: 4
                },

                1200 : {
                    items: 5
                }
            }
        });
    }


    /*------------------------------------------
        = SERVICES SLIDER
    -------------------------------------------*/
    if ($(".services-slider").length) {
        $(".services-slider").owlCarousel({
            loop:true,
            margin: 30,
            smartSpeed: 500,
            responsive:{
                0 : {
                    items: 1,
                },
                
                550 : {
                    items: 2,
                    center: false,
                    margin: 10
                },
                
                992 : {
                    items: 3,
                    center: false,
                    margin: 10
                },
                
                1400:{
                    items:3
                }
            }
        });
    }


    /*------------------------------------------
        = PRODUCT CASES TO SLIDER
    -------------------------------------------*/
    function buildProductCasesSlider() {
        $(".cases-section").each(function() {
            var $section = $(this);
            var $caseLinks;
            var $rows;
            var $headerRow;
            var $slider;

            if ($section.find(".cases-slider").length || !$section.find(".product-advantages-header").length) {
                return;
            }

            $caseLinks = $section.find(".col-md-4 > .case-card-link");

            if (!$caseLinks.length) {
                return;
            }

            $rows = $section.find(".container > .row");
            $headerRow = $rows.first();
            $slider = $('<div class="cases-slider"></div>');

            $caseLinks.each(function() {
                var $slide = $('<div class="case-slide"></div>');
                $slide.append($(this));
                $slider.append($slide);
            });

            $rows.slice(1).remove();
            $headerRow.after($slider);
        });
    }

    buildProductCasesSlider();


    /*------------------------------------------
        = CASES SLIDER
    -------------------------------------------*/
    if ($(".cases-slider").length) {
        $(".cases-slider").each(function() {
            var $slider = $(this);
            var itemCount = $slider.children().length;

            $slider.owlCarousel({
                loop: itemCount > 1,
                margin: 30,
                smartSpeed: 500,
                nav: false,
                dots: true,
                autoplay: itemCount > 1,
                autoplayTimeout: 4000,
                autoplayHoverPause: true,
                responsive:{
                    0 : {
                        items: 1,
                    },

                    550 : {
                        items: Math.min(2, itemCount),
                        center: false,
                        margin: 10
                    },

                    992 : {
                        items: Math.min(3, itemCount),
                        center: false,
                        margin: 10
                    },

                    1400:{
                        items: Math.min(3, itemCount)
                    }
                }
            });
        });
    }


    /*------------------------------------------
        = TESTIMONIAL SLIDER
    -------------------------------------------*/
    if ($(".testimonial-slider").length) {
        $(".testimonial-slider").owlCarousel({
            items: 1,
            loop:true,
            smartSpeed: 500,
        });
    }



    /*------------------------------------------
        = PORTFOLIO SLIDER S2
    -------------------------------------------*/
    if ($(".portfolio-slider-s2").length) {
        $(".portfolio-slider-s2").owlCarousel({
            autoplay: false,
            smartSpeed: 300,
            margin: 0,
            loop:true,
            autoplayHoverPause:true,
            dots: false,
            responsive: {
                0 : {
                    items: 1
                },

                500 : {
                    items: 2
                },

                768 : {
                    items: 3
                }
            }
        });
    }


    /*------------------------------------------
        = POST SLIDER
    -------------------------------------------*/
    if($(".post-slider".length)) {
        $(".post-slider").owlCarousel({
            mouseDrag: false,
            smartSpeed: 500,
            margin: 30,
            loop:true,
            nav: true,
            navText: ['<i class="fi flaticon-back"></i>','<i class="fi flaticon-next"></i>'],
            dots: false,
            items: 1
        });
    }   
    

    /*------------------------------------------
        = RSVP FORM SUBMISSION
    -------------------------------------------*/
    if ($("#contact-form-main").length) {
        $("#contact-form-main").validate({
            rules: {
                name: {
                    required: true,
                    minlength: 2
                },

                email: "required",

                phone: "required",

            },

            messages: {
                name: "Please enter your name",
                email: "Please enter your email address",
                phone: "Please enter your phone number",
            },

            submitHandler: function (form) {
                $.ajax({
                    type: "POST",
                    url: "mail-contact.php",
                    data: $(form).serialize(),
                    success: function () {
                        $( "#loader").hide();
                        $( "#success").slideDown( "slow" );
                        setTimeout(function() {
                        $( "#success").slideUp( "slow" );
                        }, 3000);
                        form.reset();
                    },
                    error: function() {
                        $( "#loader").hide();
                        $( "#error").slideDown( "slow" );
                        setTimeout(function() {
                        $( "#error").slideUp( "slow" );
                        }, 3000);
                    }
                });
                return false; // required to block normal submit since you used ajax
            }

        });
    }



    /*==========================================================================
        WHEN DOCUMENT LOADING
    ==========================================================================*/
        $(window).on('load', function() {

            preloader();


            toggleMobileNavigation();

            smallNavFunctionality();
            initKefuWidget();

        });



    /*==========================================================================
        WHEN WINDOW SCROLL


    /*==========================================================================
        WHEN WINDOW RESIZE
    ==========================================================================*/
    $(window).on("resize", function() {
        toggleClassForSmallNav();

        clearTimeout($.data(this, 'resizeTimer'));

        $.data(this, 'resizeTimer', setTimeout(function() {
            smallNavFunctionality();
        }, 200));
    });


})(window.jQuery);
