;(function ($) {

    "use strict";
    
    var pxl_scroll_top;
    var pxl_window_height;
    var pxl_window_width;
    var pxl_scroll_status = '';
    var pxl_last_scroll_top = 0;
    var pxl_post_slip = false;

    $(window).on('load', function () {
        $(".pxl-loader").addClass("is-loaded");
        $('.pxl-swiper-slider, .pxl-header-mobile-elementor').css('opacity', '1');
        $('.pxl-gallery-scroll').parents('body').addClass('body-overflow').addClass('body-visible-sm');
        pxl_window_width = $(window).width();
        pxl_window_height = $(window).height();
        solarva_header_sticky();
        solarva_header_mobile();
        solarva_scroll_to_top();
        solarva_footer_fixed();
        solarva_shop_quantity();
        solarva_submenu_responsive();
        solarva_panel_anchor_toggle();
        solarva_post_grid();
    });

    $(window).on('scroll', function () {
        pxl_scroll_top = $(window).scrollTop();
        pxl_window_height = $(window).height();
        pxl_window_width = $(window).width();
        if (pxl_scroll_top < pxl_last_scroll_top) {
            pxl_scroll_status = 'up';
        } else {
            pxl_scroll_status = 'down';
        }
        pxl_last_scroll_top = pxl_scroll_top;
        solarva_header_sticky();
        solarva_scroll_to_top();
        solarva_footer_fixed();
        solarva_ptitle_scroll_opacity();
        if (pxl_scroll_top < 100) {
            $('.elementor > .pin-spacer').removeClass('scroll-top-active');
        }
    });

    $(window).on('resize', function () {
        pxl_window_height = $(window).height();
        pxl_window_width = $(window).width();
        solarva_submenu_responsive();
        solarva_header_mobile();
        solarva_post_grid();
    });

    $(document).ready(function () {
        solarva_backtotop_progess_bar();
        solarva_type_file_upload();
        solarva_zoom_point();
        
        solarva_dynamic_resizing_image();
        solarva_menu_hover();
        pxl_hover_active();
        pxl_click_active();
        bindEventToElement('.pxl-list .pxl-item--single');
        render_value_input();
        renderValueToInputHidden();
        on_submit_cf7()

        let elRectCube = $('.pxl-heading .pxl-move-rect');
        if(elRectCube.length > 0) {
            if(elRectCube.hasClass('slide')) {
                gsap.to(elRectCube, {
                    x: -39, 
                    duration: 5,
                    repeat: -1, 
                    yoyo: true, 
                    ease: "linear"
                });
            }
            if(elRectCube.hasClass('spin')) {
                gsap.to(elRectCube, {
                    rotation: "+=360", 
                    duration: 5, 
                    repeat: -1, 
                    ease: "linear", 
                    transformOrigin: "50% 50%" 
                });
            }
        }

        let anchorButtons = $('.pxl-atc-anchor');
        if (anchorButtons.length) {
            $(anchorButtons).on('click', function(e) {
                e.preventDefault(); 
                let target = $(this).attr('data-anchor'); 
                let offset = parseInt($(this).attr('data-offset'));
                if ($(target).length) { 
                    $('html, body').animate({
                        scrollTop: $(target).offset().top + offset
                    }, 1000); 
                } 
            });
        }


        let elSwitchLanguage = $('.pxl-switch-language');

        if (elSwitchLanguage.length) {
            let btn = elSwitchLanguage.find('.pxl-btn-switch');
            let listLangs = elSwitchLanguage.find('.pxl-list--languages');
            let listNameLangs = elSwitchLanguage.find('.pxl-item--language');
            btn.on('mouseenter', function() {
                $(this).addClass('active');
            }).on('mouseleave', function() {
                $(this).removeClass('active');
            });

            listLangs.on('mouseenter', function() {
                $(this).addClass('active');
                btn.addClass('active');
            }).on('mouseleave', function() {
                $(this).removeClass('active');
                btn.removeClass('active');
            });

            listNameLangs.each(function() {
                $(this).on('click', function() {
                    listNameLangs.removeClass('current-language');
                    $(this).addClass('current-language');
                    btn.find('.pxl-btn--text').text($(this).attr('data-language'));
                })
            })
        }

        let fillProgress = (el) => {
            var value = el.val();
            var max = el.attr('max') || 100; 
            var percentage = (value / max) * 100;
            el.css('background', `linear-gradient(to right, var(--gradient-color-from) ${percentage}%, var(--gradient-color-to) ${percentage}%)`);
        }

        if($('input[type="range"]').length) {
            fillProgress($('input[type="range"]'));
            $('input[type="range"]').on('input', function() {
                fillProgress($(this));
            });
        }

        function getBlockPositions(blocks) {
            return blocks.map(function(block) {
                var rect = block.getBoundingClientRect();
                return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
            });
        }
    
        function drawCurvedLineBetweenBlocks(blockPositions, curvedLine) {
            var path = `M${blockPositions[0].x},${blockPositions[0].y}`;
            for (var i = 1; i < blockPositions.length; i++) {
                var cp1X = (blockPositions[i - 1].x + blockPositions[i].x) / 2;
                var cp1Y = blockPositions[i - 1].y;
    
                var cp2X = (blockPositions[i - 1].x + blockPositions[i].x) / 2;
                var cp2Y = blockPositions[i].y;
    
                path += ` C${cp1X},${cp1Y} ${cp2X},${cp2Y} ${blockPositions[i].x},${blockPositions[i].y}`;
            }
            $(curvedLine).attr('d', path);
        }
    
        // Chạy khi trang được tải xong
        let layout = $('.pxl-workflow-steps');
        if (layout.length) {
            layout.each(function() {
                let curvedLine = $(this).find('.pxl-curved-line path').first(); 
                let blocks = $(this).find('.pxl-item--index');
                let blockPositions = getBlockPositions(blocks.toArray());
                drawCurvedLineBetweenBlocks(blockPositions, curvedLine);
            });
        }
    
        $(window).on('resize', function() {
            let layout = $('.pxl-workflow-steps');
            if (layout.length) {
                layout.each(function() {
                    let curvedLine = $(this).find('.pxl-curved-line path').first();
                    let blocks = $(this).find('.pxl-item--index');
                    let blockPositions = getBlockPositions(blocks.toArray());
                    drawCurvedLineBetweenBlocks(blockPositions, curvedLine);
                });
            }
        });
        
        // Deactive Link
        $('.deactive-click a').on("click", function (e) {
            e.preventDefault();
        });

        /* Start Menu Mobile */
        $('.pxl-header-menu li.menu-item-has-children').append('<span class="pxl-menu-toggle"></span>');
        $('.pxl-menu-toggle').on('click', function () {
            if( $(this).hasClass('active')){
                $(this).closest('ul').find('.pxl-menu-toggle.active').toggleClass('active');
                $(this).closest('ul').find('.sub-menu.active').toggleClass('active').slideToggle();    
            }else{
                $(this).closest('ul').find('.pxl-menu-toggle.active').toggleClass('active');
                $(this).closest('ul').find('.sub-menu.active').toggleClass('active').slideToggle();
                $(this).toggleClass('active');
                $(this).parent().find('> .sub-menu').toggleClass('active');
                $(this).parent().find('> .sub-menu').slideToggle();
            }      
        });
    
        $("#pxl-nav-mobile, .pxl-anchor-mobile-menu").on('click', function () {
            $(this).toggleClass('active');
            $('body').toggleClass('body-overflow');
            $('.pxl-header-menu').toggleClass('active');
        });

        $(".pxl-menu-close, .pxl-header-menu-backdrop, #pxl-header-mobile .pxl-menu-primary a.is-one-page").on('click', function () {
            $(this).parents('.pxl-header-main').find('.pxl-header-menu').removeClass('active');
            $('#pxl-nav-mobile').removeClass('active');
            $('body').toggleClass('body-overflow');
        });
        /* End Menu Mobile */

        /* Menu Vertical */
        $('.pxl-nav-vertical li.menu-item-has-children > a').append('<span class="pxl-arrow-toggle"><i class="flaticon-right-arrow"></i></span>');
        $('.pxl-nav-vertical li.menu-item-has-children > a').on('click', function () {
            if( $(this).hasClass('active')){
                $(this).next().toggleClass('active').slideToggle(); 
            }else{
                $(this).closest('ul').find('.sub-menu.active').toggleClass('active').slideToggle();
                $(this).closest('ul').find('a.active').toggleClass('active');
                $(this).find('.pxl-menu-toggle.active').toggleClass('active');
                $(this).toggleClass('active');
                $(this).next().toggleClass('active').slideToggle();
            }   
        });

        /* Menu Hidden Sidebar Popup */
        $('.pxl-menu-hidden-sidebar li.menu-item-has-children > a').append('<span class="pxl-arrow-toggle"><i class="flaticon-right-arrow"></i></span>');
        $('.pxl-menu-hidden-sidebar li.menu-item-has-children > a').on('click', function () {
            if( $(this).hasClass('active')){
                $(this).next().toggleClass('active').slideToggle(); 
            }else{
                $(this).closest('ul').find('.sub-menu.active').toggleClass('active').slideToggle();
                $(this).closest('ul').find('a.active').toggleClass('active');
                $(this).find('.pxl-menu-toggle.active').toggleClass('active');
                $(this).toggleClass('active');
                $(this).next().toggleClass('active').slideToggle();
            }   
        });

        $('.pxl-menu-hidden-sidebar .pxl-menu-button').on('click', function () {
            $(this).parents('.pxl-menu-hidden-sidebar').toggleClass('active');
            $(this).parents('.pxl-menu-hidden-sidebar').removeClass('boxOut');
            $(this).parents('body').toggleClass('body-overflow');
        });
        $('.pxl-menu-popup-overlay').on('click', function () {
            $(this).parent().removeClass('active');
            $(this).parent().addClass('boxOut');
            $(this).parents('body').removeClass('body-overflow');
        });
        $('.pxl-menu-popup-close, .pxl-menu-hidden-sidebar .pxl-menu-hidden a.is-one-page').on('click', function () {
            $(this).parents('.pxl-menu-hidden-sidebar').removeClass('active');
            $(this).parents('.pxl-menu-hidden-sidebar').addClass('boxOut');
            $(this).parents('body').removeClass('body-overflow');
        });

        /* Mega Menu Max Height */
        var m_h_mega = $('li.pxl-megamenu > .sub-menu > .pxl-mega-menu-elementor').outerHeight();
        var w_h_mega = $(window).height();
        var w_h_mega_css = w_h_mega - 120;
        if(m_h_mega > w_h_mega) {
            $('li.pxl-megamenu > .sub-menu > .pxl-mega-menu-elementor').css('max-height', w_h_mega_css + 'px');
            $('li.pxl-megamenu > .sub-menu > .pxl-mega-menu-elementor').css('overflow-x', 'scroll');
        }
        /* End Mega Menu Max Height */

        /* Scroll To Top */
        $('.pxl-scroll-top').on('click', function () {
            $('html, body').animate({scrollTop: 0}, 1200);
            $(this).parents('.pxl-wapper').find('.elementor > .pin-spacer').addClass('scroll-top-active');
            return false;
        });

        /* Animate Time Delay */
        $('.pxl-grid-masonry').each(function () {
            var eltime = 80;
            var elt_inner = $(this).children().length;
            var _elt = elt_inner - 1;
            $(this).find('> .pxl-grid-item > .wow').each(function (index, obj) {
                $(this).css('animation-delay', eltime + 'ms');
                if (_elt === index) {
                    eltime = 80;
                    _elt = _elt + elt_inner;
                } else {
                    eltime = eltime + 80;
                }
            });
        });
        /* End Animate Time Delay */

        /* Lightbox Popup */
        setTimeout(function() {
            // Khởi tạo Magnific Popup
            $('.pxl-action-popup').magnificPopup({
                type: 'iframe',
                mainClass: 'mfp-fade',
                removalDelay: 160,
                preloader: false,
                fixedContentPos: false
            });
        
        
        }, 300);        

        $('.pxl-gallery-lightbox').each(function () {
            $(this).magnificPopup({
                delegate: 'a.lightbox',
                type: 'image',
                gallery: {
                    enabled: true
                },
                mainClass: 'mfp-fade',
            });
        });


        /* Cart Sidebar Popup */
        $(".pxl-cart-sidebar-button").on('click', function (e) {
            e.preventDefault()
            $('body').addClass('body-overflow');
            $('#pxl-cart-sidebar').addClass('active');
        });
        $("#pxl-cart-sidebar .pxl-popup--overlay, #pxl-cart-sidebar .pxl-item--close, #pxl-cart-sidebar .pxl-popup--close2").on('click', function () {
            console.log('Test trong theme js')
            $('body').removeClass('body-overflow');
            $('#pxl-cart-sidebar').removeClass('active');
        });

        /* Start Icon Bounce */
        var boxEls = $('.el-bounce, .pxl-image-effect1, .el-effect-zigzag');
        $.each(boxEls, function(boxIndex, boxEl) {
            loopToggleClass(boxEl, 'active');
        });

        function loopToggleClass(el, toggleClass) {
            el = $(el);
            let counter = 0;
            if (el.hasClass(toggleClass)) {
                waitFor(function () {
                    counter++;
                    return counter == 2;
                }, function () {
                    counter = 0;
                    el.removeClass(toggleClass);
                    loopToggleClass(el, toggleClass);
                }, 'Deactivate', 1000);
            } else {
                waitFor(function () {
                    counter++;
                    return counter == 3;
                }, function () {
                    counter = 0;
                    el.addClass(toggleClass);
                    loopToggleClass(el, toggleClass);
                }, 'Activate', 1000);
            }
        }

        function waitFor(condition, callback, message, time) {
            if (message == null || message == '' || typeof message == 'undefined') {
                message = 'Timeout';
            }
            if (time == null || time == '' || typeof time == 'undefined') {
                time = 100;
            }
            var cond = condition();
            if (cond) {
                callback();
            } else {
                setTimeout(function() {
                    waitFor(condition, callback, message, time);
                }, time);
            }
        }
        /* End Icon Bounce */

        /* Image Effect */
        if($('.pxl-image-tilt').length){
            $('.pxl-image-tilt').parents('.elementor-top-section').addClass('pxl-image-tilt-active');
            $('.pxl-image-tilt').each(function () {
                var pxl_maxtilt = $(this).data('maxtilt'),
                    pxl_speedtilt = $(this).data('speedtilt'),
                    pxl_perspectivetilt = $(this).data('perspectivetilt');
                VanillaTilt.init(this, {
                    max: pxl_maxtilt,
                    speed: pxl_speedtilt,
                    perspective: pxl_perspectivetilt
                });
            });
        }

        /* Select Theme Style */
        $('.wpcf7-select').each(function(){
            var $this = $(this), numberOfOptions = $(this).children('option').length;
          
            $this.addClass('pxl-select-hidden'); 
            $this.wrap('<div class="pxl-select"></div>');
            $this.after('<div class="pxl-select-higthlight"></div>');

            var $styledSelect = $this.next('div.pxl-select-higthlight');
            $styledSelect.text($this.children('option').eq(0).text());
          
            var $list = $('<ul />', {
                'class': 'pxl-select-options'
            }).insertAfter($styledSelect);
          
            for (var i = 0; i < numberOfOptions; i++) {
                $('<li />', {
                    text: $this.children('option').eq(i).text(),
                    rel: $this.children('option').eq(i).val()
                }).appendTo($list);
            }
          
            var $listItems = $list.children('li');
          
            $styledSelect.on('click', function (e) {
                e.stopPropagation();
                $('div.pxl-select-higthlight.active').not(this).each(function(){
                    $(this).removeClass('active').next('ul.pxl-select-options').addClass('pxl-select-lists-hide');
                });
                $(this).toggleClass('active');
            });
          
            $listItems.on('click', function (e) {
                e.stopPropagation();
                $styledSelect.text($(this).text()).removeClass('active');
                $this.val($(this).attr('rel'));
            });
          
            $(document).on('click', function () {
                $styledSelect.removeClass('active');
            });

        });

        /* Nice Select */
        $('.woocommerce-ordering .orderby, #pxl-sidebar-area select, .variations_form.cart .variations select, .pxl-open-table select, .pxl-nice-select').each(function () {
            $(this).niceSelect();
        });

        /* Section Particles */      
        setTimeout(function() {
            $(".pxl-row-particles").each(function() {
                particlesJS($(this).attr('id'), {
                  "particles": {
                    "number": {
                        "value": $(this).data('number'),
                    },
                    "color": {
                        "value": $(this).data('color')
                    },
                    "shape": {
                        "type": "circle",
                    },
                    "size": {
                        "value": $(this).data('size'),
                        "random": $(this).data('size-random'),
                    },
                    "line_linked": {
                        "enable": false,
                    },
                    "move": {
                        "enable": true,
                        "speed": 2,
                        "direction": $(this).data('move-direction'),
                        "random": true,
                        "out_mode": "out",
                    }
                  },
                  "retina_detect": true
                });
            });
        }, 400);

        /* Get checked input - Mailchimpp */
        $('.mc4wp-form input:checkbox').change(function(){
            if($(this).is(":checked")) {
                $('.mc4wp-form').addClass("pxl-input-checked");
            } else {
                $('.mc4wp-form').removeClass("pxl-input-checked");
            }
        });


        // Active Mega Menu Hover
        $('li.pxl-megamenu').hover(function(){
                $(this).parents('.elementor-section').addClass('section-mega-active');
            },function(){
                $(this).parents('.elementor-section').removeClass('section-mega-active');
        });

    });
    
    jQuery(document).ajaxComplete(function(event, xhr, settings){
        solarva_shop_quantity();
    });

    jQuery( document ).on( 'updated_wc_div', function() {
        solarva_shop_quantity();
    } );
     
    /* Header Sticky */
    function solarva_header_sticky() {
        if($('#pxl-header-elementor').hasClass('is-sticky')) {
            if (pxl_scroll_top > 100) {
                $('.pxl-header-elementor-sticky.pxl-sticky-stb').addClass('pxl-header-fixed');
                $('#pxl-header-mobile').addClass('pxl-header-mobile-fixed');
            } else {
                $('.pxl-header-elementor-sticky.pxl-sticky-stb').removeClass('pxl-header-fixed');
                $('#pxl-header-mobile').removeClass('pxl-header-mobile-fixed');
            }

            if (pxl_scroll_status == 'up' && pxl_scroll_top > 100) {
                $('.pxl-header-elementor-sticky.pxl-sticky-stt').addClass('pxl-header-fixed');
            } else {
                $('.pxl-header-elementor-sticky.pxl-sticky-stt').removeClass('pxl-header-fixed');
            }
        }

        $('.pxl-header-elementor-sticky').parents('body').addClass('pxl-header-sticky');
    }

    /* Header Mobile */
    function solarva_header_mobile() {
        var h_header_mobile = $('#pxl-header-elementor').outerHeight();
        if(pxl_window_width < 1199) {
            $('#pxl-header-elementor').css('min-height', h_header_mobile + 'px');
        }
    }

    /* Scroll To Top */
    function solarva_scroll_to_top() {
        if (pxl_scroll_top < pxl_window_height) {
            $('.pxl-scroll-top').addClass('pxl-off').removeClass('pxl-on');
        }
        if (pxl_scroll_top > pxl_window_height) {
            $('.pxl-scroll-top').addClass('pxl-on').removeClass('pxl-off');
        }
    }

    /* Footer Fixed */
    function solarva_footer_fixed() {
        setTimeout(function(){
            var h_footer = $('.pxl-footer-fixed #pxl-footer-elementor').outerHeight() - 1;
            $('.pxl-footer-fixed #pxl-main').css('margin-bottom', h_footer + 'px');
        }, 600);
    }

    /* WooComerce Quantity */
    function solarva_shop_quantity() {
        "use strict";
        $('#pxl-wapper .quantity').append('<span class="quantity-icon quantity-down pxl-icon--minus"></span><span class="quantity-icon quantity-up pxl-icon--plus"></span>');
        $('.quantity-up').on('click', function () {
            $(this).parents('.quantity').find('input[type="number"]').get(0).stepUp();
            $(this).parents('.woocommerce-cart-form').find('.actions .button').removeAttr('disabled');
        });
        $('.quantity-down').on('click', function () {
            $(this).parents('.quantity').find('input[type="number"]').get(0).stepDown();
            $(this).parents('.woocommerce-cart-form').find('.actions .button').removeAttr('disabled');
        });
        $('.quantity-icon').on('click', function () {
            var quantity_number = $(this).parents('.quantity').find('input[type="number"]').val();
            var add_to_cart_button = $(this).parents( ".product, .woocommerce-product-inner" ).find(".add_to_cart_button");
            add_to_cart_button.attr('data-quantity', quantity_number);
            add_to_cart_button.attr("href", "?add-to-cart=" + add_to_cart_button.attr("data-product_id") + "&quantity=" + quantity_number);
        });
        $('.woocommerce-cart-form .actions .button').removeAttr('disabled');
    }

    /* Menu Responsive Dropdown */
    function solarva_submenu_responsive() {
        var $solarva_menu = $('.pxl-header-elementor-main, .pxl-header-elementor-sticky');
        $solarva_menu.find('.pxl-menu-primary li').each(function () {
            var $solarva_submenu = $(this).find('> ul.sub-menu');
            if ($solarva_submenu.length == 1) {
                if ( ($solarva_submenu.offset().left + $solarva_submenu.width() + 0 ) > $(window).width()) {
                    $solarva_submenu.addClass('pxl-sub-reverse');
                }
            }
        });
    }

    function solarva_panel_anchor_toggle(){
        'use strict';
        $(document).on('click','.pxl-anchor-button',function(e){
            e.preventDefault();
            e.stopPropagation();
            var target = $(this).attr('data-target');
            $(target).toggleClass('active');
            $('body').addClass('body-overflow');
            $('.pxl-popup--conent .wow').addClass('animated').removeClass('aniOut');
            $('.pxl-popup--conent .fadeInPopup').removeClass('aniOut');
            if($(target).find('.pxl-search-form').length > 0){
                setTimeout(function(){
                    $(target).find('.pxl-search-form .pxl-search-field').focus();
                },1000);
            }
        });

        $('.pxl-anchor-button').each(function () {
            var t_target = $(this).attr('data-target');
            var t_delay = $(this).attr('data-delay-hover');
            $(t_target).find('.pxl-popup--conent').css('transition-delay', t_delay + 'ms');
            $(t_target).find('.pxl-popup--overlay').css('transition-delay', t_delay + 'ms');
        });

        $(".pxl-hidden-panel-popup .pxl-popup--overlay, .pxl-hidden-panel-popup .pxl-close-popup").on('click', function () {
            $('body').removeClass('body-overflow');
            $('.pxl-hidden-panel-popup').removeClass('active');
            $('.pxl-popup--conent .wow').addClass('aniOut').removeClass('animated');
            $('.pxl-popup--conent .fadeInPopup').addClass('aniOut');
        });

        if($(".pxl-atc-panel").length > 0) {
            $(".pxl-atc-panel").on('click', function () {
                $('body').addClass('body-overflow');
                let panelPopupContent = $('.pxl-atc-panel').parents($('#pxl-wapper')).find('.pxl-hidden-panel-popup');
                $(panelPopupContent).addClass('active');
            });
        }


        $(".pxl-button.pxl-atc-popup").on('click', function () {
            $('body').addClass('body-overflow');
            $(this).parents('.pxl-wapper').find('.pxl-page-popup').addClass('active');
        });
        $(".pxl-popup--close").on('click', function () {
            $('body').removeClass('body-overflow');
            $(this).parent().removeClass('active');
        });

        /* Custom Theme Style */
        $('blockquote:not(.pxl-blockquote)').append('<i class="pxl-blockquote-icon flaticon-quote-1 text-gradient"></i>');
    }

    /* Post Grid */
    function solarva_post_grid() {
        setTimeout(function(){
            $('.pxl-item--inner').each(function () {
                var item_w = $(this).outerWidth();
                var item_h = $(this).outerHeight();
                $(this).find('.pxl-item--imgfilter').css('width', item_w + 'px');
                $(this).find('.pxl-item--imgfilter').css('height', item_h + 'px');
            });
        }, 300);
    }

    /* Page Title Scroll Opacity */
    function solarva_ptitle_scroll_opacity() {
        var divs = $('#pxl-page-title-elementor.pxl-scroll-opacity .elementor-widget'),
            limit = $('#pxl-page-title-elementor.pxl-scroll-opacity').outerHeight();
        if (pxl_scroll_top <= limit) {
            divs.css({ 'opacity' : (1 - pxl_scroll_top/limit)});
        }
    }

    /* Preloader Default */
    $.fn.extend({
        jQueryImagesLoaded: function () {
          var $imgs = this.find('img[src!=""]')

          if (!$imgs.length) {
            return $.Deferred()
              .resolve()
              .promise()
          }

          var dfds = []

          $imgs.each(function () {
            var dfd = $.Deferred()
            dfds.push(dfd)
            var img = new Image()
            img.onload = function () {
              dfd.resolve()
            }
            img.onerror = function () {
              dfd.resolve()
            }
            img.src = this.src
          })

          return $.when.apply($, dfds)
        }
    })

    /* Back To Top Progress Bar */
    function solarva_backtotop_progess_bar() {
        if($('.pxl-scroll-top').length > 0) {
            var progressPath = document.querySelector('.pxl-scroll-top .pxl-scroll-progress-circle path');
            var pathLength = progressPath.getTotalLength();
            progressPath.style.transition = progressPath.style.WebkitTransition = 'none';
            progressPath.style.strokeDasharray = pathLength + ' ' + pathLength;
            progressPath.style.strokeDashoffset = pathLength;
            progressPath.getBoundingClientRect();
            progressPath.style.transition = progressPath.style.WebkitTransition = 'stroke-dashoffset 10ms linear';      
            var updateProgress = function () {
                var scroll = $(window).scrollTop();
                var height = $(document).height() - $(window).height();
                var progress = pathLength - (scroll * pathLength / height);
                progressPath.style.strokeDashoffset = progress;
            }
            updateProgress();
            $(window).scroll(updateProgress);   
            var offset = 50;
            var duration = 550;
            $(window).on('scroll', function() {
                if ($(this).scrollTop() > offset) {
                    $('.pxl-scroll-top').addClass('active-progress');
                } else {
                    $('.pxl-scroll-top').removeClass('active-progress');
                }
            });
        }
    }

    /* Custom Type File Upload*/
    function solarva_type_file_upload() {

        var multipleSupport = typeof $('<input/>')[0].multiple !== 'undefined',
        isIE = /msie/i.test( navigator.userAgent );

        $.fn.pxl_custom_type_file = function() {

            return this.each(function() {

            var $file = $(this).addClass('pxl-file-upload-hidden'),
            $wrap = $('<div class="pxl-file-upload-wrapper">'),
            $button = $('<button type="button" class="pxl-file-upload-button">Choose File</button>'),
            $input = $('<input type="text" class="pxl-file-upload-input" placeholder="No File Choose" />'),
            $label = $('<label class="pxl-file-upload-button" for="'+ $file[0].id +'">Choose File</label>');
            $file.css({
                position: 'absolute',
                opacity: '0',
                visibility: 'hidden'
            });

            $wrap.insertAfter( $file )
            .append( $file, $input, ( isIE ? $label : $button ) );

            $file.attr('tabIndex', -1);
            $button.attr('tabIndex', -1);

            $button.on('click', function () {
                $file.focus().click();
            });

            $file.change(function() {

            var files = [], fileArr, filename;

            if ( multipleSupport ) {
                fileArr = $file[0].files;
                for ( var i = 0, len = fileArr.length; i < len; i++ ) {
                files.push( fileArr[i].name );
                }
                filename = files.join(', ');
            } else {
                filename = $file.val().split('\\').pop();
            }

            $input.val( filename )
                .attr('title', filename)
                .focus();
            });

            $input.on({
                blur: function() { $file.trigger('blur'); },
                keydown: function( e ) {
                if ( e.which === 13 ) {
                    if ( !isIE ) { 
                        $file.trigger('click'); 
                    }
                } else if ( e.which === 8 || e.which === 46 ) {
                    $file.replaceWith( $file = $file.clone( true ) );
                    $file.trigger('change');
                    $input.val('');
                } else if ( e.which === 9 ){
                    return;
                } else {
                        return false;
                    }
                }
            });

            });

        };
        $('.wpcf7-file[type=file]').pxl_custom_type_file();
    }

    // Zoom Point
    function solarva_zoom_point() {
        $(".pxl-zoom-point").each(function () {

            let scaleOffset = $(this).data('offset');
            let scaleAmount = $(this).data('scale-mount');

            function scrollZoom() {
                const images = document.querySelectorAll("[data-scroll-zoom]");
                let scrollPosY = 0;
                scaleAmount = scaleAmount / 100;

                const observerConfig = {
                    rootMargin: "0% 0% 0% 0%",
                    threshold: 0
                };

                images.forEach(image => {
                    let isVisible = false;
                    const observer = new IntersectionObserver((elements, self) => {
                        elements.forEach(element => {
                            isVisible = element.isIntersecting;
                        });
                    }, observerConfig);

                    observer.observe(image);

                    image.style.transform = `scale(${1 + scaleAmount * percentageSeen(image)})`;

                    window.addEventListener("scroll", () => {
                    if (isVisible) {
                        scrollPosY = window.pageYOffset;
                        image.style.transform = `scale(${1 +
                        scaleAmount * percentageSeen(image)})`;
                    }
                    });
                });

                function percentageSeen(element) {
                    const parent = element.parentNode;
                    const viewportHeight = window.innerHeight;
                    const scrollY = window.scrollY;
                    const elPosY = parent.getBoundingClientRect().top + scrollY + scaleOffset;
                    const borderHeight = parseFloat(getComputedStyle(parent).getPropertyValue('border-bottom-width')) + parseFloat(getComputedStyle(element).getPropertyValue('border-top-width'));
                    const elHeight = parent.offsetHeight + borderHeight;

                    if (elPosY > scrollY + viewportHeight) {
                        return 0;
                    } else if (elPosY + elHeight < scrollY) {
                        return 100;
                    } else {
                        const distance = scrollY + viewportHeight - elPosY;
                        let percentage = distance / ((viewportHeight + elHeight) / 100);
                        percentage = Math.round(percentage);

                        return percentage;
                    }
                }
            }

            scrollZoom();

        });
    }

    function on_submit_cf7() {
        let contactForms = $('.pxl-contact-form');
        contactForms.each(function() {
            let form = $(this).find('.wpcf7-form');
            let fromWrap = $(this).find('.pxl-wpcf7-wrap'); 
            $(form).on('wpcf7submit', function(e) {
                $(fromWrap).removeClass('loading');
            });
            
            $(form).on('wpcf7beforesubmit', function(e) {
                $(fromWrap).addClass('loading');
            });
        });
    }

    function render_value_input() {
        const sliders = $('.wpcf7 input[type="range"]');
        sliders.each(function() {
            const id = $(this).attr('id');
            const label = $(`label[for="${id}"]`);
            const value = label.find('.label-number > span').first();
            value.text($(this).val());            
            $(this).on('input', function() {
                value.text($(this).val());
            });
        });
    }
    
    function solarva_menu_hover() {
        let navMenu = $('.pxl-nav-menu.menu-hover-box-green, .pxl-nav-menu.menu-hover-devider-below');
        if (navMenu.length) {
            navMenu.each(function() {
                let links = navMenu.find('.pxl-menu-primary > li > a');
                links.each(function() {
                    let link = $(this);
                    let lastMouseX;
                    let isDirection = true;
                    link.on('mouseenter', function(event) {
                        links.removeClass('current-menu-hover')
                        $(this).addClass('current-menu-hover')
                        lastMouseX = event.clientX; 
                        let linkRect = this.getBoundingClientRect(); 
                        let linkCenterX = linkRect.left + (linkRect.width / 2); 
                        if (lastMouseX <= linkCenterX) {
                            this.style.setProperty('--afterWidth', '100%');
                            this.style.setProperty('--afterLeft', '0');
                            this.style.setProperty('--afterRight', 'auto');
                            isDirection = true; // Right
                        } else {
                            this.style.setProperty('--beforeWidth', '100%');
                            this.style.setProperty('--beforeLeft', 'auto');
                            this.style.setProperty('--beforeRight', '0');
                            isDirection = false; // Left
                        }
                    });
                    link.on('mouseleave', function(event) {
                        let currentMouseX = event.clientX;
                        let $menuItem = $(this).closest('.menu-item');
                        let $subMenuHovered = $menuItem.find('.sub-menu:hover').length;
                        let isMovingRight = currentMouseX > lastMouseX;
                        let currentLink = $(this);
                        const setBeforeAfterProperties = (beforeOrAfter) => {
                            currentLink.removeClass('current-menu-hover')
                            if (isMovingRight) {
                                this.style.setProperty(`--${beforeOrAfter}Left`, 'auto');
                                this.style.setProperty(`--${beforeOrAfter}Right`, '0');
                            } else {
                                this.style.setProperty(`--${beforeOrAfter}Left`, '0');
                                this.style.setProperty(`--${beforeOrAfter}Right`, 'auto');
                            }
                            this.style.setProperty(`--${beforeOrAfter}Width`, '0');
                        };

                        if ($subMenuHovered) {
                            currentLink.addClass('current-menu-hover')
                            $menuItem.find('.sub-menu').on('mouseleave', function() {
                                if (isDirection) {
                                    setBeforeAfterProperties('after');
                                } else {
                                    setBeforeAfterProperties('before');
                                }
                            })   
                        } else {
                            if (isDirection) {
                                setBeforeAfterProperties('after');
                            } else {
                                setBeforeAfterProperties('before');
                            }
                        }
                        lastMouseX = currentMouseX;
                    });
                    
                }); 
            });
        }        
    }


    function solarva_dynamic_resizing_image() {
        $('.elementor-section').each(function() {
            let $imgElements = $(this).find('.pxl-image-single.pxl-dynamic-resizing');
            
            if ($imgElements.length >= 2) {
                let img1 = $imgElements.eq(0); 
                let img2 = $imgElements.eq(1); 
        
                let el_section1 = img1.closest('.elementor-element');
                let el_section2 = img2.closest('.elementor-element');
        
                var widthEl1 = el_section1.width();
                var widthEl2 = el_section2.width();
        
                var maxWidthEl1 = parseFloat(el_section1.css('max-width')) || widthEl1;
                var maxWidthEl2 = parseFloat(el_section2.css('max-width')) || widthEl2;
    
                let offsetTop1 = el_section1.offset().top;
                let offsetTop2 = el_section2.offset().top;
    
                if (Math.abs(offsetTop1 - offsetTop2) < el_section1.outerHeight()) {
                    if (widthEl1 > widthEl2) {
                        gsap.to(el_section1, {
                            scrollTrigger: {
                                trigger: $(this),
                                start: "top-=500 top",
                                end: "bottom top",
                                scrub: true
                            },
                            width: widthEl2,
                            maxWidth: maxWidthEl2 ,
                            duration: 1.5,
                            ease: "linear"
                        });
                        gsap.to(el_section2, {
                            scrollTrigger: {
                                trigger: $(this),
                                start: "top-=500 top", 
                                end: "bottom top",
                                scrub: true
                            },
                            width: widthEl1,
                            maxWidth: maxWidthEl1 ,
                            duration: 1.5,
                            ease: "linear"
                        });
                    } else {
                        gsap.to(el_section2, {
                            scrollTrigger: {
                                trigger: $(this),
                                start: "top-=500 top", 
                                end: "bottom top",
                                scrub: true
                            },
                            width: widthEl1,
                            maxWidth: maxWidthEl1,
                            duration: 1.5,
                            ease: "linear"
                        });
                        gsap.to(el_section1, {
                            scrollTrigger: {
                                trigger: $(this),
                                start: "top-=500 top", 
                                end: "bottom top",
                                scrub: true
                            },
                            width: widthEl2,
                            maxWidth: maxWidthEl2 ,
                            duration: 1.5,
                            ease: "linear"
                        });
                    }
                }
        
        
            } 
        });
    }

    function bindEventToElement(elements, event='mousemove', active='active'){
        if (elements.length === 0) return;
        $(elements).each(function(index, element) {
            $(element).on(event, function() {
                $(elements).removeClass(active); 
                $(this).addClass(active); 
            });
        });
    }
    
    function renderValueToInputHidden() {
        let elements = $('.pxl-links.pxl-layout-vertical3 .pxl-item--link');
        if (elements.length > 0){
            let service = null;
            $(elements).each(function(index, element) {
                let parent = $(element).closest('.elementor-section');
                if (parent.length === 0) return;
            
                let cf7_heading = parent.find('.pxl-contact-form .pxl-heading--text')[0];
                let cf7_input = parent.find('.pxl-contact-form input[name="service"]')[0];
            
                if ($(element).hasClass('active')) {
                    service = $(element).text().trim();
                }
                $(element).on('click', function(e) {
                    e.preventDefault();
                    $(elements).removeClass('active');
                    $(this).addClass('active');
                    service = ($(this).text()).trim();
                    
                    if (cf7_heading) cf7_heading.textContent = service;
                    if (cf7_input) cf7_input.value = service;
                });
            
                if (cf7_heading) cf7_heading.textContent = service;
                if (cf7_input) cf7_input.value = service;
            });
        }
        
    }

    function pxl_hover_active() {
        let items = $('.pxl-contact-box.pxl-contact-box3 .pxl-item--single');
        let images = $('.pxl-contact-box.pxl-contact-box3 .pxl-item--image');
        if (items.length) {
            items.each(function() {
                $(this).on('mousemove', function() { 
                    items.removeClass('active')
                    $(this).addClass('active');
                    const item_index = $(this).attr('data-index') ?? 0;
                    images.each(function() {
                        const image_index = $(this).attr('data-index') ?? 0;
                        if(item_index === image_index) {
                            images.removeClass('active')
                            $(this).addClass('active');
                        }
                    })
                });
            });
        }
    }

    
    function pxl_click_active() {
        let items = $('.pxl-accordion.pxl-accordion2 .pxl-item--title');
        let images = $('.pxl-accordion.pxl-accordion2 .pxl-item--featured');
        if (items.length) {
            items.each(function(i1, el) {
                $(this).on('click', function() { 
                    const item_index = i1;    
                    images.removeClass('active');
                    images.each(function(i2) {
                        if(item_index === i2) {
                            $(this).addClass('active');
                        }
                    });
                });
            });
        }
    }
    

    
})(jQuery);