/*global jQuery */
/* Contents
// ------------------------------------------------>
	1.  LOADING SCREEN
	2.  BACKGROUND INSERT
	3.	NAV MODULE
	4.  MOBILE MENU
	5.  HEADER AFFIX
	6.  HEADER STATIC
	7.  COUNTER UP
	8.  COUNTDOWN DATE
	9.  AJAX MAILCHIMP
	10. AJAX CAMPAIGN MONITOR 
	11. OWL CAROUSEL
	12. MAGNIFIC POPUP
	13. MAGNIFIC POPUP VIDEO
	14. ROUNDED SKILL
	15. SWITCH GRID
	16. BACK TO TOP
	17. PORTFOLIO FLITER / SHOP FLITER
	18. FOLLOW INSTAGRAM
	19. TWITTER FEED
	20. FLICKR STREAM
	21. SCROLL TO
	22. PROGRESS BAR
	23. SWITCH GRID
	24. NAV SPLIT
	25. TYPED SCRIPT
	26. SLIDER RANGE
	27. YOUTUBE BACKGROUND
	28. COLUMN HEIGHT 
	29. FULLSCREEN CAROUSEL
	30. AJAX CONTACT FORM
	31. AJAX RESERVATION FORM
*/
(function($) {
    "use strict";
    /* ------------------  LOADING SCREEN ------------------ */

    $(window).on("load", function() {
        $(".preloader").fadeOut(10000);
        $(".preloader").remove();
    });

    /* ------------------  Background INSERT ------------------ */

    var $bgSection = $(".bg-section");
    var $bgPattern = $(".bg-pattern");
    var $colBg = $(".col-bg");

    $bgSection.each(function() {
        var bgSrc = $(this).children("img").attr("src");
        var bgUrl = 'url(' + bgSrc + ')';
        $(this).parent().css("backgroundImage", bgUrl);
        $(this).parent().addClass("bg-section");
        $(this).remove();
    });

    $bgPattern.each(function() {
        var bgSrc = $(this).children("img").attr("src");
        var bgUrl = 'url(' + bgSrc + ')';
        $(this).parent().css("backgroundImage", bgUrl);
        $(this).parent().addClass("bg-pattern");
        $(this).remove();
    });

    $colBg.each(function() {
        var bgSrc = $(this).children("img").attr("src");
        var bgUrl = 'url(' + bgSrc + ')';
        $(this).parent().css("backgroundImage", bgUrl);
        $(this).parent().addClass("col-bg");
        $(this).remove();
    });

    /* ------------------  NAV MODULE  ------------------ */
	
    var $moduleIcon = $(".module-icon"),
        $moduleCancel = $(".module-cancel");
    $moduleIcon.on("click", function(e) {
        $(this).parent().siblings().removeClass('module-active'); // Remove the class .active form any sibiling.
        $(this).parent(".module").toggleClass("module-active"); //Add the class .active to parent .module for this element.
        e.stopPropagation();
    });
    // If Click on [ Search-cancel ] Link
    $moduleCancel.on("click", function(e) {
        $(".module").removeClass("module-active");
        e.stopPropagation();
    });

    $(".side-nav-icon").on("click", function() {
        if ($(this).parent().hasClass('module-active')) {
            //$(".module-hamburger > .hamburger-panel").css;
            $(".wrapper").addClass("hamburger-active");
            $(this).addClass("module-hamburger-close");
        } else {
            //$(".module-hamburger").width(0);
            $(".wrapper").removeClass("hamburger-active");
            $(this).removeClass("module-hamburger-close");
        }

    });
    // If Click on [ Document ] and this click outside [ hamburger panel ]
    $(document).on("click", function(e) {
        if ($(e.target).is(".hamburger-panel,.hamburger-panel .list-links,.hamburger-panel .list-links a,.hamburger-panel .social-share,.hamburger-panel .social-share a i,.hamburger-panel .social-share a,.hamburger-panel .copywright") === false) {
            $(".wrapper").removeClass("page-transform"); // Remove the class .active form .module when click on outside the div.
            $(".module-side-nav").removeClass("module-active");
            e.stopPropagation();
        }
    });

    // If Click on [ Document ] and this click outside [ module ]
    $(document).on("click", function(e) {
        if ($(e.target).is(".module, .module-content, .search-form input,.cart-control .btn,.cart-overview a.cancel,.cart-box") === false) {
            $module.removeClass("module-active"); // Remove the class .active form .module when click on outside the div.
            e.stopPropagation();
        }
    });

    /* ------------------  MOBILE MENU ------------------ */

    var $dropToggle = $("ul.dropdown-menu [data-toggle=dropdown]"),
        $module = $(".module");
    $dropToggle.on("click", function(event) {
        event.preventDefault();
        event.stopPropagation();
        $(this).parent().siblings().removeClass("open");
        $(this).parent().toggleClass("open");
    });

    $module.on("click", function() {
        $(this).toggleClass("toggle-module");
    });
    $module.find("input.form-control", ".btn", ".module-cancel").on("click",function(e){
		 e.stopPropagation();
	});

    /* OLD HEADER CODE - REMOVED - Using new sticky header implementation below */

    /* ------------------  COUNTER UP ------------------ */

    $(".counting").counterUp({
        delay: 10,
        time: 1000
    });

    /* ------------------ COUNTDOWN DATE ------------------ */

    $(".countdown").each(function() {
        var $countDown = $(this),
            countDate = $countDown.data("count-date"),
            newDate = new Date(countDate);
        $countDown.countdown({
            until: newDate,
            format: "MMMM Do , h:mm:ss a"
        });
    });

    /* ------------------  AJAX MAILCHIMP ------------------ */

    $('.mailchimp').ajaxChimp({
        url: "http://wplly.us5.list-manage.com/subscribe/post?u=91b69df995c1c90e1de2f6497&id=aa0f2ab5fa", //Replace with your own mailchimp Campaigns URL.
        callback: chimpCallback

    });

    function chimpCallback(resp) {
        if (resp.result === 'success') {
            $('.subscribe-alert').html('<h5 class="alert alert-success">' + resp.msg + '</h5>').fadeIn(1000);
            //$('.subscribe-alert').delay(6000).fadeOut();

        } else if (resp.result === 'error') {
            $('.subscribe-alert').html('<h5 class="alert alert-danger">' + resp.msg + '</h5>').fadeIn(1000);
        }
    }

    /* ------------------  AJAX CAMPAIGN MONITOR  ------------------ */

    $('#campaignmonitor').submit(function(e) {
        e.preventDefault();
        $.getJSON(
            this.action + "?callback=?",
            $(this).serialize(),
            function(data) {
                if (data.Status === 400) {
                    alert("Error: " + data.Message);
                } else { // 200
                    alert("Success: " + data.Message);
                }
            });
    });

    /* ------------------ OWL CAROUSEL ------------------ */

    $(".carousel").each(function() {
        var $Carousel = $(this);
        $Carousel.owlCarousel({
            loop: $Carousel.data('loop'),
            autoplay: $Carousel.data("autoplay"),
            margin: $Carousel.data('space'),
            nav: $Carousel.data('nav'),
            dots: $Carousel.data('dots'),
            center: $Carousel.data('center'),
            dotsSpeed: $Carousel.data('speed'),
            responsive: {
                0: {
                    items: 1
                },
                600: {
                    items: $Carousel.data('slide-rs'),
                },
                1000: {
                    items: $Carousel.data('slide'),
                }
            }
        });
    });

    /* ------------------ MAGNIFIC POPUP ------------------ */

    var $imgPopup = $(".img-popup");
    $imgPopup.magnificPopup({
        type: "image"
    });
    $('.img-gallery-item').magnificPopup({
        type: 'image',
        gallery: {
            enabled: true
        }
    });

    /* ------------------  MAGNIFIC POPUP VIDEO ------------------ */

    $('.popup-video,.popup-gmaps').magnificPopup({
        disableOn: 700,
        mainClass: 'mfp-fade',
        removalDelay: 0,
        preloader: false,
        fixedContentPos: false,
        type: 'iframe',
        iframe: {
            markup: '<div class="mfp-iframe-scaler">' +
                '<div class="mfp-close"></div>' +
                '<iframe class="mfp-iframe" frameborder="0" allowfullscreen></iframe>' +
                '</div>',
            patterns: {
                youtube: {
                    index: 'youtube.com/',
                    id: 'v=',
                    src: '//www.youtube.com/embed/%id%?autoplay=1'
                }
            },
            srcAction: 'iframe_src',
        }
    });

    /* ------------------  ROUNDED SKILL ------------------ */

    $(window).on("scroll", function() {
        var skill = $('.skill'),
            scrollTop = $(window).scrollTop(),
            windowHeight = $(window).height(),
            roundedSkill = $('.rounded-skill');
        if (roundedSkill.length) {
            var wScroll = scrollTop + windowHeight,
                skillScroll = skill.offset().top + skill.outerHeight();
            if (wScroll > skillScroll) {
                roundedSkill.each(function() {
                    $(this).easyPieChart({
                        duration: 1000,
                        enabled: true,
                        scaleColor: false,
                        size: $(this).attr('data-size'),
                        trackColor: false,
                        lineCap: $(this).attr('data-line'),
                        lineWidth: $(this).attr('data-width'),
                        barColor: $(this).attr('data-color'),
                        animate: 5000,
                        onStep: function(from, to, percent) {
                            $(this.el).find('.prcent').text(Math.round(percent));
                        }
                    });
                });
            }
        }
    });

    /* ------------------  SWITCH GRID ------------------ */

    $('#switch-list').on("click", function(event) {
        event.preventDefault();
        $(this).addClass('active');
        $(this).siblings().removeClass("active");
        $(".product-item").each(function() {
            // "this" points to current item in looping through all elements with
            // class="Mandatory"
            $(this).addClass('product-list');
        });

    });
	
    $('#switch-grid').on("click", function(event) {

        event.preventDefault();
        $(this).addClass('active');
        $(this).siblings().removeClass("active");
        $(".product-item").each(function() {
            // "this" points to current item in looping through all elements with
            // class="Mandatory"
            $(this).removeClass('product-list');
        });

    });

    /* ------------------  BACK TO TOP ------------------ */

    var backTop = $('#back-to-top');
    if (backTop.length) {
        var scrollTrigger = 200, // px
            backToTop = function() {
                var scrollTop = $(window).scrollTop();
                if (scrollTop > scrollTrigger) {
                    backTop.addClass('show');
                } else {
                    backTop.removeClass('show');
                }
            };
        backToTop();
        $(window).on('scroll', function() {
            backToTop();
        });
        backTop.on('click', function(e) {
            e.preventDefault();
            $('html,body').animate({
                scrollTop: 0
            }, 700);
        });
    }

    /* ------------------ PORTFOLIO FLITER ------------------ */

    var $portfolioFilter = $(".portfolio-filter"),
        portfolioLength = $portfolioFilter.length,
        protfolioFinder = $portfolioFilter.find("a"),
        $portfolioAll = $("#portfolio-all");

    // init Isotope For Portfolio
    protfolioFinder.on("click", function(e) {
        e.preventDefault();
        $portfolioFilter.find("a.active-filter").removeClass("active-filter");
        $(this).addClass("active-filter");
    });
	
    if (portfolioLength > 0) {
        $portfolioAll.imagesLoaded().progress(function() {
            $portfolioAll.isotope({
                filter: "*",
                animationOptions: {
                    duration: 750,
                    itemSelector: ". portfolio-item ",
                    easing: "linear",
                    queue: false,
                }
            });
        });
    }
	
    protfolioFinder.on("click", function(e) {
        e.preventDefault();
        var $selector = $(this).attr("data-filter");
        $portfolioAll.imagesLoaded().progress(function() {
            $portfolioAll.isotope({
                filter: $selector,
                animationOptions: {
                    duration: 750,
                    itemSelector: ". portfolio-item ",
                    easing: "linear",
                    queue: false,
                }
            });
            return false;
        });
    });

    /* ------------------ SHOP FLITER ------------------ */

    var $shopFilter = $(".shop-filter"),
        shopLength = $shopFilter.length,
        shopFinder = $shopFilter.find("a"),
        $shopAll = $("#shop-all");

    // init Isotope For shop
    shopFinder.on("click", function(e) {
        e.preventDefault();
        $shopFilter.find("a.active-filter").removeClass("active-filter");
        $(this).addClass("active-filter");
    });
    if (shopLength > 0) {
        $shopAll.imagesLoaded().progress(function() {
            $shopAll.isotope({
                filter: "*",
                animationOptions: {
                    duration: 750,
                    itemSelector: ". productFilter",
                    easing: "linear",
                    queue: false,
                }
            });
        });
    }
    shopFinder.on("click", function(e) {
        e.preventDefault();
        var $selector = $(this).attr("data-filter");
        $shopAll.imagesLoaded().progress(function() {
            $shopAll.isotope({
                filter: $selector,
                animationOptions: {
                    duration: 750,
                    itemSelector: ". productFilter",
                    easing: "linear",
                    queue: false,
                }
            });
            return false;
        });
    });

    /* ------------------  FOLLOW INSTAGRAM ------------------ */
	
    var instafeedModule = $('#instafeedModule').length,
        instafeedSidebar = $('#instafeedSidebar').length,
        instafeedSection = $('#instafeedSection').length,
        InstaUserID = '6069962191',
        /*YOUR_USER_ID*/
        InstaAccessToken = '6069962191.1677ed0.2378d7ca8d274dae89847215f19cc93f'; /*YOUR_ACCESS_TOKEN*/
    if (instafeedModule > 0) {

        var userFeedModule = new Instafeed({
            target: 'instafeedModule',
            get: 'user',
            userId: InstaUserID,
            accessToken: InstaAccessToken,
            limit: $('.instafeed').data("insta-number"),
            template: '<a href="{{link}}" target="_blank"><img src="{{image}}" /><div class="insta-hover"><i class="fa fa-plus"></i></div></a>',
            resolution: 'low_resolution',
        });

        userFeedModule.run();
    }

    if (instafeedSidebar > 0) {

        var userFeedSidebar = new Instafeed({
            target: 'instafeedSidebar',
            get: 'user',
            userId: InstaUserID,
            accessToken: InstaAccessToken,
            limit: $('.instafeed').data("insta-number"),
            template: '<a href="{{link}}" target="_blank"><img src="{{image}}" /><div class="insta-hover"><i class="fa fa-plus"></i></div></a>',
            resolution: 'low_resolution',
        });
        userFeedSidebar.run();
    }

    if (instafeedSection > 0) {

        var userFeedSection = new Instafeed({
            target: 'instafeedSection',
            get: 'user',
            userId: InstaUserID,
            accessToken: InstaAccessToken,
            limit: $('.instafeed').data("insta-number"),
            template: '<a href="{{link}}" target="_blank"><img src="{{image}}" /><div class="insta-hover"><i class="fa fa-instagram"></i></div></a>',
            resolution: 'low_resolution',
        });
        userFeedSection.run();
    }

    /* ------------------  TWITTER FEED ------------------ */

    var twitterFeed = $('#twitter-feed'),
        twitterID = '721372281637888000', // Your Twitter Widget Id Here
        $twitterNumber = twitterFeed.data("tweets-number");
    if (twitterFeed.length > 0) {
        var twitterConfig = {
            "id": twitterID,
            "domId": 'twitter-feed',
            "maxTweets": $twitterNumber,
            "showUser": false,
            "showTime": true,
            "showRetweet": false,
            "showInteraction": false,
            "enableLinks": true,
            "customCallback": handleTweets,
            "dateFunction": momentDateFormatter,
        };

        function handleTweets(tweets) {
            var x = tweets.length;
            var n = 0;
            var element = document.getElementById('twitter-feed');
            var html = '<ul class="list-unstyled mb-0">';
            while (n < x) {
                html += '<li>' + tweets[n] + '</li>';
                n++;
            }
            html += '</ul>';
            element.innerHTML = html;
        }

        function momentDateFormatter(date, dateString) {
            return moment(dateString).fromNow();
        }
        twitterFetcher.fetch(twitterConfig);
    }

    /* ------------------  FLICKR STREAM ------------------ */

    var flickrID = '52617155@N08', // Your Flickr Account Id Here
        $flikrDiv = $('#flickr-feed'),
        $flikrNumber = $flikrDiv.data("flickr-number");
    $flikrDiv.jflickrfeed({
        limit: $flikrNumber,
        qstrings: {
            id: flickrID
        },
        itemTemplate: '<a class="flickr-item" href="{{image}}" title="{{title}}"><img src="{{image_s}}" alt="{{title}}" /></a>'
    }, function(data) {
        $('.flickr-item').magnificPopup({
            type: 'image',
            gallery: {
                enabled: true
            }
        });
    });

    /* ------------------  SCROLL TO ------------------ */

    var aScroll = $('a[data-scroll="scrollTo"]');
    aScroll.on('click', function(event) {
        var target = $($(this).attr('href'));
        if (target.length) {
            event.preventDefault();
            $('html, body').animate({
                scrollTop: target.offset().top - 100
            }, 1000);
            if ($(this).hasClass("menu-item")) {
                $(this).parent().addClass("active");
                $(this).parent().siblings().removeClass("active");
            }
        }
    });

    /* ------------------ PROGRESS BAR ------------------ */

    if ($(".skills").length > 0) {
        $(window).scroll(function() {
            var skillsTop = $(".skills").offset().top - 100,
                skillsHight = $(this).outerHeight(),
                wScroll = $(window).scrollTop();
            if (wScroll > skillsTop - 1 && wScroll < skillsTop + skillsHight - 1) {
                $(".progress-bar").each(function() {
                    $(this).width($(this).attr('aria-valuenow') + '%');
                });
            }
        });
    }

    if ($(".skills-scroll").length > 0) {
        $(".progress-bar").each(function() {
            $(this).width($(this).attr('aria-valuenow') + '%');
        });
    }

    /* ------------------  SWITCH GRID ------------------ */

    $('#switch-list').on("click", function(event) {
        event.preventDefault();
        $(this).addClass('active');
        $(this).siblings().removeClass("active");
        $(".product-item").each(function() {
            // "this" points to current item in looping through all elements with
            // class="Mandatory"
            $(this).addClass('product-list');
        });

    });
    $('#switch-grid').on("click", function(event) {

        event.preventDefault();
        $(this).addClass('active');
        $(this).siblings().removeClass("active");
        $(".product-item").each(function() {
            // "this" points to current item in looping through all elements with
            // class="Mandatory"
            $(this).removeClass('product-list');
        });

    });

    /* ------------------ NAV SPLIT ------------------ */

    if ($('.body-split').length > 0) {
        $(window).on("scroll", function() {
            $('.section').each(function() {

                var sectionID = $(this).attr("id"),
                    sectionTop = $(this).offset().top - 100,
                    sectionHight = $(this).outerHeight(),
                    wScroll = $(window).scrollTop(),
                    $navHref = $("a[href='#" + sectionID + "']"),
                    $nav = $('.nav-split').find($navHref).parent();
                if (wScroll > sectionTop - 1 && wScroll < sectionTop + sectionHight - 1) {
                    $nav.addClass('active');
                    $nav.siblings().removeClass('active');
                }
            });
        });
    }

    var $section = $('.section'),
        $bodyScroll = $('.body-scroll');
    if ($bodyScroll.length > 0) {
        $(window).on("scroll", function() {
            $section.each(function() {
                var sectionID = $(this).attr("id"),
                    sectionTop = $(this).offset().top - 100,
                    sectionHight = $(this).outerHeight(),
                    wScroll = $(window).scrollTop(),
                    $navHref = $("a[href='#" + sectionID + "']"),
                    $nav = $('.nav-onepage').find($navHref).parent();
                if (wScroll > sectionTop - 1 && wScroll < sectionTop + sectionHight - 1) {
                    $nav.addClass('active');
                    $nav.siblings().removeClass('active');
                }
            });
        });
    }
    /* ------------------ TYPED SCRIPT ------------------ */

    $(".typed-text").each(function() {
        var $string = $(this).data("typed-string") ? $(this).data("typed-string").split(",") : [];
        console.log($string);
        $(this).typed({
            strings: $string,
            typeSpeed: 0
        });

    });

    /* ------------------ SLIDER RANGE ------------------ */

    var $sliderRange = $("#slider-range"),
        $sliderAmount = $("#amount");
    $sliderRange.slider({
        range: true,
        min: 0,
        max: 500,
        values: [50, 300],
        slide: function(event, ui) {
            $sliderAmount.val("$" + ui.values[0] + " - $" + ui.values[1]);
        }
    });
    $sliderAmount.val("$" + $sliderRange.slider("values", 0) + " - $" + $sliderRange.slider("values", 1));

    /* ------------------  YOUTUBE BACKGROUND  ------------------ */

    $(".bg-ytvideo").each(function() {

        var vidId = $(this).data("vid-id"),
            vidAutoPlay = $(this).data("autoplay"),
            vidStartAt = $(this).data("start-at"),
            vidMute = $(this).data("mute"),
            vidOpacity = $(this).data("opacity"),
            vidShowPluginLogo = $(this).data("plugin-logo"),
            vidShowControls = $(this).data("controls"),
            vidFallBackImg = $(this).data("fall-cover");

        if (vidAutoPlay === "" || vidAutoPlay === null || vidAutoPlay === undefined) {
            vidAutoPlay = true;
        }
        if (vidStartAt === "" || vidStartAt === null || vidStartAt === undefined) {
            vidStartAt = 0;
        }
        if (vidMute === "" || vidMute === null || vidMute === undefined) {
            vidMute = true;
        }
        if (vidOpacity === "" || vidOpacity === null || vidOpacity === undefined) {
            vidOpacity = 1;
        }
        if (vidShowPluginLogo === "" || vidShowPluginLogo === null || vidShowPluginLogo === undefined) {
            vidShowPluginLogo = false;
        }
        if (vidShowControls === "" || vidShowControls === null || vidShowControls === undefined) {
            vidShowControls = false;
        }
        if (vidFallBackImg === "" || vidFallBackImg === null || vidFallBackImg === undefined) {
            vidFallBackImg = "";
        }

        $(this).data(
            "property",
            "{videoURL:'http://youtu.be/" + vidId + "',containment:'self',autoPlay:" + vidAutoPlay + ", mute:" + vidMute + ", startAt:" + vidStartAt + ", opacity:" + vidOpacity + ",showYTLogo:" + vidShowPluginLogo + ",showControls:" + vidShowControls + ",stopMovieOnBlur:false,mobileFallbackImage:'" + vidFallBackImg + "'}"
        );
    });

    $(".bg-ytvideo").mb_YTPlayer();

    /* ------------------ COLUMN HEIGHT  ------------------ */

    $(".comm-height").each(function() {
        var comHeightOuter = $(this).outerHeight(),
            colHeightContent = $(this).children(".col-content").outerHeight();
        if ($(this).length > 0) {
            if ($(window).width() > 991) {
                $(this).children("[class*=col-]").css('height', comHeightOuter);
            } else {
                $(this).children("[class*=col-]").css('height', colHeightContent);
            }
        }
    });

    /* ------------------ FULLSCREEN CAROUSEL  ------------------ */
	
    $(".fullscreen-sections").owlCarousel({
        loop: true,
        autoplay: true,
        autoplayHoverPause: true,
        animateOut: 'slideOutUp',
        animateIn: 'slideInUp',
        nav: false,
        dots: true,
        responsive: {
            0: {
                items: 1
            },
            600: {
                items: 1
            },
            1000: {
                items: 1
            }
        }

    });

    $(window).on("scroll", function() {
        var wScroll = $(window).scrollTop();
        if (wScroll > 100) {
            $('.logo-centered').css('display', 'none');
        } else {
            $('.logo-centered').css('display', 'block');
        }

    });

    /* ------------------  AAJAX CONTACT FORM  ------------------ */

    var contactForm = $(".contactForm"),
        contactResult = $('.contact-result');
    contactForm.validate({
        debug: false,
        submitHandler: function(contactForm) {
            $(contactResult, contactForm).html('Please Wait...');
            $.ajax({
                type: "POST",
                url: "assets/php/contact.php",
                data: $(contactForm).serialize(),
                timeout: 20000,
                success: function(msg) {
                    $(contactResult, contactForm).html('<div class="alert alert-success" role="alert"><strong>Thank you. We will contact you shortly.</strong></div>').delay(3000).fadeOut(2000);
                },
                error: $('.thanks').show()
            });
            return false;
        }
    });

    /* ------------------  AJAX RESERVATION FORM  ------------------ */

    var reservationPopupForm = $(".reservationForm"),
        reservationResult = $('.reservation-result');
    reservationPopupForm.validate({
        debug: false,
        submitHandler: function(reservationPopupForm) {
            $(reservationResult, reservationPopupForm).html('Please Wait...');
            $.ajax({
                type: "POST",
                url: "assets/php/reservation.php",
                data: $(reservationPopupForm).serialize(),
                timeout: 20000,
                success: function(msg) {
                    $(reservationResult, reservationPopupForm).html('<div class="alert alert-success" role="alert"><strong>Thank you. We will contact you shortly.</strong></div>').delay(3000).fadeOut(2000);
                },
                error: $('.thanks').show()
            });
            return false;
        }
    });

    /* ------------------ NEW HEADER MOBILE MENU TOGGLE & STICKY NAV ------------------- */
    
    function setupStickyHeader() {
        var headerMenuToggle = $("#headerMenuToggle");
        var headerNavMenu = $("#headerNavMenu");
        var headerDropdowns = $(".has-dropdown");
        var headerNavBar = $(".header-nav-bar");
        var headerMain = $(".header-main");
        var headerTopBar = $(".header-top-bar");
        var isHeaderSticky = false;
        var stickyOffset = 0;
        var headerTopBarHeight = 0;
        var headerMainHeight = 0;
        
        // Calculate sticky offset - THIS IS CRITICAL FOR STICKY HEADER TO WORK
        function calculateOffset() {
            try {
                // Get actual heights
                headerTopBarHeight = headerTopBar.length ? headerTopBar.outerHeight() : 0;
                headerMainHeight = headerMain.length ? headerMain.outerHeight() : 0;
                
                // Calculate total offset
                stickyOffset = headerTopBarHeight + headerMainHeight;
                
                // Make sure offset is not zero
                if (stickyOffset <= 0) {
                    stickyOffset = 200;
                }
                
                console.log("=== STICKY HEADER DEBUG ===");
                console.log("Top Bar Height: " + headerTopBarHeight + "px");
                console.log("Main Header Height: " + headerMainHeight + "px");
                console.log("Total Sticky Offset: " + stickyOffset + "px");
                console.log("========================");
            } catch (e) {
                console.log("Error calculating offset: " + e);
                stickyOffset = 200;
            }
        }
        
        // Initialize when DOM is ready
        calculateOffset();
        
        // Mobile menu toggle
        if (headerMenuToggle.length) {
            headerMenuToggle.on("click", function(e) {
                e.preventDefault();
                e.stopPropagation();
                headerNavMenu.toggleClass("active");
                console.log("Menu toggled, active state: " + headerNavMenu.hasClass("active"));
            });
        }
        
        // Mobile dropdown toggle
        if (headerDropdowns.length) {
            headerDropdowns.each(function() {
                var $dropdown = $(this);
                var $link = $dropdown.find("> a");
                
                $link.on("click", function(e) {
                    if ($(window).width() <= 768) {
                        e.preventDefault();
                        e.stopPropagation();
                        $dropdown.toggleClass("active");
                        console.log("Dropdown toggled, active state: " + $dropdown.hasClass("active"));
                    }
                });
            });
        }
        
        // Close menu when clicking non-dropdown links
        if (headerNavMenu.length) {
            headerNavMenu.find("a").not(".has-dropdown > a").on("click", function() {
                if ($(window).width() <= 768) {
                    headerNavMenu.removeClass("active");
                    console.log("Menu closed on link click");
                }
            });
        }
        
        // Sticky header on scroll - THIS IS THE MAIN SCROLL HANDLER
        // DISABLED ON MOBILE: Mobile header is already sticky via CSS
        var scrollCounter = 0;
        var wrapper = $(".wrapper");
        
        $(window).on("scroll", function() {
            // Only apply sticky header on desktop (wider than 768px)
            if ($(window).width() > 768) {
                scrollCounter++;
                var scrollTop = $(window).scrollTop();
                
                // Only log every 10th scroll event to avoid console spam
                if (scrollCounter % 10 === 0) {
                    console.log("Scroll: " + scrollTop + "px | Threshold: " + stickyOffset + "px | Sticky: " + isHeaderSticky);
                }
                
                if (scrollTop > stickyOffset) {
                    if (!isHeaderSticky) {
                        headerNavBar.addClass("sticky-active");
                        wrapper.addClass("sticky-nav-active");
                        isHeaderSticky = true;
                        console.log(">>> NAVBAR MADE STICKY <<<");
                    }
                } else {
                    if (isHeaderSticky) {
                        headerNavBar.removeClass("sticky-active");
                        wrapper.removeClass("sticky-nav-active");
                        isHeaderSticky = false;
                        console.log(">>> NAVBAR MADE RELATIVE <<<");
                    }
                }
            }
        });
        
        // Recalculate on window resize
        $(window).on("resize", function() {
            console.log("Window resized, recalculating offset...");
            calculateOffset();
            
            // Reset mobile menu on desktop
            if ($(window).width() > 768) {
                headerNavMenu.removeClass("active");
                headerDropdowns.removeClass("active");
                console.log("Desktop view detected, resetting mobile menus");
            }
        });
        
        // Trigger scroll on load to set initial state
        console.log("Setting up initial scroll state...");
        $(window).trigger("scroll");
    }
    
    // Setup sticky header when DOM is ready - with explicit checks
    console.log("Document ready state: " + document.readyState);
    
    if (document.readyState === 'loading') {
        $(document).ready(function() {
            console.log("DOM ready event fired");
            setupStickyHeader();
        });
    } else {
        console.log("DOM already loaded, setting up immediately");
        setupStickyHeader();
    }

    /* ------------------  MODERN CAROUSEL SLIDER (DYNAMIC) ------------------ */
    
    $(document).ready(function() {
        // Load sliders from backend
        loadCarouselSliders();

        function loadCarouselSliders() {
            fetch('backend/sliders_api.php?action=get_all')
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.data.length > 0) {
                        // Build carousel HTML from data
                        const sliders = data.data;
                        const container = document.getElementById('carouselContainer');
                        const indicatorsContainer = document.getElementById('carouselIndicators');
                        
                        // Create slide elements
                        let slidesHTML = '';
                        let indicatorsHTML = '';
                        
                        sliders.forEach((slider, index) => {
                            const isActive = index === 0 ? 'active' : '';
                            
                            // Build button HTML if button text exists
                            let buttonHTML = '';
                            if (slider.button_text) {
                                const buttonClasses = `btn ${slider.button_style}`;
                                buttonHTML = `<div class="slide-action"><a class="${buttonClasses}" href="${slider.button_link}">${slider.button_text}</a></div>`;
                            }
                            
                            slidesHTML += `
                                <div class="carousel-slide ${isActive}">
                                    <div class="slide-background" style="background-image: url('${slider.image_path}')"></div>
                                    <div class="slide-overlay"></div>
                                    <div class="slide-content">
                                        <div class="slide--subheadline">${slider.subheadline || ''}</div>
                                        <h2 class="slide--headline">${slider.headline}</h2>
                                        <p class="slide--bio">${slider.description || ''}</p>
                                        ${buttonHTML}
                                    </div>
                                </div>
                            `;
                            
                            indicatorsHTML += `<button class="indicator ${isActive}" data-slide="${index}" aria-label="Slide ${index + 1}"></button>`;
                        });
                        
                        container.innerHTML = slidesHTML;
                        indicatorsContainer.innerHTML = indicatorsHTML;
                        
                        // Initialize carousel after DOM is updated
                        initializeCarousel(sliders.length);
                    }
                })
                .catch(error => {
                    console.error('Error loading sliders:', error);
                });
        }

        function initializeCarousel(totalSlides) {
            // Carousel functionality
            const carousel = {
                currentSlide: 0,
                totalSlides: totalSlides,
                autoplayInterval: 5000,
                autoplayTimeout: null,

                init: function() {
                    this.updateSlide(this.currentSlide);
                    this.attachEventListeners();
                    this.startAutoplay();
                },

                updateSlide: function(index) {
                    // Remove active class from all slides and indicators
                    document.querySelectorAll('.carousel-slide').forEach(slide => {
                        slide.classList.remove('active');
                    });
                    document.querySelectorAll('.indicator').forEach(indicator => {
                        indicator.classList.remove('active');
                    });
                    
                    // Add active class to current slide and indicator
                    document.querySelectorAll('.carousel-slide')[index].classList.add('active');
                    document.querySelectorAll('.indicator')[index].classList.add('active');
                    
                    this.currentSlide = index;
                },

                nextSlide: function() {
                    const next = (this.currentSlide + 1) % this.totalSlides;
                    this.updateSlide(next);
                    this.resetAutoplay();
                },

                prevSlide: function() {
                    const prev = (this.currentSlide - 1 + this.totalSlides) % this.totalSlides;
                    this.updateSlide(prev);
                    this.resetAutoplay();
                },

                goToSlide: function(index) {
                    if (index >= 0 && index < this.totalSlides) {
                        this.updateSlide(index);
                        this.resetAutoplay();
                    }
                },

                startAutoplay: function() {
                    const self = this;
                    this.autoplayTimeout = setInterval(function() {
                        self.nextSlide();
                    }, this.autoplayInterval);
                },

                resetAutoplay: function() {
                    clearInterval(this.autoplayTimeout);
                    this.startAutoplay();
                },

                attachEventListeners: function() {
                    const self = this;
                    
                    // Next button
                    document.querySelectorAll('.carousel-nav-next').forEach(btn => {
                        btn.addEventListener('click', function() {
                            self.nextSlide();
                        });
                    });
                    
                    // Previous button
                    document.querySelectorAll('.carousel-nav-prev').forEach(btn => {
                        btn.addEventListener('click', function() {
                            self.prevSlide();
                        });
                    });
                    
                    // Indicator buttons
                    document.querySelectorAll('.indicator').forEach(indicator => {
                        indicator.addEventListener('click', function() {
                            const index = parseInt(this.getAttribute('data-slide'));
                            self.goToSlide(index);
                        });
                    });
                    
                    // Pause autoplay on hover
                    document.querySelectorAll('.carousel-container').forEach(container => {
                        container.addEventListener('mouseenter', function() {
                            clearInterval(self.autoplayTimeout);
                        });
                        container.addEventListener('mouseleave', function() {
                            self.startAutoplay();
                        });
                    });
                    
                    // Keyboard navigation
                    document.addEventListener('keydown', function(e) {
                        if (e.key === 'ArrowLeft') {
                            self.prevSlide();
                        } else if (e.key === 'ArrowRight') {
                            self.nextSlide();
                        }
                    });
                }
            };

            // Initialize carousel
            if (document.querySelector('.carousel-wrapper')) {
                carousel.init();
            }
        }
    });
	
}(jQuery));