(function ($) {

    var HTMegaAdvanceStickyHandler = function ($scope) {

        if ( !$scope.hasClass("htmega-advanced-sticky-yes") ){
          return;
        }
        var stickyWrapperArea = $($scope[0]),
            editorStickyWrapper = $scope.find('.htmega-advanced-sticky-editor'),
            editMode = elementorFrontend.isEditMode(),
            stickyData = '',
            defaultPosition = 'static';
            if( editMode ){
                stickyData = editorStickyWrapper.data('sticky_settings');
                defaultPosition = 'relative';
            } else {
                stickyData = JSON.parse(stickyWrapperArea[0].dataset['sticky_settings']);
            }

            if( undefined === stickyData ){
                return;
            }
    
        let sPosition = (stickyData.position) ? stickyData.position : 'top',
            sOffset = (stickyData.offset) ? parseInt(stickyData.offset) : 0,
            sZindex = (stickyData.z_index) ? stickyData.z_index : '99',
            sStickyUntill = (stickyData.sticky_untill) ? '#' + stickyData.sticky_untill : '',
            stickyOnScrollUp = (stickyData.sticky_on_scroll_up) ? stickyData.sticky_on_scroll_up : 'no',
            hideOnTablet = (stickyData.hide_on_tablet) ? stickyData.hide_on_tablet : 'no',
            hideOnMobile = (stickyData.hide_on_mobile) ? stickyData.hide_on_mobile : 'no',
            stickyAnimation = ('yes' == stickyData.sticky_animation) ? stickyData.sticky_animation : 'no',
            clPosition = sPosition,
            stickyWrapHegiht = stickyWrapperArea.outerHeight(true),
            totalOffset = stickyWrapperArea.offset().top + stickyWrapHegiht,
            sectionWidth = stickyWrapperArea.outerWidth(),
            columnOffset = 0;

        if( 'column' == sPosition ){
            sPosition = 'top';
            totalOffset = stickyWrapperArea.offset().top;
            let columnArea = stickyWrapperArea.parents('.elementor-widget-wrap').outerHeight();
            columnOffset = stickyWrapperArea.offset().top + parseInt( columnArea ) - stickyWrapHegiht;

            if( 'center' == $( stickyWrapperArea.parents('.elementor-widget-wrap')).css( 'align-items' )){
                columnOffset =  columnOffset - ( stickyWrapHegiht/2 );
            }
            if( 'flex-end' == $( stickyWrapperArea.parents('.elementor-widget-wrap')).css( 'align-items' )){
                columnOffset =  columnOffset - stickyWrapHegiht;
            }
        }

        let untilOffset = 0;
        if( '' != sStickyUntill ){
            untilOffset = $(sStickyUntill).offset().top + stickyWrapHegiht;
        }

        let prevScrollPos = $(window).scrollTop();

        if ( ($( '#wpadminbar' ) && 'fixed' === $( '#wpadminbar' ).css( 'position' ) ) && 'top' == sPosition ) {
            var offset = $( '#wpadminbar' ).outerHeight( true );
            sOffset += offset;
        }
        var HTMegaStickyToggler = function () {

            var windowScroll = $(window).scrollTop()+sOffset;
            if( 'column'!= clPosition ){
                windowScroll = windowScroll+stickyWrapHegiht;
            }

            var isScrollingUp = windowScroll <= prevScrollPos;
            prevScrollPos = windowScroll;

            if ( ( ( 'yes' == stickyOnScrollUp && isScrollingUp ) && totalOffset <= windowScroll ) || ( 'no' == stickyOnScrollUp && totalOffset <= windowScroll  ) ) {
                
                stickyWrapperArea.addClass('htmega-sticky-open');
                if ( stickyWrapperArea.parents('.elementor-widget-wrap').length && 'column'!= clPosition ){
                    stickyWrapperArea.css({'position':'fixed','z-index':sZindex,'max-width':sectionWidth+'px','width':'100%'});
                } else {
                    stickyWrapperArea.css({'position':'sticky','z-index':sZindex,'max-width':sectionWidth+'px','width':'100%'});
                }
                stickyWrapperArea.css( sPosition, sOffset+'px' );
            } else {
                stickyWrapperArea.removeClass('htmega-sticky-open');
                stickyWrapperArea.css({'position': defaultPosition,'z-index':''});
                if ( 'yes' == stickyAnimation ){
                    stickyWrapperArea.css(sPosition,-stickyWrapHegiht+'px');
                }
                if ( editMode ){
                    stickyWrapperArea.css(sPosition,0);
                }
            }
            // Until sticky section controll
            if ( '' != sStickyUntill && untilOffset <= windowScroll+stickyWrapHegiht ) {
                stickyWrapperArea.removeClass('htmega-sticky-open');
                stickyWrapperArea.css({'position':defaultPosition,'z-index':''});
            }
            // Column height sticky widget controll
            if (  columnOffset && columnOffset <=windowScroll ) {
                stickyWrapperArea.removeClass('htmega-sticky-open');
                stickyWrapperArea.css({'position':'absolute','z-index':sZindex,'bottom':'0','top':'auto'});
            }
        };

        let currentDevice = elementorFrontend.getCurrentDeviceMode();
        let activeDevices = 'yes';
        if( 'tablet' == currentDevice && 'yes' == hideOnTablet ){
            activeDevices = 'no';
        } else if( 'mobile' == currentDevice && 'yes' ==  hideOnMobile ){
            activeDevices = 'no';
        }
        if( 'yes' == activeDevices ){
            HTMegaStickyToggler();
            $(window).scroll(HTMegaStickyToggler);
        }
    };

    $(window).on('elementor/frontend/init', function () {

        elementorFrontend.hooks.addAction("frontend/element_ready/section", HTMegaAdvanceStickyHandler);
        elementorFrontend.hooks.addAction("frontend/element_ready/container", HTMegaAdvanceStickyHandler);
        elementorFrontend.hooks.addAction("frontend/element_ready/widget", HTMegaAdvanceStickyHandler);
    });

})(jQuery);