<?php 
include_once(GG_DIR .'/classes/gg_local_images.php');
$fm = new gg_local_images();

dike_lc('lcweb', 'gg', true);
?>

<div class="wrap">  
    <h2 class="gg_page_title">
        Global Gallery <?php esc_html_e('Albums - Images Manager', 'gg_ml') ?>
        <a href="javascript:void(0)" id="gg_lim_create_folder" class="page-title-action">
            <i class="dashicons dashicons-plus-alt"></i>
            <span><?php esc_html_e('Create new folder', 'gg_ml') ?></span>
        </a>
        
        <?php if(current_user_can("manage_options")) : ?>
        <a href="javascript:void(0)" id="gg_lim_man_paths" class="page-title-action">
            <i class="dashicons dashicons-admin-generic"></i>
            <span><?php esc_attr_e("Manage base folder path", 'gg_ml') ?></span>
        </a>
        <?php endif; ?>
    </h2>  

    <div id="poststuff" class="metabox-holder">
        <?php
    
        // be sure the engine is ready to act
        $is_ready = $fm->is_ready();
    
        if($fm->is_ready() !== true) :
            
            if(!$fm->folder_error) {
                $fm->wp_filesys_setup_form();
            }
            else {
                echo 
                '<div class="error gg_fs_setup_error">
                    <p>'. esc_html($is_ready) .'. '. esc_html__("please check basepath", 'gg_ml') .'</p>
                </div>';  
                
                $fm->basepaths_setup_form();
            }
            
            echo '
            <style>
            #gg_lim_create_folder {
                display: none;
            }
            #gg_lim_paths_wrap {
                display: block !important;    
            }
            </style>';
        
        
        
        
        // manager code
        else :
            $fm->basepaths_setup_form();
            $folders_list = (array)$fm->list_folders();
        ?>

        
        <div id="gg_lim_dropzone">
            <div id="gg_lim_folders_n_uploader">
                <div id="gg_lim_folders_wrap">
                    <label><?php esc_html_e("Selected folder", 'gg_ml') ?></label>
                    
                    <select name="gg_lim_sel_folder" autocomplete="off">
                        <?php 
                        foreach($folders_list as $folder) {
                            echo '<option value="'. esc_attr($folder) .'">'. esc_html($folder) .'</option>';    
                        }
                        ?>
                    </select>

                    <strong class="gg_lim_imgs_counter">
                        <span>0</span> <?php esc_html_e('images') ?>
                    </strong>

                    <input type="button" name="gg_lim_del_folder" value="<?php esc_attr_e("delete folder", 'gg_ml') ?>" class="button-secondary gg_displaynone" />
                </div>
                
                <div id="gg_lim_uploader_wrap" class="gg_displaynone">
                    <input type="button" name="gg_lim_upload_btn" value="<?php esc_html_e('Upload Images', 'gg_ml') ?>" class="button-primary" /> 
                    <small class="gg_lim_maxsize_legend"><?php esc_html_e('Only JPG, PNG, GIF, WEBP, AVIF - max files size', 'gg_ml') ?> <?php echo esc_html(gg_static::human_filesize(wp_max_upload_size(), 0)) ?></small>

                    <div class="gg_lim_uploaders">
                        <input type="file" name="gg_lim_upl_input" accept=".jpg,.jpeg,.png,.gif,.webp,.avif" multiple />

                        <ul class="gg_lim_uploads_list"></ul>
                    </div>    
                </div>
            </div>
            
            
            <div class="gg_lim_bulk_cmd_wrap">
                <div id="gg_bulk_opt_wrap">
                    <label><?php esc_html_e('Bulk Options', 'gg_ml') ?></label>

                    <select name="gg_bulk_opt" id="gg_bulk_opt" autocomplete="off">
                        <option value="remove"><?php esc_html_e('Remove images', 'gg_ml') ?></option>
                        <option value="author"><?php esc_html_e('Set author', 'gg_ml') ?></option>
                        <option value="title"><?php esc_html_e('Set title', 'gg_ml') ?></option>
                        <option value="descr"><?php esc_html_e('Set description', 'gg_ml') ?></option>
                        <option value="folder_move"><?php esc_html_e('Move to another folder', 'gg_ml') ?></option>
                    </select>

                    <textarea name="gg_bulk_val" id="gg_bulk_val" autocomplete="off" class="gg_displaynone"></textarea>

                    <select name="gg_bulk_folder_move" id="gg_bulk_folder_move" autocomplete="off">
                        <?php 
                        foreach($folders_list as $folder) {
                            echo '<option value="'. esc_attr($folder) .'">'. esc_html($folder) .'</option>';    
                        }
                        ?>
                    </select>
                    
                    <input type="button" value="<?php esc_attr_e('Apply', 'gg_ml') ?>" id="gg_bulk_perform" class="button-secondary" />
                </div>
                
                <div id="gg_lim_layout_btn_wrap">
                    <input type="button" name="gg_lim_update_all" value="<?php esc_attr_e('Update all', 'gg_ml') ?>" class="button-primary" />
                    <input type="button" name="gg_lim_select_all" value="<?php esc_attr_e('Select all', 'gg_ml') ?>" class="button-secondary" />
                    
                    <a href="javascript:void(0)" id="gg_rows_builder_layout" class="<?php echo esc_attr(gg_static::builder_layout_selected('rows')) ?>" title="<?php esc_attr_e('Rows builder layout', 'gg_ml') ?>">
                        <span class="dashicons dashicons-menu-alt3"></span>
                    </a>
                    <a href="javascript:void(0)" id="gg_cols_builder_layout" class="<?php echo esc_attr(gg_static::builder_layout_selected('cols')) ?>" title="<?php esc_attr_e('Columns builder layout', 'gg_ml') ?>">
                        <span class="dashicons dashicons-screenoptions"></span>
                    </a>
                </div>
            </div>

            <div id="gg_lim_files_wrap" class="<?php echo (gg_static::builder_layout_selected('rows')) ? 'gg_rows_builder_layout' : '' ?>"></div>
        </div>
        <?php 
        endif; 
        ?>
    </div>
</div>  



<script type="text/javascript">
(function($) {
    "use strict"; 

    const $folder_sel_dd    = $('select[name="gg_lim_sel_folder"], #gg_bulk_folder_move'),
          nonce             = `<?php echo esc_js(wp_create_nonce('gg_files_manager')) ?>`,
          tt_url            = `<?php echo esc_js(GG_TT_URL) ?>`,
          ewpt_url          = `<?php echo esc_js(GG_EWPT_URL) ?>`,
          thumb_base_script = `<?php echo esc_js(((get_option('gg_use_timthumb')) ? GG_TT_URL : GG_EWPT_URL)) ?>`,
          
          no_img_code       = 
            `<div id="gg_lim_no_imgs_found">
                <h3>.. <?php esc_html_e("no images found", 'gg_ml') ?> ..</h3>
                <span class="dashicons dashicons-images-alt2"></span>
            </div>`;
    
    let sel_folder          = '',
        is_creating_folder  = false,
        is_deleting_folder  = false,
        is_operating_on_imgs= 0, // incerase/decrese number to allow multiple systems to operate separately
        folder_ajax_obj     = false,
        is_uploading        = false;
    
    
    $(document).ready(function() {
        $('textarea[name="#gg_bulk_val"]').gg_auto_h_textarea();
        
        
        // basepath manager toggle
        $('#gg_lim_man_paths').on('click', function() {
            $('#gg_lim_paths_wrap').toggle();           
        });



        // add folder - show modal
        $('#gg_lim_create_folder').on('click', function() {

            const modal_code = `
            <div id="gg_lim_create_folder_modal">
                <p>
                    <label>Folder Name</label>
                </p>
                <p>   
                    <input type="text" name="gg_lim_new_folder_name" autocomplete="off" maxlength="150" />
                </p>
                <p class="gg_lim_cfm_legend"><strong>NB: </strong> <?php esc_html_e("no accented letters, spaces or symbols. Hyphens and underscores accepted") ?></p>
                <p>
                    <input type="button" name="gg_lim_create_folder" value="<?php esc_attr_e('Create') ?>" class="button-primary" />
                    <span class="gg_lim_cfm_response"></span>

                    <input type="button" value="<?php esc_attr_e('Cancel') ?>" class="button-secondary" onclick="lcwpm_close()" />
                </p>
            </div>`;
            
            lc_wp_popup_message('modal', modal_code);
            $('input[name="gg_lim_new_folder_name"]').focus();
        });


        
        // add folder - ajax
        $(document).on('click', 'input[name="gg_lim_create_folder"]', function() {
            const $btn = $(this),
                  val = $.trim( $('input[name="gg_lim_new_folder_name"]').val() );
            
            if(!val || is_creating_folder) {
                return false;    
            }
            $('.gg_lim_cfm_response').empty();
            
            // sanitize value
            var regex = /^[a-zA-Z0-9_-]+$/;
            if(!regex.test(val)) {
                $('.gg_lim_cfm_response').html("<span class='gg_lim_cfm_error'><?php esc_attr_e("Invalid format", 'gg_ml') ?></span>");                
            }
            
            if(val.length > 150) {
                $('.gg_lim_cfm_response').html("<span class='gg_lim_cfm_error'><?php esc_attr_e("Too long", 'gg_ml') ?></span>");           
            }
            
            
            is_creating_folder = true;
            $btn.fadeTo(200, 0.5);
            
            // submit
            let data = {
                action  : 'gg_lim_create_folder',
                nonce   : nonce,
                f_name  : val
            };

            $.post(ajaxurl, data, function(response) {
                if($.trim(response) == 'success') {                
                    $('.gg_lim_cfm_response').html("<?php esc_attr_e("Folder successfully created!", 'gg_ml') ?>");
    
                    $folder_sel_dd.append('<option value="'+ val +'">'+ val +'</option>');
                    lc_select_for_folder_dd();
                    
                    setTimeout(function() {
                        lcwpm_close();
                    }, 1850);
                }
                else {
                   $('.gg_lim_cfm_response').html("<span class='gg_lim_cfm_error'>"+ response +"</span>"); 
                }
            })
            .fail(function(e) {
                console.error(e);
                $('.gg_lim_cfm_response').html("<span class='gg_lim_cfm_error'><?php esc_attr_e("Error creating the folder", 'gg_ml') ?></span>"); 
            })
            .always(function() {
                $btn.fadeTo(200, 1);
                is_creating_folder = false;    
            });	
        });
        
        
        
        // folder selection
        $(document).on('change', 'select[name="gg_lim_sel_folder"]', function(e) {
            const f_name = $(this).val();
           
            $('#gg_bulk_opt_wrap').css('visibility', 'hidden');
            $('.gg_lim_imgs_counter').addClass('gg_displaynone');
            
            // abort previous calls
            if(folder_ajax_obj) {
                folder_ajax_obj.abort();    
            }
            
            // no selection - reset
            if(!f_name) {
                $('#gg_lim_files_wrap').empty();
                $('input[name="gg_lim_del_folder"], #gg_lim_uploader_wrap').addClass('gg_displaynone');
                $('.gg_lim_bulk_cmd_wrap').css('visibility', 'hidden');
                
                return false;
            }
            
            // set folder and get images
            sel_folder = f_name;
            get_folder_images();
        });
        
        
        
        // get folder images
        const get_folder_images = function() {
            $('input[name="gg_lim_del_folder"], #gg_lim_uploader_wrap').removeClass('gg_displaynone');
            $('.gg_lim_bulk_cmd_wrap').css('visibility', 'visible');
            $('#gg_lim_files_wrap').html('<div class="gg_spinner gg_spinner_big"></div>');
            
            
            // load images
            let data = {
                action  : 'gg_lim_get_images',
                nonce   : nonce,
                f_name  : sel_folder
            };
            folder_ajax_obj = $.post(ajaxurl, data, function(response) {
                
                try {
                    const resp = JSON.parse(response);    

                    if(resp.status == 'success') {
                        if(!resp.images.length) {
                            $('#gg_lim_files_wrap').html(no_img_code);    
                            return true;
                        }

                        $('#gg_lim_files_wrap').html('<ul id="gg_fb_builder"></ul>');
                        images_columnize();
                        
                        $.each(resp.images, function(i, img_data) {
                            append_image(img_data);    
                        }); 
                        
                        $('.gg_lim_imgs_counter').removeClass('gg_displaynone');
                        
                        after_appended_images();
                        set_images_count();
                        read_imgs_data();
                    }
                    else {
                        lc_wp_popup_message('error', resp.message);   
                        $('#gg_lim_files_wrap').empty();
                    }
                }
                catch(e) {
                    console.error(e);
                    lc_wp_popup_message('error', "<?php esc_attr_e("Error retrieving images", 'gg_ml') ?>"); 

                    $('#gg_lim_files_wrap').empty();        
                }
            })
            .fail(function(e) {
                if(!e.status) {
                    return true;
                }
                
                console.error(e);
                lc_wp_popup_message('error', "<?php esc_attr_e("Error retrieving images", 'gg_ml') ?>"); 
                
                $('#gg_lim_files_wrap').empty();
            });         
        };
        
        
        
        // append image
        const append_image = function(img_data, prepend = false) {
            const thumb_url = 
                  <?php echo (!get_option('gg_use_admin_thumbs')) ? 
                    'img_data.url' : 
                    "get_thumb_maker_base(img_data.path) +'?src='+ img_data.path +'&w=400&h=&q=85&rs=3&zc=3'"; ?>;
            
            let code = '';

            if($.inArray(img_data.ext, ['jpg', 'jpeg', 'png', 'gif']) !== -1) {
                code = `
                <li data-path="${ img_data.path }" data-filename="${ img_data.name }" data-ext="${ img_data.ext }" data-size="${ img_data.size }">
                    <div class="gg_cmd_bar">
                        <div class="dashicons dashicons-saved gg_row_to_sel" title="<?php esc_attr_e('select image', 'gg_ml') ?>"></div>
                        <div class="far fa-save gg_update_local_img" title="<?php esc_attr_e('update image data', 'gg_ml') ?>"></div>
                        <div class="dashicons dashicons-no-alt gg_del_row" title="<?php esc_attr_e('delete image', 'gg_ml') ?>"></div>
                    </div>
                    <div class="gg_builder_img_wrap">
                        <figure style="background-image: url(${ thumb_url });" class="gg_builder_img" data-fullurl="${ img_data.url }" title="<?php esc_attr_e("click to enlarge", 'gg_ml') ?>"></figure>
                    </div>
                    <div class="gg_img_texts">
                        <table>
                          <tr>
                            <td class="gg_img_data_icon"><span class="dashicons dashicons-format-image" title="<?php esc_attr_e('file name', 'gg_ml') ?>"></span></td>
                            <td>&nbsp; ${ img_data.name }</td>
                          </tr>
                          <tr>
                            <td class="gg_img_data_icon"><span class="dashicons dashicons-admin-users" title="<?php esc_attr_e('photo author', 'gg_ml') ?>"></span></td>
                            <td><input type="text" name="gg_item_author" value="${ img_data.author }" autocomplete="off" /></td>
                          </tr>
                          <tr>
                            <td class="gg_img_data_icon"><span class="dashicons dashicons-editor-textcolor" title="<?php esc_attr_e('photo title', 'gg_ml') ?>"></span></td>
                            <td><textarea name="gg_item_title" autocomplete="off">${ img_data.title }</textarea></td>
                          </tr>
                          <tr>
                            <td class="gg_img_data_icon"><span class="dashicons dashicons-editor-alignleft" title="<?php esc_attr_e('photo description', 'gg_ml') ?>"></span></td>
                            <td><textarea name="gg_item_descr" autocomplete="off">${ img_data.descr }</textarea></td>
                          </tr>
                          <tr>
                            <td class="gg_img_data_icon"><span class="dashicons dashicons-tag" title="<?php esc_attr_e('photo tags - comma split', 'gg_ml') ?>"></span></td>
                            <td><textarea name="gg_item_tags" autocomplete="off">${ img_data.tags }</textarea></td>
                          </tr>
                        </table>
                    </div>
                </li>`;        
            }
            
            else {
                code = `
                <li data-path="${ img_data.path }" data-filename="${ img_data.name }" data-ext="${ img_data.ext }" data-size="${ img_data.size }">
                    <div class="gg_cmd_bar">
                        <div class="dashicons dashicons-saved gg_row_to_sel" title="<?php esc_attr_e('select image', 'gg_ml') ?>"></div>
                        <div class="dashicons dashicons-no-alt gg_del_row" title="<?php esc_attr_e('delete image', 'gg_ml') ?>"></div>
                    </div>
                    <div class="gg_builder_img_wrap">
                        <figure style="background-image: url(${ thumb_url });" class="gg_builder_img" data-fullurl="${ img_data.url }" title="<?php esc_attr_e("click to enlarge", 'gg_ml') ?>"></figure>
                    </div>
                    <div class="gg_img_texts">
                        <table>
                          <tr>
                            <td class="gg_img_data_icon"><span class="dashicons dashicons-format-image" title="<?php esc_attr_e('file name', 'gg_ml') ?>"></span></td>
                            <td>&nbsp; ${ img_data.name }</td>
                          </tr>
                          <tr>
                            <td class="gg_img_data_icon"><span class="dashicons dashicons-admin-users" title="<?php esc_attr_e('photo author', 'gg_ml') ?>"></span></td>
                            <td>${ img_data.author }</td>
                          </tr>
                          <tr>
                            <td class="gg_img_data_icon"><span class="dashicons dashicons-editor-textcolor" title="<?php esc_attr_e('photo title', 'gg_ml') ?>"></span></td>
                            <td>${ img_data.title }</td>
                          </tr>
                          <tr>
                            <td class="gg_img_data_icon"><span class="dashicons dashicons-editor-alignleft" title="<?php esc_attr_e('photo description', 'gg_ml') ?>"></span></td>
                            <td>${ img_data.descr }</td>
                          </tr>
                          <tr>
                            <td class="gg_img_data_icon"><span class="dashicons dashicons-tag" title="<?php esc_attr_e('photo tags - comma split', 'gg_ml') ?>"></span></td>
                            <td>${ img_data.tags }</td>
                          </tr>
                        </table>
                    </div>
                </li>`;    
            }
            
            (prepend) ? $('#gg_fb_builder').prepend(code) : $('#gg_fb_builder').append(code);
        };
        
        
        
        // operation after having appended/prepended images
        const after_appended_images = function() {
            // auto-resizing textarea
            $('textarea[name="gg_item_title"], textarea[name="gg_item_tags"]').gg_auto_h_textarea(true);
            $('textarea[name="gg_item_descr"]').gg_auto_h_textarea();
            
            if(!$('textarea[name="gg_item_title"]').length) {
                $('#gg_bulk_opt').find('option[value="author"], option[value="title"], option[value="descr"]').prop('disabled', 'disabled');
            } else {
                $('#gg_bulk_opt').find('option[value="author"], option[value="title"], option[value="descr"]').removeAttr('disabled');
            }  
        };
        
        
        
        // images info detection - pass through JS to not weight on server
        const read_imgs_data = function() {
            $('.gg_builder_img').each(function() {
                var $wrap = $(this).parents('li').first();

                if($wrap.find('.gg_img_info').length) {
                    return true;
                }
                var img_url = $(this).data('fullurl');

                // read weight and mime
                var blob = null;
                var xhr = new XMLHttpRequest();
                xhr.open("GET", img_url);
                xhr.responseType = "blob"; //force the HTTP response, response-type header to be blob
                xhr.onload = function() {
                    blob = xhr.response; //xhr.response is now a blob object

                    // image sizes
                    var img = new Image();
                    img.onload = function() {
                        var sizes = this.width + ' x ' + this.height +'px';

                        // append img info block
                        var $target = ($wrap.find('.gg_cmd_bar').length) ? $wrap.find('.gg_cmd_bar') : $wrap.find('.gg_builder_img'); 
                        $target.after('<div class="gg_img_info">\
                            <span>'+ $wrap.data('size') +'</span><span>'+ $wrap.data('ext') +'</span><span>'+ sizes +'</span>\
                        </div>');
                    }
                    img.src = img_url;
                };
                xhr.send();
            });	
        };
        
        

        // delete folder
        $(document).on('click', 'input[name="gg_lim_del_folder"]', function() {
            const $btn      = $(this),
                  f_name    = $folder_sel_dd.val();
            
            if(!f_name || is_deleting_folder || is_operating_on_imgs) {
                return false;    
            }
            
            const confirm_mess = "<?php esc_attr_e("WARNING: deleting %s folder you will also delete contained images. Continue?") ?>".replace('%s', f_name);
            if(!confirm(confirm_mess)) {
                return false;    
            }
            
            is_deleting_folder = true;
            $btn.fadeTo(200, 0.5);
            
            $folder_sel_dd.prop('disabled', 'disabled');
            lc_select_for_folder_dd();
            
            // submit
            let data = {
                action  : 'gg_lim_delete_folder',
                nonce   : nonce,
                f_name  : f_name
            };

            $.post(ajaxurl, data, function(response) {
                if($.trim(response) == 'success') {                
                    lc_wp_popup_message('success', "<?php esc_attr_e("Folder successfully deleted!", 'gg_ml') ?>");
                    
                    sel_folder = false;
                    $folder_sel_dd.find('option[value="'+ f_name +'"]').remove();
                    $folder_sel_dd.trigger('change');
                    
                    $btn.addClass('gg_displaynone');
                    $('.lcslt.lcslt-f-gg_lim_sel_folder').html('<span class="lcslt-placeholder">'+ $('.lcslt.lcslt-f-gg_lim_sel_folder').data("placeh") +'</span>');
                }
                else {
                    lc_wp_popup_message('error', response); 
                }
            })
            .fail(function(e) {
                console.error(e);
                lc_wp_popup_message('error', "<?php esc_attr_e("Error deleting the folder", 'gg_ml') ?>"); 
            })
            .always(function() {
                $btn.fadeTo(200, 1);
                is_deleting_folder = false; 
                $folder_sel_dd.removeAttr('disabled');
            });	
        });
        
        
        
        // delete image - handler
        $(document).on('click', '#gg_lim_files_wrap .gg_del_row', function(e) {
            const filename = $(this).parents('li').first().data('filename');
            delete_images( [filename] );
        });
        
        
        // delete images - perform
        const delete_images = function(filenames) {
            if(is_deleting_folder) {  
                return false;        
            }
            
            const skimmed = lock_imgs(filenames, 'delete');
            if(!skimmed.length) {
                lc_wp_popup_message('error', "<?php esc_attr_e("All selected images are currently busy", 'gg_ml') ?>");    
                return false;    
            }
            
            if(filenames.length > 1) {
                if(!confirm("<?php esc_attr_e("Do you really want to physically delete selected images from the server?", 'gg_ml') ?>")) {
                    return false;    
                }
            } else {
                if(!confirm("<?php esc_attr_e("Do you really want to physically delete this image from the server?", 'gg_ml') ?>")) {
                    return false;    
                }    
            }
            
            is_operating_on_imgs++;
            
            // perform
            let data = {
                action      : 'gg_lim_delete_files',
                nonce       : nonce,
                f_name      : sel_folder,
                files       : skimmed,
            };

            $.post(ajaxurl, data, function(response) {     
                try {
                    const resp = JSON.parse(response);    

                    if(resp.status == 'success') {

                        (resp.problems.length) ? 
                            lc_wp_popup_message('warning', "<?php esc_attr_e("Some images cannot be deleted", 'gg_ml') ?>") :
                            lc_wp_popup_message('success', "<?php esc_attr_e("Images successfully deleted!", 'gg_ml') ?>"); 


                        $.each(filenames, function(i, filename) {
                            if($.inArray(filename, resp.problems) === -1) {
                                $('#gg_fb_builder > li[data-filename="'+ filename +'"]').remove();    
                            }
                        });

                        set_images_count();
                    }
                    else {
                        lc_wp_popup_message('error', resp.message);   
                    }
                }
                catch(e) {
                    console.error(e);
                    lc_wp_popup_message('error', "<?php esc_attr_e("Error deleting images", 'gg_ml') ?>");    
                }
            })
            .fail(function(e) {
                console.error(e);
                lc_wp_popup_message('error', "<?php esc_attr_e("Error deleting images", 'gg_ml') ?>"); 
            })
            .always(function() {
                is_operating_on_imgs--;
                unlock_imgs(skimmed, 'delete');
            });	
        };
        
        
        
        // update single image's data - handler
        $(document).on('click', '#gg_lim_files_wrap .gg_update_local_img', function(e) {
            const filename = $(this).parents('li').first().data('filename');
            update_images( [filename] );
        });
        
        // update all images data - handler
        $(document).on('click', 'input[name="gg_lim_update_all"]', function(e) {
            let filenames = [];
            
            $('#gg_fb_builder > li').not('[data-ext="png"], [data-ext="gif"]').each(function() {
                filenames.push( $(this).data('filename'));        
            });

            update_images(filenames);
        });
        
        
        // update images data - perform
        const update_images = function(filenames) {
            if(is_deleting_folder) {  
                return false;        
            }
            
            const skimmed = lock_imgs(filenames, 'update');
            if(!skimmed.length) {
                lc_wp_popup_message('error', "<?php esc_attr_e("All selected images are currently busy", 'gg_ml') ?>");    
                return false;    
            }
            is_operating_on_imgs++;
            
            // retrieve images data
            let img_data = {};
            $.each(skimmed, function(i, filename) {
                const $img = $('#gg_fb_builder > li[data-filename="'+ filename +'"]');
                
                img_data[ filename ] = {
                    author  : $img.find('input[name="gg_item_author"]').val(),
                    title   : $img.find('textarea[name="gg_item_title"]').val(),
                    descr   : $img.find('textarea[name="gg_item_descr"]').val(),
                    tags    : $img.find('textarea[name="gg_item_tags"]').val(),
                };
            });
            
            
            // perform
            let data = {
                action      : 'gg_lim_update_images_data',
                nonce       : nonce,
                f_name      : sel_folder,
                img_data    : img_data,
            };

            $.post(ajaxurl, data, function(response) {     
                try {
                    const resp = JSON.parse(response);    

                    if(resp.status == 'success') {
                        lc_wp_popup_message('success', "<?php esc_attr_e("Images successfully updated!", 'gg_ml') ?>"); 
                    }
                    else {
                        lc_wp_popup_message('error', resp.message);   
                    }
                }
                catch(e) {
                    console.error(e);
                    lc_wp_popup_message('error', "<?php esc_attr_e("Error updating images", 'gg_ml') ?>");    
                }
            })
            .fail(function(e) {
                console.error(e);
                lc_wp_popup_message('error', "<?php esc_attr_e("Error updating images", 'gg_ml') ?>"); 
            })
            .always(function() {
                is_operating_on_imgs--;
                unlock_imgs(skimmed, 'updaate');
            });	
        };
        
        
        
        // LC select for folder selection
        const lc_select_for_folder_dd = function() {
            if($folder_sel_dd.length) {
                const placeh = ($folder_sel_dd.find('option').length) ? "<?php esc_attr_e("Please select a folder", 'gg_ml') ?>" : "<?php esc_attr_e("No folders found", 'gg_ml') ?>"; 
                $folder_sel_dd.attr('data-placeholder', placeh);
                
                // already initialized? refresh
                if($folder_sel_dd.parent().hasClass('lcslt')) {
                    $folder_sel_dd.each(function() {
                       
                        const event  = new Event('lc-select-refresh')
                        this.dispatchEvent(event); 
                    });
                    
                    return true;
                }
                
                new lc_select($folder_sel_dd, {
                    pre_placeh_opt  : true,
                    wrap_width      : '400px',
                    addit_classes   : ['lcslt-lcwp'],
                });
            }
        };
        lc_select_for_folder_dd();
        
        // open dropdown on page's opening
        if($('select[name="gg_lim_sel_folder"] option').length > 1) {
            $('.lcslt-f-gg_lim_sel_folder').trigger('click');    
        }
        
        
        
        // images block sizing - cycle to find proper size
        let fp_column_w_tout = false;
        $(window).resize(function() {
            if(fp_column_w_tout) {
                clearTimeout(fp_column_w_tout);
            }

            setTimeout(function() {
                images_columnize();
            }, 50);
        });

        // images block sizing - cycle to find proper size
        const images_columnize = function() {
            var w = $('#gg_fb_builder').width();

            for(let a=7; a>0; a--) {
                if( ((w / a) + 15) > 320 || a == 1 ) {

                    $('#gg_fb_builder').css('grid-template-columns', 'repeat('+ a +', 1fr)');
                    break; 	
                }
            }
        };
        
        
        
        // builder layout switch
        $(document).on('click', '#gg_rows_builder_layout, #gg_cols_builder_layout', function(e) {
            const $subj = $(this);
            if($subj.hasClass('selected')) {
                return false;    
            }

            const new_val = ($subj.attr('id') == 'gg_rows_builder_layout') ? 'rows' : 'cols',
                  expires = (new Date(Date.now() + (60 * 60 * 24 * 365) * 1000)).toUTCString();

            document.cookie = "gg_builder_layout="+ new_val +"; expires=" + expires + ";path=/;"

            $('#gg_lim_files_wrap').toggleClass('gg_rows_builder_layout');
            $('#gg_rows_builder_layout, #gg_cols_builder_layout').removeClass('selected');
            $subj.addClass('selected');
            
            images_columnize();
        });
        
        
        
        // LC lightbox for images preview
        $(document).on('click', ".gg_builder_img", function(e) {
            e.stopPropagation();
            const $clicked = $(this);
            
            let images = [],
                index = 0;
            
            $('#gg_fb_builder > li').each(function(i, v) {
                images.push({
                    type	: 'image',
                    src		: $(this).find('.gg_builder_img').data('fullurl'),
                    title   : $(this).find('.gg_img_texts tbody tr:nth-child(1) td:last-child').text(),
                    thumb   : get_thumb_maker_base($(this).data('path')) +'?src='+ $(this).data('path') +'&w=100&h=100',
                    download: $(this).find('.gg_builder_img').data('fullurl'),
                }); 
                
                if($clicked.is( $(this).find('.gg_builder_img') )) {
                    index = i;    
                }
            });

            var instance = lc_lightbox(images, {
                wrap_class		: 'lcl_zoomin_oc',
                max_width		: '85%', // Lightbox maximum width. Use a responsive percent value or an integer for static pixel value
                max_height		: '85%', 
                remove_scrollbar: false,
                download        : true,
                tn_hidden       : 5000,
                ins_close_pos	: 'corner',
                open_close_time	: 200,
                fading_time		: 200,
            });
            lcl_open(instance, index); // direct lightbox opening showing first element*/
        });
        
        
         
        
        /////////////////////////////////////////////////////////////////
        // BULK CONTROLS
        
        
        
        // single image select
        $(document).on('click', '.gg_row_to_sel', function() {
            $(this).toggleClass('gg_sel_row');
            $(this).parent().parent().toggleClass('selected');

            const visibility = ($('#gg_fb_builder > li.selected').length) ? 'visible' : 'hidden';
            $('#gg_bulk_opt_wrap').css('visibility', visibility);
        });



        // track button click
        $(document).on('click', 'input[name="gg_lim_select_all"]', function(e) {
            e.stopPropagation();

            if( $(this).hasClass('selected') ) {
                $(this).removeClass('selected').attr('value', '<?php esc_html_e('Select all', 'gg_ml') ?>');

                $('.gg_row_to_sel').each(function() {
                    $(this).removeClass('gg_sel_row');
                    $(this).parent().parent().removeClass('selected');
                });

                $('#gg_bulk_opt_wrap').css('visibility', 'hidden');
            }
            else {
                if(!$('.gg_row_to_sel').length) {
                    return false;
                }

                $(this).addClass('selected').attr('value', '<?php esc_attr_e('Deselect all', 'gg_ml') ?>');

                $('.gg_row_to_sel').each(function() {
                    $(this).addClass('gg_sel_row');
                    $(this).parent().parent().addClass('selected');
                });
                
                $('#gg_bulk_opt_wrap').css('visibility', 'visible');
            }
        });



        // bulk opt input toggle
        $(document).on('change', '#gg_bulk_opt', function() {
            if( $(this).val() == 'remove') {
                $('#gg_bulk_val, .lcslt-f-gg_bulk_folder_move').addClass('gg_displaynone');
            }
            else if( $(this).val() == 'folder_move') {
                $('#gg_bulk_val').val('').addClass('gg_displaynone');
                $('.lcslt-f-gg_bulk_folder_move').removeClass('gg_displaynone');
            }
            else {
                $('#gg_bulk_val').val('').removeClass('gg_displaynone');
                $('.lcslt-f-gg_bulk_folder_move').addClass('gg_displaynone');
            }
        });



        // perform bulk opt
        $(document).on('click', '#gg_bulk_perform', function() {
            if(is_deleting_folder) {
                return false;    
            }
            
            let type        = $('#gg_bulk_opt').val(),
                bulk_val    = $('#gg_bulk_val').val();

            // create chosen images filenames array for future operations
            let filenames = [];
            $('#gg_fb_builder li.selected').each(function() {
                filenames.push( $(this).data('filename') );        
            });
            
            
            // delete images
            if(type == 'remove') {
                delete_images(filenames);
            }
            
            
            // move images on a different folder
            else if(type == 'folder_move') {
                if(confirm("<?php esc_attr_e("Do you really want to move these files in a new folder? NB: files having the same name will not be moved", 'gg_ml') ?>")) {
                    return false;    
                }
                
                const skimmed = lock_imgs(filenames, 'move');
                if(!skimmed.length) {
                    lc_wp_popup_message('error', "<?php esc_attr_e("All selected images are currently busy", 'gg_ml') ?>");    
                    return false;    
                }
                is_operating_on_imgs++;

                // perform
                let data = {
                    action      : 'gg_lim_move_files',
                    nonce       : nonce,
                    old_f_name  : sel_folder,
                    new_f_name  : $('#gg_bulk_folder_move').val(),
                    files       : skimmed,
                };
                
                $.post(ajaxurl, data, function(response) {     
                    try {
                        const resp = JSON.parse(response);    

                        if(resp.status == 'success') {
                            
                            (resp.problems.length) ? 
                                lc_wp_popup_message('warning', "<?php esc_attr_e("Some images cannot be moved (please check for duplicates)", 'gg_ml') ?>") :
                                lc_wp_popup_message('success', "<?php esc_attr_e("Images moved successfully!", 'gg_ml') ?>"); 
                            
                            
                            $.each(filenames, function(i, filename) {
                                if($.inArray(filename, resp.problems) === -1) {
                                    $('#gg_fb_builder > li[data-filename="'+ filename +'"]').remove();    
                                }
                            });
                            
                            set_images_count();
                        }
                        else {
                            lc_wp_popup_message('error', resp.message);   
                        }
                    }
                    catch(e) {
                        console.error(e);
                        lc_wp_popup_message('error', "<?php esc_attr_e("Error moving images", 'gg_ml') ?>");    
                    }
                })
                .fail(function(e) {
                    console.error(e);
                    lc_wp_popup_message('error', "<?php esc_attr_e("Error moving images", 'gg_ml') ?>"); 
                })
                .always(function() {
                    is_operating_on_imgs--;
                    unlock_imgs(skimmed, 'move');
                });	
            }
            
                      
            // images data override
            else {
                if(type == 'author') {
                    $('#gg_fb_builder li.selected input[name="gg_item_author"]').val(bulk_val.replace(/\n/g, " "));
                }
                else if(type == 'title') {
                    $('#gg_fb_builder li.selected textarea[name="gg_item_title"]').val(bulk_val.replace(/\n/g, " "));
                }
                else if(type == 'descr') {
                    $('#gg_fb_builder li.selected textarea[name="gg_item_descr"]').val(bulk_val);
                }

                reset_selection();
            }
        });
        
        
        
        // reset items selection
        const reset_selection = function() {
            $('#gg_fb_builder .selected').removeClass('selected');
            $('input[name="gg_lim_select_all"]').removeClass('selected').attr('value', `<?php esc_attr_e('Select all', 'gg_ml') ?>`);
            $('#gg_bulk_opt_wrap').css('visibility', 'hidden');
        };
        
        
        
        // given filenames array, skim ones already busy for moving/deleting/saving operations
        const skim_busy_img = function(filenames) {
            let to_return = [];
            
            $.each(filenames, function(i, filename) {
                const $subj = $('#gg_fb_builder > li[data-filename="'+ filename +'"]');
                
                if($subj.length && !$subj.hasClass('gg_lim_moving_img') && !$subj.hasClass('gg_lim_deleting_img') && !$subj.hasClass('gg_lim_saving_img')) {
                    to_return.push( filename );    
                }
            });
            
            return to_return;
        };
        
        
        // unlock images fields for moving/deleting/saving operations (operation: move, update, delete)
        const unlock_imgs = function(filenames, operation) {
            let operation_class;
            
            switch(operation) {
                case 'move' : 
                    operation_class = 'gg_lim_moving_img'; 
                    break;     
                    
                case 'update' : 
                    operation_class = 'gg_lim_updating_img'; 
                    break;  
                    
                case 'delete' : 
                    operation_class = 'gg_lim_deleting_img'; 
                    break;  
            }  
            
            $.each(filenames, function(i, filename) {
                $('#gg_fb_builder > li[data-filename="'+ filename +'"]').removeClass(operation_class);  
                $('#gg_fb_builder > li[data-filename="'+ filename +'"]').find('input, textarea').removeAttr('disabled');
            });
        };
        
        
        // lock images fields for moving/deleting/saving operations (operation: move, updating, delete) - returns affected filenames
        const lock_imgs = function(filenames, operation) {
            const skimmed = skim_busy_img(filenames);
            let operation_class;
            
            switch(operation) {
                case 'move' : 
                    operation_class = 'gg_lim_moving_img'; 
                    break;     
                    
                case 'updating' : 
                    operation_class = 'gg_lim_updating_img'; 
                    break;  
                    
                case 'delete' : 
                    operation_class = 'gg_lim_deleting_img'; 
                    break;  
            }
            
            $.each(skimmed, function(i, filename) {
                $('#gg_fb_builder > li[data-filename="'+ filename +'"]').addClass(operation_class);
                $('#gg_fb_builder > li[data-filename="'+ filename +'"]').find('input, textarea').prop('disabled', 'disabled');
            });
            
            return skimmed;
        };

        
        
        
        /////////////////////////////////////////////////////////////////
        // UPLOADER
        
        
        $('.gg_lim_uploaders').fileupload({
            url 		: ajaxurl,
            paramName 	: 'gg_lim_image',
            dropZone 	: $('#gg_lim_dropzone'),

            // called when a file is added to the queue;
            add : function (e, data) {
                if(is_deleting_folder) {
                    return false;    
                }
                
                data.formData = {
                    action		: 'gg_lim_upload',
                    f_name	    : sel_folder,
                    nonce		: nonce
                };
                let file = data.files[0];

                const $uploader_box = $(
                '<li class="gg_lim_uploading">' +
                    '<div class="gg_lim_uploader_filename" title="'+ data.files[0].name +'">'+ data.files[0].name +'</div>' +
                    '<div class="gg_lim_uploader_response">' +
                        '<em>'+ format_filesize(file.size) +'</em>' +
                        '<span class="gg_lim_uploader_percentage">0%</em>' +
                    '</div>' +

                    '<svg class="gg_lim_uploader_progress gg_lim_upb" viewbox="0 0 100 100">' +
                         '<circle cx="50" cy="50" r="40" />' + 
                    '</svg>' +
                    '<svg class="gg_lim_uploader_progress" viewbox="0 0 100 100">' +
                         '<circle cx="50" cy="50" r="40" />' + 
                    '</svg>' +
                    '<span class="dashicons dashicons-no-alt gg_lim_del_upl"></span>' +
                '</li>');

                // append uploader block
                data.context = $('.gg_lim_uploads_list').append($uploader_box);
                data.uplBox = $uploader_box;

                // file size validation
                if (file.size > <?php echo absint(wp_max_upload_size()) ?>) {
                    $uploader_box.find('.gg_lim_uploader_response').html("<?php esc_html_e('File size exceeds the limit', 'gg_ml') ?>");
                    $uploader_box.addClass('gg_upload_error');
                }

                // upload 
                else {
                    var jqXHR = data.submit();
                }


                // Listen for clicks on the cancel icon to abort or remove a bad file
                $uploader_box.find('.gg_lim_del_upl').on('click', function() {

                    if(!$uploader_box.hasClass('gg_lim_upload_error') && !$uploader_box.hasClass('gg_lim_upload_success')){
                        jqXHR.abort();
                    }

                    $uploader_box.addClass('gg_lim_nodisplay_upl_box');
                    setTimeout(function() {
                        $uploader_box.remove();
                    }, 330);
                });
        
                
                // disable folder choice
                $folder_sel_dd.prop('disabled', 'disabled');
                lc_select_for_folder_dd();
            },

            progress : function(e, data){
                var percentage = parseInt(data.loaded / data.total * 100, 10);

                data.uplBox.find('.gg_lim_uploader_percentage').html(percentage+'%');
                data.uplBox.find('.gg_lim_uploader_progress').gg_circle_loader(percentage);

                if(percentage == 100) {
                    data.uplBox.addClass('gg_lim_waiting_uploader');	
                }
            },

            done : function (e, data) {	
                try {
                    var resp = JSON.parse(data.result);
                } catch (e) {
                    var resp = {
                        status 	: 'error',
                        txt		: data.result
                    };
                }

                data.uplBox.removeClass('gg_lim_waiting_uploader');

                if(resp.status == 'error') {
                    data.uplBox.addClass('gg_lim_upload_error');
                    data.uplBox.find('.gg_lim_uploader_response').html(resp.message);
                }
                else {
                    data.uplBox.addClass('gg_lim_upload_success');

                    data.uplBox.find('.gg_lim_del_upl').remove();
                    data.uplBox.find('.gg_lim_uploader_response').html("<?php esc_html_e("Upload completed", 'gg_ml') ?>");

                    // append and update folder files count
                    if(!$('#gg_fb_builder').length) {
                        $('#gg_lim_files_wrap').html('<ul id="gg_fb_builder"></ul>');   
                    }
                    
                    append_image(resp.img_data, true);
                    
                    after_appended_images();
                    set_images_count();
                    read_imgs_data();
                    
                    // final operations
                    setTimeout(function() {
                        data.uplBox.addClass('gg_lim_nodisplay_upl_box');
                        
                        setTimeout(function() {
                            data.uplBox.remove();
                        }, 330);
                    }, 500);
                }
            },

            fail : function(e, data){
                data.uplBox.removeClass('gg_lim_waiting_uploader').addClass('gg_lim_upload_error');
                data.uplBox.find('.gg_lim_uploader_response').html("<?php esc_html_e("Upload failed", 'gg_ml') ?>");

                console.error(data.errorThrown); // debug
            },
                
            always : function() {
                // if all files are processed -  enable folder selection
                if(!$('.gg_lim_uploading').not('.gg_lim_upload_error, .gg_lim_upload_success').length) {
                    $folder_sel_dd.removeAttr('disabled');
                    lc_select_for_folder_dd();
                }        
            }
        });


        /* circular loader - setting SVG value basing on the integer percentage  */
        $.fn.gg_circle_loader = function(percentage) {

            var $round = this,
            roundRadius = $round.find('circle').attr('r'),
            roundCircum = 2 * roundRadius * Math.PI,
            roundDraw = parseInt(percentage, 10) * roundCircum / 100;

            $round.css('stroke-dasharray', roundDraw  + ' 999');
        };
    
    

        // launch upload box emulating a click on the true upload btn
        $(document).on('click', 'input[name="gg_lim_upload_btn"], #gg_lim_no_imgs_found', function() {
            $('input[name="gg_lim_upl_input"]').trigger('click');
        });



        // 	show drag N drop message on drag over
        $('#gg_lim_dropzone').on('dragover dragenter', function() {
            $('#gg_lim_files_wrap').addClass('gg_lim_is_dragging');
        })
        .on('dragleave dragend drop click', function() {
            $('#gg_lim_files_wrap').removeClass('gg_lim_is_dragging');
        })


        // Prevent the default action when a file is dropped on the window
        $(document).on('drop dragover', function (e) {
            e.preventDefault();
        });
    });
    
    
    
    
    
    
    /////////////////////////////////////////////////////////////////
    // EXTRA FUNCTIONS
    
    
    // get the thumbs maker base depending on the image URL/path
    const get_thumb_maker_base = function(img_url) {
        return (/\.(jpe?g|png|gif)$/i.test(img_url)) ? thumb_base_script : ewpt_url;  
    };
    
    
    
    // given the bytes value, returns the human readable format
    const format_filesize = function(bytes) {
        if (typeof bytes !== 'number') {
            return '';
        }
        else if (bytes >= 1024000000) {
            return (bytes / 1024000000).toFixed(1) + ' GB';
        }
        else if (bytes >= 1024000) {
            return (bytes / 1024000).toFixed(1) + ' MB';
        }
        else if (bytes >= 1024) {
            return (bytes / 1024).toFixed(1) + ' KB';
        }
        else {
            return bytes + ' bytes';	
        }
    };

    
    
    // set folder images count
    const set_images_count = function() {
        const count = parseInt($('#gg_fb_builder > li').length, 10); 
        $('.gg_lim_imgs_counter span').text(count);    
        
        if(!count) {
            $('.gg_lim_imgs_counter').addClass('gg_displaynone');
            $('#gg_lim_files_wrap').html(no_img_code);        
        }
    };
    
    

    // auto-resizing textarea
    $.fn.gg_auto_h_textarea = function(strip_newlines) {
        $(this).each(function() {
            var min_val = ($(this).hasClass('gg_item_descr')) ? 50 : 20;
            $( this ).height(min_val).height( $( this )[ 0 ].scrollHeight );

            $( this ).off("input").on("input", function(){

                if(typeof(strip_newlines) != 'undefined') {
                    $(this).val( $(this).val().replace("\n", "") ); // strip new lines
                }	
                $( this ).height(min_val).height( $( this )[ 0 ].scrollHeight );
            } );
        });
    };
    
    
})(jQuery);    
</script>