(function ($) {
    "use strict";
    var WidgetDynamicGalleryHandler = function ($scope, $) {
        
        var dGallery_elem = $scope.find('.htmega-dynamic-gallery-active').eq(0);
        if( dGallery_elem.length > 0){ dGallery_elem[0].style.display='block'; }
        const dGallery_opt = dGallery_elem.data('settings');
        let exclude_posts = dGallery_opt.exclude_posts;
        let postLimit = dGallery_opt.post_limit;
        let menuActiveNumber = (dGallery_opt.menu_active_number)? dGallery_opt.menu_active_number:0;
        let post_found = postLimit;
        let containerHeight = '';
        let gallery_active_container = $(".htmega-dynamic-gallery-grid",dGallery_elem);
        if (dGallery_elem.length > 0) {
            var $isotopFilter = $('.htmega-dynamic-gallery-filter',dGallery_elem);
            var $isotopeGrid = $('.htmega-dynamic-gallery-grid',dGallery_elem);
            $isotopFilter.on('click', '[data-filter]', function() {
                $(".htmega-dynamic-gallery-flex-column").removeClass("htmega-load-item-effect");
                var $this = $(this),
                    $filterValue = $this.attr('data-filter'),
                    $targetIsotop = $this.parent().data('target');
                $this.addClass('is-checked').siblings().removeClass('is-checked');
                $($targetIsotop).isotope({
                    filter: $filterValue
                });
                
                let loadMoreItems = 1;
                for ( let i = 1; i<=$isotopFilter[0].children.length; i++) {
                    if($($isotopFilter[0].children[i]).hasClass('readmore_visibility')){
                        loadMoreItems++;
                    }
                }
                if( $(this).hasClass('readmore_visibility') || $isotopFilter[0].children.length == loadMoreItems || $($isotopFilter[0].children[0]).hasClass('readmore_visibility')){
                    $(".htmega-pro-load-more-wrapper."+dGallery_opt.unicid).css("display", "none");
                }else{
                    $(".htmega-pro-load-more-wrapper."+dGallery_opt.unicid).css("display", "block");
                }
                if(dGallery_opt.is_edit_mode != true){
                    let itemCheck = $(".htmega-gallery-item").hasClass(this.dataset['filter'].slice(1));

                    if( !itemCheck && '*' !== this.dataset['filter']){
                        htmegaPostsLoad(this.dataset['slug'], postLimit); 
                    }else if('*'!== this.dataset['filter'] ){
                        let itemCount = $(".htmega-gallery-item."+this.dataset['filter'].slice(1));
                        if(! $(this).hasClass('readmore_visibility') ){
                            if( itemCount.length < postLimit && '*' != this.dataset['filter'] && 0 != post_found ){
                                    let postLimitd = postLimit - itemCount.length;
                                    htmegaPostsLoad( this.dataset['slug'], postLimitd );  
                                }
                            }
                    }

                }             
            });
            if(dGallery_opt.is_edit_mode != true){

                if($isotopFilter[0]){
                    if( menuActiveNumber >=1 && $isotopFilter[0].children[0].dataset['filter'] =="*" ){
                        menuActiveNumber = menuActiveNumber;
                    } else if(menuActiveNumber == 0 && $isotopFilter[0].children[0].dataset['filter'] =="*" ){
                        menuActiveNumber =0;
                    } else{
                        menuActiveNumber -=1;
                    }
                    menuActiveNumber = $isotopFilter[0].children[menuActiveNumber].dataset['filter'];

                }else{
                    menuActiveNumber = '*';
                }
                    $isotopeGrid.imagesLoaded(function() {
                        $isotopeGrid.isotope({
                            itemSelector: '.htmega-gallery-item',
                            masonry: {
                                columnWidth: '.htmega-dynamic-gallery-flex-column'
                            },
                            filter: menuActiveNumber,
                            layoutMode: 'masonry',//fitRows
                        });
                    });

                    $(".htmega-pro-load-more-wrapper."+dGallery_opt.unicid).on('click',function(e){
                        e.preventDefault();
                        let loadmoreCate  = $(".htmega-dynamic-gallery-filter."+dGallery_opt.unicid+" button.is-checked").data('slug');
                        if(loadmoreCate){
                            htmegaPostsLoad(loadmoreCate, postLimit); 
                        } else{
                            htmegaPostsLoad('all',postLimit); 

                        }
                    });
                }

            $(dGallery_opt.img_popup).magnificPopup({
                type: 'image',
                gallery: {
                    enabled: true
                }
            });
        // ajax load function
        function htmegaPostsLoad(loadmoreCate, postLimit= null){

            $(".htmega-pro-load-more-wrapper ."+dGallery_opt.unicid).addClass('htmega-infinity-loading '+loadmoreCate);

            var data = {
                settings: dGallery_opt.display_options,
                args: dGallery_opt.args_json,
                catId: loadmoreCate,
                postLimit: postLimit,
                excludePost: exclude_posts,
                action: "htmega_ajax_dynamic_gallery_posts",
                security: dGallery_opt.security
            };
            var itemHTML = "";
            $.ajax({
                url:dGallery_opt.site_url,
                data: data,// form data
                method : 'POST',
                success:function(data){
                    containerHeight = gallery_active_container.outerHeight();
                    var obj = JSON.parse(data);
                    for(const item in obj){
                        if(item != 'post_ids_array' && item != 'no_post_found'){
                            itemHTML += obj[item];
                        }
                    }
                    $($isotopeGrid).append(itemHTML);
                    $isotopeGrid.imagesLoaded(function() {
                        if($($isotopeGrid).isotope()){
                            $($isotopeGrid).isotope('destroy');
                        }
                        $($isotopeGrid).fadeIn().css('height',containerHeight); 
                        let filterActive  = $(".htmega-dynamic-gallery-filter."+dGallery_opt.unicid+" button.is-checked").data('filter');
                        $isotopeGrid.isotope({
                            itemSelector: '.htmega-gallery-item',
                            masonry: {
                                columnWidth: '.htmega-dynamic-gallery-flex-column'
                            },
                            filter: filterActive,
                            layoutMode: 'masonry',//fitRows
                        });
                    });
                    
                    if( obj['post_ids_array'] ){
                        exclude_posts = obj['post_ids_array'];
                    };
                    
                    $(".htmega-pro-load-more-wrapper ."+dGallery_opt.unicid ).removeClass('htmega-infinity-loading');
                    if( postLimit >= obj['no_post_found'] ){
                        post_found= obj['no_post_found'];
                        $(".htmega-pro-load-more-wrapper."+dGallery_opt.unicid).css("display", "none");
                        $(".htmega-dynamic-gallery-filter."+dGallery_opt.unicid+" button.is-checked").addClass('readmore_visibility');
                    } else{
                        $(".htmega-pro-load-more-wrapper ."+dGallery_opt.unicid+">span").html(dGallery_opt.show_load_txt);
                    }
                    $(dGallery_opt.img_popup).magnificPopup({
                        type: 'image',
                        gallery: {
                            enabled: true
                        }
                    });

                }
            });
        }

     }

}

    
    // Run this code under Elementor.
    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction( 'frontend/element_ready/htmega-dynamic-gallery-addons.default', WidgetDynamicGalleryHandler);
    });

})(jQuery);
