(function ($) {
    "use strict";
    var WidgetPostGridHandler = function ($scope, $) {
        
        var grid_elem = $scope.find('.htmega-post-grid-area').eq(0);
        if( grid_elem.length > 0){ grid_elem[0].style.display='block'; }
        const grid_opt = grid_elem.data('settings');
        let exclude_posts = grid_opt.exclude_posts;
        let postLimit = grid_opt.post_limit;
        let post_found = postLimit;
        let containerHeight = '';
        let gallery_active_container = $( ".htmega-post-grid-area",grid_elem );
        if (grid_elem.length > 0) {
            var $isotopeGrid = $('.htb-row',grid_elem );
            $(".htmega-pro-load-more-wrapper."+grid_opt.unicid).on('click',function(e){
                e.preventDefault();
                htmegaPostsLoad( postLimit ); 
            });
        // ajax load function
        function htmegaPostsLoad( postLimit= null ){
            var data = {
                settings: grid_opt.display_options,
                args: grid_opt.args_json,
                postLimit: postLimit,
                excludePost: exclude_posts,
                action: "htmega_ajax_post_gird_posts_load",
                security: grid_opt.security
            };
            var itemHTML = "";
            $.ajax({
                url:grid_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);
                    if( obj['post_ids_array'] ){
                        exclude_posts = obj['post_ids_array'];
                    };
                    
                    $(".htmega-pro-load-more-wrapper ."+grid_opt.unicid ).removeClass('htmega-infinity-loading');
                    if( postLimit >= obj['no_post_found'] ){
                        post_found= obj['no_post_found'];
                        $(".htmega-pro-load-more-wrapper."+grid_opt.unicid).css("display", "none");
                    } else{
                        $(".htmega-pro-load-more-wrapper ."+grid_opt.unicid+">span").html(grid_opt.show_load_txt);
                    }
                }
            });
        }

     }

}

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

})(jQuery);
