<?php
// WRAPPING UP BUILDER BOXES


// register boxes
function gg_gall_builder_metaboxes() {
	global $post;
    add_meta_box('submitdiv', esc_html__('Publish', 'gg_ml'), 'post_submit_meta_box', 'gg_galleries', 'side', 'high');


	// SIDEBOXES
	include_once('side_boxes.php');
	add_meta_box('gg_gb_gallery_type', esc_html__('Main images source', 'gg_ml'), 'gg_gb_gallery_type', 'gg_galleries', 'side', 'core');
	
	add_meta_box('gg_gb_main_settings', esc_html__('Main Settings', 'gg_ml') .'<span class="dashicons dashicons-info gg_gb_meta_infobox" title="'. esc_attr__('Use "as default" option or leave fields empty to use global setup', 'gg_ml') .'"></span>', 'gg_gb_main_settings', 'gg_galleries', 'side', 'core');
	
	add_meta_box('gg_gb_sitemap', esc_html__('Page URL for sitemap', 'gg_ml') .'<span class="dashicons dashicons-info gg_gb_meta_infobox" title="'. esc_attr__('Insert the page URL where the gallery will be placed', 'gg_ml') .'"></span>', 'gg_gb_sitemap', 'gg_galleries', 'side', 'low');

	if(is_object($post) && gg_coll_static::get_gall_first_img($post->ID, 'img') && filter_var(get_option('gg_watermark_img'), FILTER_VALIDATE_URL)) {
		add_meta_box('gg_gb_wmark_cache', esc_html__('Watermark Cache', 'gg_ml'), 'gg_gb_wmark_cache', 'gg_galleries', 'side', 'low');
	}

    
	// BUILDER
	add_meta_box('gg_specific_settings', esc_html__('Specific Settings', 'gg_ml'), 'gg_specific_settings', 'gg_galleries', 'normal', 'default');
	add_meta_box('gg_gallery_builder', esc_html__('Gallery Builder', 'gg_ml'), 'gg_gallery_builder', 'gg_galleries', 'normal', 'default');
}
add_action('admin_init', 'gg_gall_builder_metaboxes');



// SAVE
include_once('ajax.php');
include_once('save.php');








//////////////////////////
// GALLERY SPECIFIC SETTINGS
function gg_specific_settings() {
	include_once(GG_DIR . '/classes/gg_builder_sources_hub.php');
	global $post;
    
    dike_lc('lcweb', 'gg', true);
	?>
    <div class="gg_mainbox_meta">
    	<div id="gg_settings_wrap">
			<?php
            $hub = new gg_builder_hub($post->ID, get_post_meta($post->ID, 'gg_type', true) );
            echo gg_static::wp_kses_ext($hub->spec_opt());
            ?>
        </div>
    </div>
    <?php
}







//////////////////////////
// GALLERY BUILDER
function gg_gallery_builder() {
	include_once(GG_DIR . '/classes/gg_connections_hub.php');
    
	global $post;
	$conn_hub = new gg_connection_hub($post->ID);
	
	$type 		= get_post_meta($post->ID, 'gg_type', true);
	$autopop 	= get_post_meta($post->ID, 'gg_autopop', true);
    $rows_layout= (gg_static::builder_layout_selected('rows')) ? 'gg_rows_builder_layout' : '';
	?>
    
    <div class="gg_mainbox_meta">
    	<div id="gg_builder_wrap" class="<?php echo esc_attr($rows_layout) ?>">
		<?php
		
		// MANUAL GALLERY
		if($autopop != '1') {
			$gallery = gg_gall_static::get_data($post->ID);

			// picked images gallery
			if(empty($gallery)) {
				echo '<div class="gg_manual_builder_no_img">.. '. esc_attr__('no images added yet', 'gg_ml') .' ..</div>';
			}
			else {
				echo '
				<table class="widefat gg_table gg_metabox_table">
				  <thead>
				  <tr>
					<th>
						<div id="gg_bulk_opt_wrap" class="gg_displaynone"></div>
					</th>
				  </tr>
				  </thead>
				</table>
				<ul id="gg_fb_builder">';

				if(!is_array($gallery)) {
					$gallery = array();
				}
				foreach($gallery as $image) {
					$tags 		= (isset($image['tags'])) ? $image['tags'] : '';
					$link_opt 	= (isset($image['link_opt'])) ? $image['link_opt'] : 'none';
					$link_val 	= (isset($image['link'])) ? $image['link'] : '';

					$img_full_src = gg_static::img_src_on_type($image['img_src'], $type);
					$img_full_url = gg_static::img_url_on_type($image['img_src'], $type);
                    
					if(in_array($type, array('wp', 'wp_cat', 'cpt_tax', 'rml'))) { // use WP thumbs					
						$thumb_data = wp_get_attachment_image_src($image['img_src'], array(400, 0));
						$thumb = (!get_option('gg_use_admin_thumbs')) ? $thumb_data[0] : gg_static::thumb_src($image['img_src'], $width = 400, false, 85, $alignment = $image['thumb'], 3);
					} 
					else {
						$thumb = (!get_option('gg_use_admin_thumbs')) ? $img_full_url : gg_static::thumb_src($img_full_src, $width = 400, false, 85, $alignment = $image['thumb'], 3);
					}
					
                    echo gg_static::wp_kses_ext(str_replace(
                        array(
                            '%%IMG_ID%%',
                            '%%THUMB_CENTER%%', 
                            '%%THUMB-URL%%', 
                            '%%FULL-URL%%', 
                            '%%IMG_SRC%%', 
                            '%%AUTHOR%%', 
                            '%%TITLE%%', 
                            '%%DESCR%%', 
                            '%%TAGS%%'
                        ),
                        array(
                            ($type == 'g_drive') ? md5(gg_gall_static::gdrive_img_url_trick($img_full_src)) : md5($img_full_url),
                            esc_attr($image['thumb']),
                            esc_attr(gg_gall_static::gdrive_img_url_trick($thumb)), 
                            esc_attr($img_full_url), 
                            esc_attr($image['img_src']),
                            esc_attr($image['author']),
                            esc_attr($image['title']),
                            esc_textarea($image['descr']),
                            esc_textarea($tags),
                        ),
                        gg_gall_static::manual_image_code_block($link_opt, $link_val)
                    ));
				}

				echo '</ul>';
			}
		}



		// AUTO POPULATED GALLERY
		else {
			$gallery = gg_gall_static::get_data($post->ID, true);

			if(empty($gallery)) {
				echo '<em>'. esc_html__('No images found', 'gg_ml') .' .. </em>';
			}
			else {
				echo '<ul id="gg_fb_builder" class="gg_autopop_gallery">';

				foreach($gallery as $img) {
					$img_full_src = gg_static::img_src_on_type($img['img_src'], $type);
					$img_full_url = gg_static::img_url_on_type($img['img_src'], $type);

					if(in_array($type, array('wp', 'wp_cat', 'cpt_tax', 'rml'))) { // use WP thumbs
						$thumb_data = wp_get_attachment_image_src($img['img_src'], array(400, false));
						$thumb = $thumb_data[0];
					} else {
						$thumb = (!get_option('gg_use_admin_thumbs')) ? $img_full_url : gg_static::thumb_src($img_full_src, $width = 400, false, 'c', 3);
					}
					
					echo '<li>
						<div class="gg_builder_img_wrap">
							<figure style="background-image: url('. esc_attr(gg_gall_static::gdrive_img_url_trick($thumb)) .');" class="gg_builder_img" data-fullurl="'. esc_attr($img_full_url) .'" title="'. esc_attr__("click to enlarge", 'gg_ml') .'"></figure>
						</div>
						<div class="gg_img_texts">
							<table>
							  <tr>
								<td class="gg_img_data_icon"><span class="dashicons dashicons-admin-users" title="'. esc_attr__('photo author', 'gg_ml') .'"></span></td>
								<td>'. esc_attr($img['author']) .'</td>
							  </tr>
							  <tr>
								<td class="gg_img_data_icon"><span class="dashicons dashicons-editor-textcolor" title="'. esc_attr__('photo title', 'gg_ml') .'"></span></td>
								<td>'. esc_textarea($img['title']) .'</td>
							  </tr>
							  <tr>
								<td class="gg_img_data_icon"><span class="dashicons dashicons-editor-alignleft" title="'. esc_attr__('photo description', 'gg_ml') .'"></span></td>
								<td>'. esc_textarea($img['descr']) .'</td>
							  </tr>';
				  
                              if(in_array($type, array('gg_album', 'ngg')) && isset($img['tags'])) {
                                echo '
                                <tr>
                                  <td class="gg_img_data_icon">
                                    <span class="dashicons dashicons-tag" title="'. esc_attr__('photo tags - comma split', 'gg_ml') .'"></span>
                                  </td>
                                  <td>'. esc_html($img['tags']) .'</td>
                                </tr>';
                              }
                    
							  if(($type == 'wp_cat' || $type == 'cpt_tax') && isset($img['link']) && !empty($img['link'])) {
								echo '
								<tr>
									<td class="gg_img_data_icon"><span class="dashicons dashicons-admin-links" title="'. esc_attr__('photo link', 'gg_ml') .'"></span></td>
									<td><a href="'. esc_attr($img['link']) .'" target="_blank">'. esc_html($img['link']) .'</a></td>
								</tr>';
							  }
							
							echo '
							</table>
						</div>
					</li>';
				}

				echo '</ul>';
			}
		}
        ?>
        </div>
    </div>




    <?php // hidden code to set thumbs center ?>
    <div id="gg_set_thumb_center" class="gg_displaynone">
    	<h4><?php esc_html_e('Select thumbnail center clicking on a cell', 'gg_ml') ?>:</h4>
        <table class="gg_sel_thumb_center">
            <tr>
                <td id="gg_tl"></td>
                <td id="gg_t"></td>
                <td id="gg_tr"></td>
            </tr>
            <tr>
                <td id="gg_l"></td>
                <td id="gg_c"></td>
                <td id="gg_r"></td>
            </tr>
            <tr>
                <td id="gg_bl"></td>
                <td id="gg_b"></td>
                <td id="gg_br"></td>
            </tr>
        </table>
    </div>



 	<?php // hidden bulk cmd code ?>
	<div id="gg_bulk_cmd_code_wrap" class="gg_displaynone">
    	<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="thumb"><?php esc_html_e('Set thumbnails center', 'gg_ml') ?></option>
        </select>
        
        <textarea name="gg_bulk_val" id="gg_bulk_val" autocomplete="off" class="gg_displaynone"></textarea>
        
        <select name="gg_bulk_thumb_val" id="gg_bulk_thumb_val" autocomplete="off" class="gg_displaynone">
            <option value="tl"><?php esc_html_e('Top-left', 'gg_ml') ?></option>
            <option value="t"><?php esc_html_e('Top', 'gg_ml') ?></option>
            <option value="tr"><?php esc_html_e('Top-right', 'gg_ml') ?></option>
            <option value="l"><?php esc_html_e('Left', 'gg_ml') ?></option>
            <option value="c"><?php esc_html_e('Center', 'gg_ml') ?></option>
            <option value="r"><?php esc_html_e('Right', 'gg_ml') ?></option>
            <option value="bl"><?php esc_html_e('Bottom-left', 'gg_ml') ?></option>
            <option value="b"><?php esc_html_e('Bottom', 'gg_ml') ?></option>
            <option value="br"><?php esc_html_e('Bottom-right', 'gg_ml') ?></option>
        </select>

        <input type="button" value="<?php esc_attr_e('Apply', 'gg_ml') ?>" id="gg_bulk_perform" class="button-secondary" />
    </div>



    <script type="text/javascript">
    (function($) {
	   "use strict";    
        
        /*** VARS ***/
        const gg_nonce = '<?php echo esc_js(wp_create_nonce('gg_gall_builder')) ?>';
        var gg_erase_past = false; // flag reporting whether a gallery cleaning is needed (eg. changing source)


        // First init - gallery settings & builder load
        const gid 		    = <?php echo absint($post->ID); ?>,
              TT_url 		= '<?php echo esc_js(GG_TT_URL) ?>',
              EWPT_url 	    = '<?php echo esc_js(GG_EWPT_URL) ?>',
              gg_use_tt 	= <?php echo (get_option('gg_use_timthumb')) ? 'true' : 'false'; ?>,
              thumbs_on_admin = <?php echo (get_option('gg_use_admin_thumbs')) ? 'true' : 'false'; ?>;
        
        // encapsulate ajax objects to abort them in case and save server resources 
        var spec_opt_ajax = false;
        var img_picker_ajax = false;

        // connection data
        var gg_type 	= false;
        var gg_username = false;
        var gg_psw 		= false;
        
        // images picker
        var gg_img_pp = 26;
        var gg_sel_img = [];

        var gg_saved_manual_gallery = false;
        var gg_sort_mode_on = false;
        
        // images uploader
        let gg_TB = 0;
        var file_frame = false;
        
        // thumbs center - temporary store managed image
        let $thumb_center_subj = false;
        
        
        
        
        /*** ON PAGE'S READY ***/
        jQuery(document).ready(function($) {
               
            // initialize engine
            gg_gallery_init(true);
            gg_count_gall_images();
            gg_sortable_images();
            gg_read_imgs_data();          
            
            // auto-resizing textarea
            $('textarea.gg_item_title').gg_auto_h_textarea(true);
            $('textarea.gg_item_descr').gg_auto_h_textarea();
            $('textarea.gg_item_tags').gg_auto_h_textarea(true);
            $('textarea#gg_username').gg_auto_h_textarea(true);
            $('textarea#gg_bulk_val').gg_auto_h_textarea();
            
            gg_live_lc_switch();
            gg_live_lc_select();
            
            
            
            //////////////////////////////////////////////////////////////////////////////////
            // SOURCE CONNECTION + IMAGES PICKER
            
            // update on gallery type change
            $(document).on('change', '#gg_type_dd', function(e) {
                if($('#gg_fb_builder > li').length && !confirm(`<?php esc_html_e('Current gallery will be erased. Continue?', 'gg_ml') ?>`)) {
                    return false;	
                }

                const gg_new_type = $(this).val();

                gg_erase_past = 1;
                gg_reset_gallery();

                
                // DEC 2024 - google drive re-connect button - normalize on change
                if($('#gg_handle_user_btn').length && $('#gg_handle_user_btn').hasClass('gg_gdrive_reconnect')) {
                    console.log('test');
                    $('#gg_handle_user_btn').removeClass('gg_gdrive_reconnect').val(`<?php esc_html_e('Connect', 'gg_ml') ?>`);
                }
                
                
                // init gallery if source doesn't require config
                if( $.inArray(gg_new_type, ['wp', 'wp_cat', 'cpt_tax', 'gg_album', 'rml', 'ngg']) !== -1 ) {
                    gg_gallery_init();

                    $('#gg_connect_id_wrap, #gg_username_wrap, #gg_psw_wrap, #gg_handle_user_btn').addClass('gg_displaynone');
                    return false;
                }


                // connection hub toggle
                if($.inArray(gg_new_type, ['<?php echo esc_html(implode("','", $conn_hub->to_consider)) ?>']) !== -1) {
                    $('#gg_connect_id_wrap').removeClass('gg_displaynone');
                    gg_reload_conn_hub_dd();	
                } else {
                    $('#gg_connect_id_wrap').addClass('gg_displaynone');
                }

                ////////////////////////////////////////////


                // change username label
                switch(gg_new_type) {
                    case 'flickr'	: $('#gg_username_wrap label').text(`<?php esc_html_e('Set / Profile / Tag URL', 'gg_ml') ?>`); break;
                    case 'pinterest': $('#gg_username_wrap label').text(`<?php esc_html_e('Board URL', 'gg_ml') ?>`); break;
                    case 'instagram': $('#gg_username_wrap label').text(`<?php esc_html_e('Profile URL', 'gg_ml') ?>`); break;
                    case 'g_drive'	: $('#gg_username_wrap label').text(`<?php esc_html_e('Public folder URL', 'gg_ml') ?>`); break;
                    case 'twitter'	: $('#gg_username_wrap label').text(`<?php esc_html_e('@Username or #hashtag', 'gg_ml') ?>`); break;
                    case 'tumblr'	: $('#gg_username_wrap label').text(`<?php esc_html_e('Blog URL', 'gg_ml') ?>`); break;
                    case 'rss'		: $('#gg_username_wrap label').text(`<?php esc_html_e('Feed URL', 'gg_ml') ?>`); break;
                    default			: $('#gg_username_wrap label').text(`<?php esc_html_e('Username', 'gg_ml') ?>`); break;
                }
                
                
                //// gallery type auth data toggle
                // reset fields
                if(gg_type != gg_new_type) {
                    $('#gg_username_wrap input, #gg_psw_wrap input').val('');
                }


                // username field visibility
                if( $.inArray(gg_new_type, ['<?php echo esc_html(implode("','", array_merge($conn_hub->to_consider, array('wp', 'wp_cat', 'cpt_tax', 'gg_album', 'rml', 'ngg')))) ?>']) === -1 ) {
                    $('#gg_username_wrap').removeClass('gg_displaynone');
                } else {
                    $('#gg_username_wrap').addClass('gg_displaynone');
                }


                // connect button visibility
                if( $.inArray(gg_new_type, ['wp', 'wp_cat', 'cpt_tax', 'gg_album', 'rml', 'ngg']) === -1 ) {
                    $('#gg_handle_user_btn').removeClass('gg_displaynone');
                } else {
                    $('#gg_handle_user_btn').addClass('gg_displaynone');
                }
            });
            
            
            
            // start on "connect" button click
            $(document).on('click', '#gg_handle_user_btn', function() {
                if($(this).hasClass('gg_gdrive_reconnect')) {
                    gg_gallery_init(); 
                }
                else if(!$('.gg_builder_img').length || ( $('.gg_builder_img').length && confirm(`<?php esc_html_e('Current gallery will be erased. Continue?', 'gg_ml') ?>`) ) ) {

                    gg_erase_past = 1;
                    gg_reset_gallery();
                    gg_gallery_init();
                }
            });
            
            
            
            // reload on category/album change - ask for confirmation
            $(document).on('change', '#gg_wp_cat, #gg_cpt_tax_term, #gg_album, #gg_gdrive_album, #gg_onedrive_album, #gg_fb_album, #gg_rml_folder, #gg_ngg_gallery', function() {
                if( !$('.gg_builder_img').length || confirm(`<?php esc_html_e('Current gallery will be erased. Continue?', 'gg_ml') ?>`)) {
                    if( $('#gg_autopop input').is(':checked') ) {
                        gg_erase_past = 1;
                        gg_autopop_make_cache();
                    }
                    else {
                        gg_load_img_picker(1);
                        $('#gg_builder_wrap').html(`<div class="gg_manual_builder_no_img">.. <?php esc_html_e('no images added yet', 'gg_ml') ?> ..</div>`);
                        $('#gg_builder_wrap h2 small').empty();
                    }
                } 
                else {
                    return false;
                }
            });



            // CPT taxonomy - change subject and reload terms erasing the gallery
            $(document).on('change', '#gg_cpt_tax', function() {
                if($('.gg_builder_img').length && !confirm(`<?php esc_html_e('Current gallery will be erased. Continue?', 'gg_ml') ?>`)) {
                    return false;    
                }

                var data = {
                    action	: 'gg_cpt_tax_change',
                    cpt_tax	: $('#gg_cpt_tax').val(),
                    nonce	: gg_nonce,
                };

                $('#gg_ctp_tax_term_wrap').html('<div class="gg_spinner"></div>');

                $.post(ajaxurl, data, function(response) {
                    $('#gg_ctp_tax_term_wrap').html(response);
                    gg_live_lc_select();

                    if( $('#gg_autopop input').is(':checked') ) {
                        gg_erase_past = 1;
                        gg_autopop_make_cache();
                    }
                    else {
                        gg_load_img_picker(1);
                        $('#gg_builder_wrap').html(`<em><?php esc_html_e('Select WP images or the images source', 'gg_ml') ?></em>`);
                    }
                })
                .fail(function(e) {
                    if(e.status) {
                        console.error(e);
                        lc_wp_popup_message('error', `<?php esc_html_e("Error performing the operation", 'gg_ml') ?>`);
                    }
                });
            });
            
            
            
            // change imges picker's page
            $(document).on('click', '.gg_img_pick_back, .gg_img_pick_next', function() {
                var page = $(this).attr('id').substr(4);
                gg_load_img_picker(page);
            });
            
            
            
            // sanitize entered value for numeric fields
            let gg_num_field_check_tout = false;
            $(document).on('keyup', '#gg_main_settings .gg_sidebox_meta input, #gg_max_images, #gg_img_pick_pp', function(e) {
                const $subj = $(this);
                
                let val = parseInt($subj.val(), 10);
                if(val < 1) {
                    val = 1;
                }

                if(gg_num_field_check_tout) {
                    clearTimeout(gg_num_field_check_tout);	
                }

                gg_num_field_check_tout = setTimeout(function() {
                    $subj.val(val);
                    
                    if($subj.is('#gg_img_pick_pp')) {
                        gg_img_pp = val;
                        gg_load_img_picker(1);
                    }
                }, 900);
            });
            
            
            
            // re-fetch images on search or enter button
            $(document).on('click', '.gg_clear_img_search', function() {
                $('.gg_img_search').val('').trigger('keyup');
            });
            
            let gg_img_search_tout = false;
            $(document).on('keyup keydown', '.gg_img_search', function(e) {
                
               if(e.keyCode == 13) {
                    e.stopPropagation();
                    e.preventDefault();
                    return false;
                } 
            });
            
            $(document).on('keyup', '.gg_img_search', function(e) {
                // fetch live
                if(gg_img_search_tout) {
                    clearTimeout(gg_img_search_tout);
                }
                const $this = $(this);
    
                gg_img_search_tout = setTimeout(function() {
                    const prev_vis = $('.gg_clear_img_search').css('visibility'),
                          vis = ($.trim($this.val()).length > 2) ? 'visible' : 'hidden';
                    
                    $('.gg_clear_img_search').css('visibility', vis); 
                    
                    if(prev_vis != 'hidden' || (prev_vis == 'hidden' && prev_vis != vis)) {
                        gg_load_img_picker(1);
                    }
                }, 400);
            });



            // images picker - "select all" action
            $(document).on('click', '.gg_sel_all_btn', function() {
                $('#gg_img_picker ul li').not('.gg_img_inserted').each(function() {
                    $(this).addClass('gg_img_sel');
                });
                gg_man_img_array();
            });



            // images picker - single img selection with click
            $(document).on('click', '#gg_img_picker > ul li:not(.gg_img_inserted) figure', function(e) {
                if($(e.target).hasClass('gg_zoom_img')) {
                    return true;    
                }

                $(this).parent().toggleClass('gg_img_sel');
                gg_man_img_array();
            });
            
            
            
            // open uploader lightbox and hide tabs
            $(document).on('click', '.gg_TB', function(e) {

                // If the media frame already exists, reopen it.
                if(file_frame){
                    file_frame.open();
                    return;
                }

                // Create the media frame
                file_frame = wp.media.frames.file_frame = wp.media({
                    title: `<?php esc_html_e('Global Gallery - images management', 'gg_ml') ?>`,
                    button: {
                    text: `<?php esc_html_e('Back to builder', 'gg_ml') ?>`,
                    },
                    library : {type : 'image'},
                    multiple: false
                });

                // if closed or selected - refresh picker
                file_frame.on('close select', function() {
                    gg_load_img_picker(1);
                    clearInterval(bb_builder_lb_intval);
                });

                // turn button into active in any case and simulate closing
                file_frame.on('open', function() {
                    bb_builder_lb_intval = setInterval(function() {
                        $('.media-button-select').removeAttr('disabled').addClass('bb_builder_lb_btn');
                    }, 10)
                });
                $(document).on('click', '.bb_builder_lb_btn', function() {
                    file_frame.close();
                });

                file_frame.open();
            });
            
            
            
            
            //////////////////////////////////////////////////////////////////////////////////
            // GALLERY MANAGEMENT
            
            // add selected images to the gallery
            $(document).on('click', '#gg_add_img', function() {
                if(!$('#gg_builder_wrap > ul').length ) {
                    $('#gg_builder_wrap').html(`
                        <table class="widefat gg_table gg_metabox_table">
                            <thead>
                                <tr>
                                    <th>
                                        <div id="gg_bulk_opt_wrap" class="gg_displaynone"></div>
                                    </th>
                                </tr>
                            </thead>
                        </table>
                        <ul id="gg_fb_builder"></ul>`
                    );
                }

                // revert array to add in right order
                gg_sel_img.reverse();

                $.each(gg_sel_img, function(index, img_id) {
                    const $img = $('.gg_gb_ip_img[data-id="'+ img_id +'"]');
                    
                    var img_url = $img.data('fullurl');
                    var img_full_src = encodeURIComponent( $img.data('img_full_src') );
                    var img_src = $img.data('img_src');

                    var author = $img.data('author');
                    var title  = $img.attr('title');
                    var descr  = $img.attr('alt').replace(/<br\s*\/?>/gi, '\n');
                    var tags   = ($img[0].hasAttribute('data-tags')) ? $img.data('tags') : ''; 

                    var base_script = (gg_use_tt) ? TT_url : EWPT_url;
                    
                    let thumb_url = img_url;
                    if(thumbs_on_admin) {
                        const thumb_src_param = (gg_use_tt || !Number.isInteger(img_src)) ? img_full_src : img_src;
                        thumb_url = base_script +'?src='+ thumb_src_param +'&w=400&h=&q=85&rs=3&zc=3'; 
                    }
                                                                        
                    var new_tr = `<?php echo gg_gall_static::manual_image_code_block() ?>`;
                    new_tr = new_tr
                                .replace('%%IMG_ID%%', img_id)
                                .replace('%%THUMB_CENTER%%', 'c') 
                                .replace('%%THUMB-URL%%', gdrive_img_url_trick(thumb_url)) 
                                .replace('%%FULL-URL%%', img_url) 
                                .replace('%%IMG_SRC%%', img_src)
                                .replace('%%AUTHOR%%', author)
                                .replace('%%TITLE%%', title)
                                .replace('%%DESCR%%', descr)
                                .replace('%%TAGS%%', tags);

                    $('#gg_fb_builder').prepend( new_tr );

                    // has got link? add it!
                    if($img.attr('link')) {
                        $('#gg_fb_builder li[data-id="'+ img_id +'"] .gg_linking_dd option[value="custom"]').attr('selected', 'selected');	
                        $('#gg_fb_builder li[data-id="'+ img_id +'"] .gg_linking_dd').trigger('change');
                        $('#gg_fb_builder li[data-id="'+ img_id +'"] .gg_link_field').val( $img.data('link') );
                    }
                });

                $('#gg_img_picker ul li.gg_img_sel').removeClass('gg_img_sel');
                $('#gg_img_picker ul li.selected').removeClass('selected');
                $('#gg_add_img').addClass('gg_displaynone');

                gg_sel_picker_img_status();
                gg_sortable_images();
                gg_count_gall_images();
                gg_read_imgs_data();

                $('textarea.gg_item_title').gg_auto_h_textarea(true);
                $('textarea.gg_item_descr').gg_auto_h_textarea();
                $('textarea.gg_item_tags').gg_auto_h_textarea(true);
            });
            
            
            
            // linking management
            $(document).on('change', '.gg_img_texts select.gg_linking_dd', function() {
                var link_opt = $(this).val();

                if(link_opt == 'page') {
                    var link_field = `<?php echo gg_static::wp_kses_ext(gg_static::link_field('page')) ?>`;
                }
                else if(link_opt == 'custom') {
                    var link_field = `<?php echo gg_static::wp_kses_ext(gg_static::link_field('custom')) ?>`;
                }
                else {
                    var link_field = `<?php echo gg_static::wp_kses_ext(gg_static::link_field('none')) ?>`;
                }

                $(this).parent().find('.gg_link_wrap').html(link_field);
            });
            


            // remove image
            $(document).on('click', '.gg_cmd_bar .gg_del_row', function() {
                if(confirm(`<?php esc_html_e('Remove image?', 'gg_ml') ?>`)) {
                    $(this).parents('li').first().remove();
                    
                    gg_sel_picker_img_status();
                    gg_count_gall_images();
                    
                    if(!$('#gg_fb_builder li').length) {
                        $('#gg_builder_wrap').html(`<div class="gg_manual_builder_no_img">.. <?php esc_html_e('no images added yet', 'gg_ml') ?> ..</div>`);
                        
                        if($('#gg_select_all_img').hasClass('selected')) {
                            $('#gg_select_all_img').trigger('mousedown');
                        }
                    }
                }
            });
            
            
            
            // open thumbnail's center wizard
            $(document).on('click', '.gg_sel_thumb', function() {
                $thumb_center_subj = $(this).parents('li');

                var thumb_center = $(this).find('input').val();
                if(!thumb_center.length) {
                    thumb_center = 'c';
                }

                var gg_H = 417;
                var gg_W = 480;
                tb_show( 'Thumbnail center', '#TB_inline?height='+ gg_H +'&width='+ gg_W +'&inlineId=gg_set_thumb_center');

                $('#TB_ajaxContent .gg_sel_thumb_center td').removeClass('thumb_center');
                $('#TB_ajaxContent .gg_sel_thumb_center #gg_'+thumb_center).addClass('thumb_center');

                $('#TB_window').css("height", gg_H);
                $('#TB_window').css("width", gg_W);

                $('#TB_window').css("top", (($(window).height() - gg_H) / 4) + 'px');
                $('#TB_window').css("left", (($(window).width() - gg_W) / 4) + 'px');
                $('#TB_window').css("margin-top", (($(window).height() - gg_H) / 4) + 'px');
                $('#TB_window').css("margin-left", (($(window).width() - gg_W) / 4) + 'px');

            });



            // set the thumbnail center
            $(document).on('click', '#TB_ajaxContent .gg_sel_thumb_center td', function() {
                var new_center = $(this).attr('id').substr(3);

                $('#TB_ajaxContent .gg_sel_thumb_center td').removeClass('thumb_center');
                $('#TB_ajaxContent .gg_sel_thumb_center #gg_'+new_center).addClass('thumb_center');

                $thumb_center_subj.find('.gg_item_thumb').val(new_center);

                <?php if(get_option('gg_use_admin_thumbs')) : ?>
                    var img_src = encodeURIComponent( $thumb_center_subj.find('.gg_item_img_src').val() );
                    var base_script = (gg_use_tt) ? TT_url : EWPT_url;
                    var new_thumb_url = base_script +'?src='+img_src+'&w=400&h=220&q=85&rs=3&zc=3&a='+new_center;

                    $thumb_center_subj.find('.gg_builder_img').attr('src', new_thumb_url);
                <?php endif; ?>
            });
            
            
            
            // LC lightbox for images preview
            $(document).on('click', ".gg_zoom_img, .gg_enlarge_img, .gg_autopop_gallery .gg_builder_img", function(e) {
                e.stopPropagation();
                const img_url = (e.target.classList.contains('gg_builder_img')) ? $(this).data('fullurl') : $(this).parents('li').find('figure').data('fullurl');
                
                var obj = [{
                    type	: 'image',
                    src		: gdrive_img_url_trick(img_url),
                }];

                var instance = lc_lightbox(obj, {
                    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,

                    ins_close_pos	: 'corner',
                    open_close_time	: 200,
                    fading_time		: 0,
                });
                lcl_open(instance, 0); // direct lightbox opening showing first element
            });
            
            
            
            // Jan 2024 - Google Drive blocks image preloading through JS - use the thumb trick
            const gdrive_img_url_trick = function(img_url) {
                if(typeof(img_url) == 'string' && img_url.indexOf('drive.google.com') === -1) {
                    return img_url;   
                }

                const url_obj = new URL(img_url);
                if(url_obj.searchParams.get('id')) {
                    img_url = 'https://drive.google.com/thumbnail?sz=w5000&id='+ url_obj.searchParams.get('id');
                }

                return img_url;
            };
            
            
            
            // 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) > 300 || a == 1 ) {

                        $('#gg_fb_builder').css('grid-template-columns', 'repeat('+ a +', 1fr)');
                        break; 	
                    }
                }
            };
            images_columnize();
            
            
            
            // builder layout switch
            $(document).on('mousedown touchend', '#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_builder_wrap').toggleClass('gg_rows_builder_layout');
                $('#gg_rows_builder_layout, #gg_cols_builder_layout').removeClass('selected');
                $subj.addClass('selected');
                
                images_columnize();
            });
            
            
            
            
            
            //////////////////////////////////////////////////////////////////////////////////
            // EASY SORTING MODE
            
            //// append button - wait a bit to let images counter and bulk selection to be added
            setTimeout(function() {
                $('#gg_gallery_builder .gg_gb_h2').append(`
                    <a href="javascript:void(0)" id="gg_cols_builder_layout" class="<?php echo gg_static::builder_layout_selected('cols') ?>" title="<?php esc_attr_e('Columns builder layout', 'gg_ml') ?>">
                        <span class="dashicons dashicons-screenoptions"></span>
                    </a>
                    <a href="javascript:void(0)" id="gg_rows_builder_layout" class="<?php echo 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_sort_mode">
                        <?php esc_html_e('Easy sorting', 'gg_ml') ?> <span id="gg_sm_flag" class="off"><?php esc_html_e('OFF', 'gg_ml') ?></span>
                    </a>
                `);	

                if( $('#gg_autopop input').is(':checked') ) {
                    $('#gg_sort_mode').addClass('gg_displaynone');
                }
            }, 400);



            // manage sorting mode toggle
            $(document).on('mousedown', '#gg_sort_mode', function(e) {
                e.stopPropagation();

                if( !$(this).hasClass('gg_esm_on') ) {
                    $('#gg_fb_builder').addClass('gg_is_sorting');
                    $(this).addClass('gg_esm_on');

                    $('#gg_sm_flag').text(`<?php esc_html_e('ON', 'gg_ml') ?>`);
                    gg_sort_mode_on = true;
                }
                else {
                    $('#gg_fb_builder').removeClass('gg_is_sorting');
                    $(this).removeClass('gg_esm_on');

                    $('#gg_sm_flag').text(`<?php esc_html_e('OFF', 'gg_ml') ?>`);
                    gg_sort_mode_on = false;
                }
            });
            
            
            
            
            //////////////////////////////////////////////////////////////////////////////////
            // BULK CONTROLS
            
            //// append button - wait a bit to let images counter to act 
            setTimeout(function() {
                $('#gg_gallery_builder .gg_gb_h2').append(`<a href="javascript:void(0)" id="gg_select_all_img"><?php esc_html_e('Select all', 'gg_ml') ?></a>`);	
                if( $('#gg_autopop input').is(':checked') ) {
                    $('#gg_select_all_img').addClass('gg_displaynone');
                }
            }, 450);

            
            
            // single image select
            $(document).on('click', '.gg_row_to_sel', function() {
                $(this).toggleClass('gg_sel_row');
                $(this).parent().parent().toggleClass('selected');

                gg_bulk_opt();
            });

            

            // track button click
            $(document).on('mousedown', '#gg_select_all_img', function(e) {
                e.stopPropagation();

                if( $(this).hasClass('selected') ) {
                    $(this).removeClass('selected').text(`<?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();
                }
                else {
                    if(!$('.gg_row_to_sel').length) {
                        return false;
                    }

                    $(this).addClass('selected').text(`<?php esc_html_e('Deselect all', 'gg_ml') ?>`);

                    $('.gg_row_to_sel').each(function() {
                        $(this).addClass('gg_sel_row');
                        $(this).parent().parent().addClass('selected');
                    });
                    gg_bulk_opt();
                }
            });
            
            
            
            // bulk opt input toggle
            $(document).on('change', '#gg_bulk_opt', function() {
                if( $(this).val() == 'remove') {
                    $('#gg_bulk_val, #gg_bulk_thumb_val').addClass('gg_displaynone');
                }
                else if( $(this).val() == 'thumb') {
                    $('#gg_bulk_val').val('').addClass('gg_displaynone');
                    $('#gg_bulk_thumb_val').removeClass('gg_displaynone');
                }
                else {
                    $('#gg_bulk_val').val('').removeClass('gg_displaynone');
                    $('#gg_bulk_thumb_val').addClass('gg_displaynone');
                }
            });
            
            
            
            // perform bulk opt
            $(document).on('click', '#gg_bulk_perform', function() {
                var type = $('#gg_bulk_opt').val();
                var bulk_val = $('#gg_bulk_val').val();
                var new_center = $('#gg_bulk_thumb_val').val();

                if(type == 'remove') {
                    if(confirm(`<?php esc_html_e('Remove selected images?', 'gg_ml') ?>`)) {
                        $('#gg_fb_builder li.selected').remove();
                        
                        gg_sel_picker_img_status();
                        gg_count_gall_images();
                        gg_reset_selection(); 
                        
                        if(!$('#gg_fb_builder li').length) {
                            $('#gg_builder_wrap').html(`<div class="gg_manual_builder_no_img">.. <?php esc_html_e('no images added yet', 'gg_ml') ?> ..</div>`);
                            
                            if($('#gg_select_all_img').hasClass('selected')) {
                                $('#gg_select_all_img').trigger('mousedown');
                            }
                        }
                    }
                }
                else if(type == 'thumb') {
                    $('#gg_fb_builder li.selected').each(function() {
                        $(this).find('.gg_item_thumb').val(new_center);
                    });

                    gg_reset_selection();
                }
                else {
                    if(type == 'author') {
                        $('#gg_fb_builder li.selected .gg_item_author').val(bulk_val.replace(/\n/g, " "));
                    }
                    else if(type == 'title') {
                        $('#gg_fb_builder li.selected .gg_item_title').val(bulk_val.replace(/\n/g, " "));
                    }
                    else if(type == 'descr') {
                        $('#gg_fb_builder li.selected .gg_item_descr').val(bulk_val);
                    }

                    gg_reset_selection();
                }
            });
            
            
            
            
            //////////////////////////////////////////////////////////////////////////////////
            // AUTO-POPULATION
            
            // autopop switch behaviors
            
            // probably a conflict with LC-switch v1 - use this workaround for now
            setTimeout(() => {
                $(document).off('click tap', '.lcs_switch:not(.lcs_disabled)');
            }, 100);
            ///////////
            
            $(document).on('lcs-statuschange', '#gg_autopop input', function(e) {
                if( $(this).is(':checked') ) {
                    gg_autopop_make_cache();

                    // gallery auto-population toggle
                    $('.gg_autopop_fields').removeClass('gg_displaynone');
                    $('#gg_sort_mode, #gg_select_all_img, #gg_img_picker_area').addClass('gg_displaynone');

                    if($('#gg_sort_mode').hasClass('gg_esm_on')) {
                        $('#gg_sort_mode').trigger('mousedown');
                    }
                    if($('#gg_select_all_img').hasClass('selected')) {
                        $('#gg_select_all_img').trigger('mousedown');
                    }
                }
                else {
                    $('#gg_builder_wrap').html(`<div class="gg_manual_builder_no_img">.. <?php esc_html_e('no images added yet', 'gg_ml') ?> ..</div>`);
                    
                    gg_sel_picker_img_status();
                    $('#gg_sort_mode, #gg_select_all_img, #gg_img_picker_area').show();

                    // gallery auto-population toggle
                    $('.gg_autopop_fields').addClass('gg_displaynone');
                }
            });



            // re-load on click
            $(document).on('click', '.gg_rebuild_cache', function() {
                gg_autopop_make_cache();
            });
            
            
            
            
            
            //////////////////////////////////////////////////////////////////////////////////
            // SAVE
            
            // block standard WP post saving to save images asynchronously - only for manual galleries
            $('#post').on('submit', function(e) {
                if($('[name=gg_autopop]').is(':checked') || gg_saved_manual_gallery) {
                    return true;	
                }

                e.preventDefault();
                $('#publishing-action .spinner').css('visibility', 'visible');

                // store gallery data into a JSON string to be as compact as possible through ajax
                var gdata = {
                    gg_item_img_src : [],
                    gg_item_thumb 	: [],
                    gg_item_author 	: [],
                    gg_item_title 	: [],
                    gg_item_descr 	: [],
                    gg_item_tags 	: [],
                    gg_link_opt 	: [],
                    gg_item_link 	: [],
                };
                $('#gg_fb_builder li').each(function() {

                    gdata.gg_item_img_src.push(		$(this).find('.gg_item_img_src').val());
                    gdata.gg_item_thumb.push(		$(this).find('.gg_item_thumb').val());
                    gdata.gg_item_author.push(		$(this).find('.gg_item_author').val());
                    gdata.gg_item_title.push(		$(this).find('.gg_item_title').val());
                    gdata.gg_item_descr.push(		$(this).find('.gg_item_descr').val());
                    gdata.gg_item_tags.push(		$(this).find('.gg_item_tags').val());
                    gdata.gg_link_opt.push(			$(this).find('.gg_linking_dd').val());
                    gdata.gg_item_link.push(		$(this).find('.gg_link_field').val());
                });
                
                var data = {
                    action 	: 'gg_manual_gb_save',
                    gid		: gid,
                    nonce	: gg_nonce,
                    gdata 	: JSON.stringify(gdata),
                };
                $.post(ajaxurl, data, function(response) {
                    if($.trim(response) == 'success') {

                        // disable fields to avoid the same problem
                        $('#gg_fb_builder li').find('input, select, textarea').prop('disabled', 'disabled');

                        gg_saved_manual_gallery = true;
                        $('#publish').trigger('click');
                    }
                    else {
                        lc_wp_popup_message('error', response);
                        $('#publishing-action .spinner').css('visibility', 'hidden');	
                    }
                })
                .fail(function(e) {
                    if(e.status) {
                        console.error(e);
                        lc_wp_popup_message('error', `<?php esc_html_e("Error saving the gallery", 'gg_ml') ?>`);

                        $('#publishing-action .spinner').css('visibility', 'hidden');
                    }
                });

                return false;
            });
            
            
            // disable gallery builder section collapse
            setTimeout(() => {
                $('#gg_gallery_builder, #gg_specific_settings').removeClass('closed');
                $('#gg_gallery_builder h2.ui-sortable-handle, #gg_specific_settings h2.ui-sortable-handle').removeClass('hndle').addClass('gg_gb_h2').off('click');
                $('#gg_gallery_builder .handlediv').addClass('gg_displaynone');
            }, 300);
            
            
            
            // fixed submit position
            $(window).scroll(function(){
                if(!$('.gg_fixed_submit_btn').length) {	
                    let clone = $('#publish').clone().wrap("<div />").parent().html();
                    $('body').append(`<div id="gg_fixed_submit_btn" class="gg_displaynone"><input type="button" value="<?php esc_html_e('Update Gallery', 'gg_ml') ?>" class="button-primary" /></div>`);
                    
                    // track click to save gallery
                    $('#gg_fixed_submit_btn input').on('click', function() {
                        $('html, body').animate({scrollTop: 0}, 400, function () {
                            $('#publish').trigger('click');
                        });    
                    });
                }
                
                (document.documentElement.scrollTop > 300) ? $('#gg_fixed_submit_btn').removeClass('gg_displaynone') : $('#gg_fixed_submit_btn').addClass('gg_displaynone');
            });
        });
            
        
        
        
        
        /*** FUNCTIONS ***/
        
        // init fetching data and starting images picker
        const gg_gallery_init = function(on_builder_opening = false) {
            gg_basic_data();
            (!on_builder_opening) ? gg_load_settings() : gg_load_img_picker(1);	
        };
        
        
        
        // basic gallery data handle
        const gg_basic_data = function() {
            gg_type 	= $('#gg_type_dd').val();
            gg_username = $('#gg_username').val();
            gg_psw 		= $('#gg_psw').val();
        };
        
        
        
        // load images picker
        const gg_load_img_picker = function(page) {
            if(img_picker_ajax !== false) {
                img_picker_ajax.abort();
            }
            $('#gg_img_picker').html('<div class="gg_spinner"></div>');

            var data = {
                action		: 'gg_img_picker',
                gg_type		: gg_type,
                page		: page,
                per_page	: gg_img_pp,
                gallery_id	: gid,
                gg_search	: ($.trim($('.gg_img_search').val()).length > 2) ? $.trim($('.gg_img_search').val()) : '',
                gg_extra	: get_type_extra(),
                nonce		: gg_nonce,
            };

            img_picker_ajax = $.post(ajaxurl, data, function(response) {
                $('#gg_img_picker').html(response);
                gg_sel_img_on_drag();
                gg_sel_picker_img_status();

                img_picker_ajax = false;
            })
            .fail(function(e) {
                if(e.status) {
                    console.error(e);

                    $('#gg_img_picker').html(`<p><?php esc_html_e('error retrieving images', 'gg_ml') ?> ..</p><div>${ e.responseText }</div>`);
                    img_picker_ajax = false;
                }
            });
        };
        
        
        
        // gallery settings display
        const gg_load_settings = function() {
            if(spec_opt_ajax !== false) {
                spec_opt_ajax.abort();
            }
            $('#gg_settings_wrap').html('<div class="gg_spinner"></div>');

            var data = {
                action		: 'gg_load_gb_settings',
                gallery_id	: gid,
                gg_type		: gg_type,
                gg_username	: gg_username,
                gg_connect_id: ($('#gg_connect_id').length) ? $('#gg_connect_id').val() : false,
                gg_psw		: gg_psw,
                nonce		: gg_nonce,
            };

            spec_opt_ajax = $.post(ajaxurl, data, function(response) {
                $('#gg_settings_wrap').html(response);
                
                gg_live_lc_switch();
                gg_live_lc_select();

                gg_load_img_picker(1);
            })
            .fail(function(e) {
                if(e.status) {
                    console.error(e);
                    lc_wp_popup_message('error', `<?php esc_html_e("Error loading gallery settings", 'gg_ml') ?>`);
                }
            })
            .always(function() {
                spec_opt_ajax = false;
            });
        };
        
        
        
        // display added images count 
        const gg_count_gall_images = function() {
            if(!$('#gg_gallery_builder .postbox-header h2 small').length) {
                $('#gg_gallery_builder .postbox-header h2').append('<small></small>');	
            }

            var $subj = $('#gg_gallery_builder .postbox-header h2 small');
            var tot = $('#gg_fb_builder > li').length;

            (!tot) ? $subj.empty() : $subj.html(' ('+ tot +` <?php esc_html_e('images', 'gg_ml') ?>)`);
        };
        
        
        
        // get the additional vars depending on the type
        const get_type_extra = function() {
            switch(gg_type) {

                case 'wp_cat' : 
                    return $('#gg_wp_cat').val();

                case 'cpt_tax' : 
                    return { 
                        cpt_tax : $('#gg_cpt_tax').val(), 
                        term 	: $('#gg_cpt_tax_term').val() 
                    };

                case 'gg_album' : 
                    return $('#gg_album').val();

                case 'g_drive' : 
                    return $('#gg_gdrive_album').val();

                case 'onedrive' : 
                    return $('#gg_onedrive_album').val();

                case 'rml' : 
                    return $('#gg_rml_folder').val();

                case 'ngg' : 
                    return $('#gg_ngg_gallery').val();

                default :
                    return '';	
            }
        };
        
   
        
        // img selection with mouse drag - works also with click
        const gg_sel_img_on_drag = function() {   
            
            // security exclusion for touch devices
            if('ontouchstart' in window) {
                return false;    
            }
            
            new DragSelect({
                selectables : document.querySelectorAll('#gg_img_picker > ul li'),
                area        : document.querySelector('#gg_img_picker > ul'),
                overflowTolerance : { x: 0, y: 0 },
                callback    : function(targeted) {
                
                    // avoid "click" interferences, do nothing if only one is selected
                    if(targeted.length < 2) {
                        return false;    
                    }
                    
                    $.each(targeted, function(i, img) {
                        if(!$(img).hasClass('gg_img_inserted')) {
                            $(img).toggleClass('gg_img_sel');
                        }    
                    });
                    gg_man_img_array();
                }
            });
        };
        
        
        
        // reset gallery
        const gg_reset_gallery = function() {
            $('#gg_settings_wrap').html(`<em><?php esc_html_e('Select gallery type and fill in data to get images', 'gg_ml') ?></em>`);
            $('#gg_builder_wrap').html(`<div class="gg_manual_builder_no_img">.. <?php esc_html_e('no images added yet', 'gg_ml') ?> ..</div>`);
            $('#gg_gallery_builder > h3 small').remove();
        };
        
        
        
        // sortable images 
        const gg_sortable_images = function() {
            $('#gg_fb_builder').sortable({
                placeholder: {
                    element: function(currentItem) {
                        if(!gg_sort_mode_on) {
                            const placeh_h = ($('.gg_rows_builder_layout').length) ? 225 : 370;
                            return $('<li style="background-color: #97dd52; height: '+ placeh_h +'px;"></li>')[0];
                        } 
                        else {
                            return $('<li id="gg_builder_sm_placeh"></li>')[0];
                        }
                    },
                    update: function(container, p) {
                        return;
                    }
                },
                tolerance	: 'intersect',
                handle		: '.gg_builder_img, .gg_sm_handler',
                items		: 'li',
                opacity		: 0.9,
                scrollSensivity: 50,
                create		: function() {
                    $("#gg_fb_builder table input, #gg_fb_builder table textarea").bind('mousedown.ui-disableSelection selectstart.ui-disableSelection', function(e) {
                      e.stopImmediatePropagation();
                    });
                },
                stop : function () {
                    $("#gg_fb_builder table input, #gg_fb_builder table textarea").bind('mousedown.ui-disableSelection selectstart.ui-disableSelection', function(e) {
                      e.stopImmediatePropagation();
                    });
                }
            });
        };
            
        
        
        // bulk options code
        const gg_bulk_opt = function() {
            var bulk_opt_code = $('#gg_bulk_cmd_code_wrap').html();

            if($('#gg_fb_builder li.selected').length) {
                $('#gg_bulk_opt_wrap').empty().append(bulk_opt_code).removeClass('gg_displaynone');
                gg_live_lc_select();
            }
            else {
                $('#gg_bulk_opt_wrap').addClass('gg_displaynone').empty();
            }
        };


        
        // reset items selection
        const gg_reset_selection = function() {
            $('.gg_sel_row').each(function() {
                $(this).removeClass('gg_sel_row');
                $(this).parent().parent().removeClass('selected');

                if($('#gg_select_all_img').hasClass('selected')) {
                    $('#gg_select_all_img').removeClass('selected').text(`<?php esc_html_e('select all', 'gg_ml') ?>`);
                }
                gg_bulk_opt();
            });
        };



        // status updater for selected images
        const gg_sel_picker_img_status = function() {
            $('#gg_img_picker figure').each(function() {
                const $target   = $(this).parent(),
                      img_id    = $(this).data('id');

                ($('#gg_fb_builder > li[data-id="'+ img_id +'"]').length) ? $target.addClass('gg_img_inserted') : $target.removeClass('gg_img_inserted');
            });
        };
        
        
        
        // create the cache and display images in the builder
        const  gg_autopop_make_cache = function() {
            var max_img = $('#gg_max_images').val();
            var random_img = ( $('#gg_auto_random input').is(':checked') ) ? 1 : 0;

            var data = {
                action: 'gg_make_autopop',
                gg_type			: gg_type,
                gallery_id		: gid,
                gg_extra		: get_type_extra(),
                gg_max_img		: max_img,
                gg_random_img	: random_img,
                gg_erase_past	: gg_erase_past,
                nonce			: gg_nonce,
            };

            $('#gg_builder_wrap').html('<div class="gg_spinner gg_spinner_big"></div>');

            $.post(ajaxurl, data, function(response) {
                $('#gg_builder_wrap').html(response);

                gg_count_gall_images();
                gg_read_imgs_data();

                if(gg_erase_past) {
                    gg_erase_past = false;
                }
            })
            .fail(function(e) {
                if(e.status) {
                    console.error(e);
                    lc_wp_popup_message('error', `<?php esc_html_e("Error creating the auto-population cache", 'gg_ml') ?>`);
                }
            });

            return true;
        };
        
        
        
        // selected images array management
        const gg_man_img_array = function() {
            gg_sel_img = [];
            $('.gg_img_sel').each(function() {
                gg_sel_img.push( $(this).find('> figure').data('id') );
            });

            (gg_sel_img.length) ? $('#gg_add_img').removeClass('gg_displaynone') : $('#gg_add_img').addClass('gg_displaynone');
        };

        
        
        // images info detection - pass through JS to not weight on server
        const gg_read_imgs_data = function() {
            $('.gg_builder_img').each(function() {
                var $wrap = $(this).parents('li');

                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';
                        
                        // detect mime
                        switch(blob.type) {
                            case 'image/avif' : 
                            case 'application/octet-stream' : var type = 'avif'; break;
                                
                            case 'image/webp' : var type = 'webp'; break;    
                            case 'image/png'  : var type = 'png'; break;
                            case 'image/gif'  : var type = 'gif'; break;
                            default 		  : var type = 'jpg'; break;	
                        }


                        // 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>'+ bytes_to_human(blob.size) +'</span><span>'+ type +'</span><span>'+ sizes +'</span>\
                        </div>');
                    }
                    img.src = img_url;
                };
                xhr.send();
            });	
        };
        
        
        
        // bytes number to human format
        const bytes_to_human = function(bytes) {
           var sizes = ['bytes', 'kb', 'mb', 'gb'];
           if (bytes == 0) return '0 Byte';
           var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
           return Math.round(bytes / Math.pow(1024, i), 2) + sizes[i];
        };
        
        
        
        // auto-resizing textarea
        $.fn.gg_auto_h_textarea = function(strip_newlines) {
            $(this).each(function() {
                var min_val = ($(this).hasClass('gg_item_descr')) ? 50 : 28;
                $( this ).css('min-height', min_val).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 );
                } );
            });
        };
        
        
        
        // live lc switch declare
        const gg_live_lc_switch = function() {
            lc_switch('.gg_lc_switch', {
                on_txt      : `<?php echo strtoupper(esc_html__('yes', 'gg_ml')) ?>`,
                off_txt     : `<?php echo strtoupper(esc_html__('no', 'gg_ml')) ?>`,   
            });
        };

        

        // live lc select declare
        const gg_live_lc_select = function() {
            new lc_select('.gg_lc_select', {
                wrap_width : '90%',
                addit_classes : ['lcslt-lcwp'],
            });
        };

        
        
        // live preview link
        <?php
        $preview_pag = get_option('gg_preview_pag');
        if($preview_pag && $gallery) :
            $link = get_permalink($preview_pag);
        ?>
            var gg_live_preview = `
            <div class="misc-pub-section-last">
                <a href="<?php echo esc_attr($link) ?>?gg_gid=<?php echo absint($post->ID) ?>" target="_blank" id="gg_live_preview_link"><?php esc_html_e('Go to gallery preview', 'gg_ml') ?> &raquo;</a>
            </div>`;

            $('#submitpost').parent().append(gg_live_preview);
            $('#major-publishing-actions').addClass('misc-pub-section');
        <?php endif; ?>
        
        
        
        // remove subcategories commands
        if(document.getElementById('gg_gall_categories-adder')) {
            document.getElementById('gg_gall_categories-adder').remove();
        }
    })(jQuery);    
	</script>

    <?php
	return true;
}



add_action('icl_make_duplicate', function($post_id_from, $lang, $post_array, $post_id_to) {
    $gg_metas = array_unique(array(
        'gg_type',
        'gg_username',
        'gg_connect_id',
        'gg_autopop',
        'gg_auto_author',
        'gg_auto_title',
        'gg_auto_descr',
        'gg_auto_link',
        'gg_forced_author',
        'gg_cache_interval',
        'gg_auto_random',
        'gg_max_images',
        'gg_autopop_cache',
        'gg_gallery',
        'gg_img_count',
        'gg_wp_cat',
        'gg_cpt_tax',
        'gg_cpt_tax_term',
        'gg_album',
        'gg_fb_album',
        'gg_gdrive_album',
        'gg_onedrive_album',
        'gg_rml_folder',
        'gg_ngg_gallery',

        'gg_layout',
        'gg_thumb_w',
        'gg_thumb_h',

        'gg_colnzd_thumb_max_w',
        'gg_colnzd_thumb_h',
        'gg_colnzd_thumb_h_type',

        'gg_masonry_cols',
        'gg_masonry_min_width',

        'gg_photostring_h',
        'gg_photostring_min_width',

        'gg_paginate',
        'gg_per_page',

        'gg_orderby'
    ));

    if(get_post_type($post_id_from) === 'gg_galleries') {
        get_post_meta($post_id_from); // cache data to use one DB query
        
        foreach($gg_metas as $meta_key) {
            $original_value = get_post_meta($post_id_from, $meta_key, true);
            update_post_meta($post_id_to, $meta_key, $original_value);
        }
    }
}, 10, 4);