<?php 


////////////////////////////////////////////////////////
// Easy WP thumbs - status
function gg_ewpt_status($field_id, $field, $value, $all_vals) {
	?>
	<table id="gg_ewpt_status_wrap" class="widefat lcwp_settings_table">
		<tr class="gg_<?php echo $field_id ?>">
			<td>
            	<input type="hidden" name="ewpt_status_f" value="" /> <?php //JS vis trick ?>
				<?php ewpt_wpf_form('gg_ml'); ?>
			</td>
		</tr>	
	</table>
    
    <script type="text/javascript">
    (function($) { 
        "use strict"; 
        
        document.addEventListener("DOMContentLoaded", function() {
            const toggle = function() {
                (document.querySelector('input[name=gg_use_timthumb]').checked) ? $('#gg_ewpt_status_wrap').hide() : $('#gg_ewpt_status_wrap').show();        
            };
            toggle(); // on opening


            document.querySelector('input[name=gg_use_timthumb]').addEventListener('lcs-statuschange', () => {
                toggle()
            });
        });
        
    })(jQuery); 
	</script>
    <?php
}






////////////////////////////////////////////////////////
// preset styles preview and setter 
function gg_preset_styles($field_id, $field, $value, $all_vals) {
	
	// build code
	echo '
	<table id="gg_preset_styles_cmd_wrap" class="widefat lcwp_settings_table">
		<tr class="mg_'. $field_id .'">
			<td class="lcwp_sf_label"><label>'. esc_html__('Choose style', 'gg_ml') .'</label></td>
			<td class="lcwp_sf_field">
				<select name="'. $field_id .'" id="gg_pred_styles" class="lcwp_sf_select gg_pred_styles_cf_select" autocomplete="off">
					<option value="">'. esc_html__('choose an option', 'gg_ml') .'</option>';
				
					foreach(gg_preset_style_names() as $id => $name) {
						echo '<option value="'. esc_attr($id) .'">'. esc_html($name) .'</option>';	
					}
		echo '
				</select>   
			</td>
			<td>
				<input name="mg_set_style" id="gg_set_style" value="'. esc_attr__('Set', 'gg_ml') .'" class="button-secondary" type="button" />
			</td>
			<td><span class="lcwp_sf_note">'. esc_html__('Overrides styling options and applies preset styles', 'gg_ml') .'. '.
            
            // translators: 1–2: <strong> and </strong> tags used around “page will be reloaded”.
            sprintf(esc_html__('Once applied, %1$spage will be reloaded%2$s with changed options', 'gg_ml'), '<strong>', '</strong>') .'</span></td>
		</tr>
		<tr class="gg_displaynone">
			<td class="lcwp_sf_label"><label>'. esc_html__('Preview', 'gg_ml') .'</label></td>
			<td colspan="3" id="gg_preset_styles_preview"></td>
		</tr>
	</table>';
	
	?>
    <script type="text/javascript">
    (function($) { 
        "use strict";   
		
		// predefined style - preview toggle
		$(document).on("change", '#gg_pred_styles', function() {
			var sel = $('#gg_pred_styles').val();
			
			if(!sel) {
				$('#gg_preset_styles_preview').empty();	
			}
			else {
				$('#gg_preset_styles_cmd_wrap tr').last().removeClass('gg_displaynone');
				
				const img_url = '<?php echo esc_js(GG_URL) ?>/img/pred_styles_demo/'+ sel +'.jpg';
				$('#gg_preset_styles_preview').html('<img src="'+ img_url +'" />');		
			}
		});
		
		
		// set predefined style 
		$(document).on('click', '#gg_set_style', function() {
			const $this = $(this);
            
            var sel_style = $('#gg_pred_styles').val();
			if(!sel_style) {
                return false;
            }
            
			if(!confirm(`<?php esc_html_e('This will overwrite your current styling settings and refresh the page, continue?', 'gg_ml') ?>`)) {
                return false;
            }
                
            $this.replaceWith('<div class="gg_spinner" style="margin: 0; width: 25px; height: 25px;"></div>');

            var data = {
                action: 'gg_set_predefined_style',
                style: sel_style,
                lcwp_nonce: '<?php echo wp_create_nonce('lcwp_nonce') ?>'
            };

            $.post(ajaxurl, data, function(response) {
                if($.trim(response) == 'success') {
                    $('#lc_toast_mess').empty().html(`<div class="lc_success"><p><?php esc_html_e('Style successfully applied!', 'gg_ml') ?></p><span></span></div>`);	
                    $('#lc_toast_mess').addClass('lc_tm_shown');

                    setTimeout(function() {
                        window.location.reload();	
                    }, 1500);
                }
                else {
                    lc_wp_popup_message('error', response);	
                    $this.empty();
                }
            })
            .fail(function(e) {
                console.error(e);

                lc_wp_popup_message('error', 'error setting the style');	
                $this.empty();
            });	
		});
    })(jQuery); 
    </script>
    <?php
}





////////////////////////////////////////////////////////
// Lightbox overlay pattern
function gg_img_fx_preview($field_id, $field, $value, $all_vals) {
	$no_pattern_sel = (!$value || $value == 'none') ? 'gg_pattern_sel' : '';
	
	echo '
	<tr class="gg_'. $field_id .'">
		<td class="lcwp_sf_label"><label>'. esc_html__('Live preview', 'gg_ml') .'</label></td>
        <td class="lcwp_sf_field" colspan="2">
            <div class="gg_img_fx_preview">
                <span>
                    <img src="'. GG_URL .'/img/fx_demo_1.jpg" />
                </span>
                <span>
                    <img src="'. GG_URL .'/img/fx_demo_2.jpg" />
                </span>
                <span>
                    <img src="'. GG_URL .'/img/fx_demo_3.jpg" />
                </span>
            </div>
            
            <input type="hidden" name="gg_img_fx_preview" value="" /> <!-- JS vis trick -->
		</td>
	</tr>';
	
	?>
	<script type="text/javascript">
    (function($) { 
        "use strict";   
        
        $(document).ready(function($) {
            const $wrap = $('.gg_gg_img_fx_behavior').parents('table').first();

            const apply = function() {
                if($('#gg_img_fx_css').length) {
                    $('#gg_img_fx_css').remove();        
                }

                const behavior = $('select[name="gg_img_fx_behavior"]').val();
                if(!behavior) {
                    return false;    
                }

                let val = 
                'filter: '+    
                'blur('+ parseFloat( $('input[name="gg_img_fx_blur"]').val()) +'px) ' +
                'brightness('+ parseFloat( $('input[name="gg_img_fx_brightness"]').val()) +'%) ' +
                'contrast('+ parseFloat( $('input[name="gg_img_fx_contrast"]').val()) +') ' +
                'grayscale('+ parseFloat( $('input[name="gg_img_fx_grayscale"]').val()) +'%) ' +
                'hue-rotate('+ parseFloat( $('input[name="gg_img_fx_hue"]').val()) +'deg) ' +
                'invert('+ parseFloat( $('input[name="gg_img_fx_invert"]').val()) +'%) ' +
                'saturate('+ parseFloat( $('input[name="gg_img_fx_saturate"]').val()) +') ' +    
                'sepia('+ parseFloat( $('input[name="gg_img_fx_sepia"]').val()) +'%);';

                let efxv_default    = val;
                let efxv_hover      = 'filter: none;';

                if(behavior == 'hover_status') {
                    efxv_default    = '';    
                    efxv_hover      = val;       
                } 

                const code = `
                .gg_img_fx_preview img {
                    ${ efxv_default }
                    transition: filter .4s ease;
                }
                .gg_img_fx_preview img:hover {
                    ${ efxv_hover }
                }`;

                $('head').append('<style id="gg_img_fx_css">'+ code +'</style>');
            };  
            apply();

            $wrap.on('change', 'select', () => {apply()} );
            $wrap.on('input', 'input[type=range]', () => {apply()} );
            $wrap.on('keyup', 'input[type=number]', () => {apply()} );
        });
    })(jQuery);   
	</script>
    <?php	
}





////////////////////////////////////////////////////////
// Lightbox overlay pattern
function gg_lb_ol_pattern_f($field_id, $field, $value, $all_vals) {
	$no_pattern_sel = (!$value || $value == 'none') ? 'gg_pattern_sel' : '';
	
	echo '
	<tr class="gg_'. $field_id .'">
		<td class="lcwp_sf_label"><label>'. esc_html__("Overlay's pattern", 'mg_ml') .'</label></td>
		<td class="lcwp_sf_field" colspan="2">
			<input type="hidden" value="'. esc_attr($value) .'" name="gg_lb_ol_pattern" id="gg_lb_ol_pattern" />
			
			<div class="gg_setting_pattern '.$no_pattern_sel.'" rel="none"> no pattern </div>';
			
			foreach(gg_lcl_patterns_list() as $pattern) {
				$sel = ($value == $pattern) ? 'gg_pattern_sel' : '';  
                
				echo '<div class="gg_setting_pattern '. esc_attr($sel) .'" rel="'. esc_attr($pattern) .'" style="background: url('. esc_attr(GG_URL) .'/js/lightboxes/lc-lightbox/img/patterns/'. esc_attr($pattern) .'.png) repeat top left transparent;"></div>';		
			}
	
	echo '
		</td>
	</tr>';
	
	?>
	<script type="text/javascript">
    (function($) { 
        "use strict"; 
        
		$(document).on('click', '.gg_setting_pattern', function() { // select a pattern
			$('.gg_setting_pattern').removeClass('gg_pattern_sel');
			$(this).addClass('gg_pattern_sel'); 
			
			$('#gg_lb_ol_pattern').val( $(this).attr('rel') );
		});
	})(jQuery);   
	</script>
    <?php	
}





////////////////////////////////////////////////////////
// upper watermark block (JS is in lower part)
function gg_u_wm_fields($field_id, $field, $value, $all_vals) {
	
	if(!isset($all_vals['gg_watermark_pos']) || empty($all_vals['gg_watermark_pos'])) {$all_vals['gg_watermark_pos'] = 'MM';}
	?>
    
    <table class="widefat lcwp_settings_table mg_settings_block">
      <tbody>
		<tr class="gg_wm_url">
        	<td class="lcwp_sf_label">
            	<label><?php esc_html_e('Watermark image', 'gg_ml') ?></label>
            </td> 
  			<td class="lcwp_sf_field" colspan="2">
                <div>
                
                    <input name="gg_watermark_img" id="gg_watermark_img" value="<?php echo esc_attr($all_vals['gg_watermark_img']) ?>" placeholder="<?php esc_attr_e("use wizard or paste image's URL", 'gg_ml') ?>" autocomplete="off" type="text" />
                    <br/>
                    <input value="<?php esc_attr_e("Select image or upload a new one", 'gg_ml') ?>" id="gg_wm_media_manag" class="button-secondary" type="button" />	
                </div>

            	<div class="gg_upload_imgwrap">
				  <?php
                  if( !empty($all_vals['gg_watermark_img']) && preg_match( '/(^.*\.jpg|jpeg|png|gif*)/i', strtolower($all_vals['gg_watermark_img']))) {
					  echo '
					  <img src="'. esc_attr($all_vals['gg_watermark_img']) .'" />
					  <span class="gg_del_ul_img dashicons dashicons-dismiss" title="'. esc_attr__('remove image', 'gg_ml') .'"></span>';
				  }
				  else {
                      echo '<div class="no_image"></div>';
                  }
                  ?>
            	</div>      
            </td>
		</tr>     
        <tr class="gg_wm_pos">
        	<td class="lcwp_sf_label">
            	<label><?php esc_html_e('Watermark position', 'gg_ml') ?></label>
            </td> 
  			<td class="lcwp_sf_field" colspan="2">
            	<input value="<?php echo $all_vals['gg_watermark_pos'] ?>" name="gg_watermark_pos" id="gg_watermark_pos" type="hidden">
                
                <table class="gg_sel_thumb_center">
					<tr>
                        <td id="gg_LT"></td>
                        <td id="gg_MT"></td>
                        <td id="gg_RT"></td>
                    </tr>
                    <tr>
                        <td id="gg_LM"></td>
                        <td id="gg_MM" class="thumb_center"></td>
                        <td id="gg_RM"></td>
                    </tr>
                    <tr>
                        <td id="gg_LB"></td>
                        <td id="gg_MB"></td>
                        <td id="gg_RB"></td>
                    </tr>
                </table>
            
            </td>
      	</tr>
    <?php
}





////////////////////////////////////////////////////////
// lower watermark block
function gg_l_wm_fields($field_id, $field, $value, $all_vals) {
		?>   
        <tr>
        	<td class="lcwp_sf_label">
            	<label><?php esc_html_e('Clean watermark cache', 'gg_ml') ?></label>
            </td>
            <td class="lcwp_sf_field">
				<input value="<?php echo esc_attr__('Clean', 'gg_ml') ?>" id="gg_clean_cache" class="button-secondary" type="button">
			</td>
			<td>
            	<span class="gg_wm_clean_status info"></span>
            </td>
        </tr>
        
      </tbody>
    </table>
    
    <script type="text/javascript">
    (function($) { 
        "use strict";     
         
        jQuery(document).ready(function($) {
            const nonce = '<?php echo esc_js(wp_create_nonce('lcwp_nonce')) ?>';

            // watermark - media image  manager 
            var file_frame = false;

            $(document).on('click', '#gg_wm_media_manag', 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_attr_e('Global Gallery - watermark selection', 'gg_ml') ?>`,
                    button: {
                        text: `<?php esc_html_e('Select', 'gg_ml') ?>`,
                    },
                    library : {type : 'image'},
                    multiple: false
                });

                // When an image is selected, run a callback.
                file_frame.on('select', function() {
                    var img_data = file_frame.state().get('selection').first().toJSON();

                    $('#gg_watermark_img').val(img_data.url);
                    $('.gg_upload_imgwrap').html('<img src="'+ img_data.url +'" /><span class="gg_del_ul_img dashicons dashicons-dismiss" title="remove image"></span>');
                });

                file_frame.open();
            });


            // watermark removal
            $(document).on('click', '.gg_del_ul_img', function() {
                $('#gg_watermark_img').val('');
                $('.gg_upload_imgwrap').html('<div class="no_image"></div>');
            });


            // create watermark cache
            $(document).on('click', '#gg_create_cache', function() {
                var wm_img = $.trim(`<?php echo esc_js($all_vals['gg_watermark_img']) ?>`);

                if(!wm_img) { 
                    lc_wp_popup_message('error', `<?php esc_html_e("Watermark image hasn't been set", 'gg_ml') ?>`);
                    return false;
                }
                else {
                    if(!confirm(`<?php esc_html_e("WARNING: this affects every image in existing galleries and might slow down your server for a while. Continue?", 'gg_ml') ?>`)) {
                        return false;	
                    }

                    $('.gg_wm_create_status').html(`<div class="gg_spinner"></div>
                    <small style="padding-left: 15px;">(<?php esc_html_e('might take very long having many images to manage', 'gg_ml' ) ?>)</small>`);

                    var data = {
                        action: 'gg_create_wm_cache',
                        nonce : nonce
                    };
                    $.post(ajaxurl, data, function(response) {
                        var resp = $.trim(response);

                        if(resp == 'success') {
                            $('.gg_wm_create_status').html(`<?php esc_html_e('Cache succesfully created!', 'gg_ml') ?>`); 
                        }
                        else {
                            if(resp.indexOf("Maximum execution") !== -1) {
                                $('.gg_wm_create_status').html(`<?php esc_html_e('Process took too much time for your server. Try creating the cache again', 'gg_ml') ?>`); 
                            }
                            else if(resp.indexOf("bytes exhausted") !== -1) {
                                $('.gg_wm_create_status').html(`<?php esc_html_e('The process requires too much memory for your server. Try applying it to smaller images', 'gg_ml') ?>`); 	
                            }
                            else {
                                $('.gg_wm_create_status').html(`<?php esc_html_e('Error during cache creation', 'gg_ml') ?>`); 
                            }
                        }
                    })
                    .fail(function(e) {
                        console.error(e);
                        $('.gg_wm_create_status').html(`<?php esc_html_e('Error during cache creation', 'gg_ml') ?>`); 
                    });	
                }
            });


            // clean watermark cache
            $(document).on('click', '#gg_clean_cache', function() {
                if( confirm(`<?php esc_html_e("Every cached image will be deleted. Continue?", 'gg_ml') ?>`) ) {
                    $('.gg_wm_clean_status').html('<div style="margin: 0; width: 25px; height: 25px;" class="gg_spinner"></div>');

                    var data = {
                        action: 'gg_clean_wm_cache',
                        nonce : nonce
                    };
                    $.post(ajaxurl, data, function(response) {
                        var resp = $.trim(response);

                        if(resp == 'success') { 
                            $('.gg_wm_clean_status').html(`<?php esc_html_e('Cache cleaned succesfully!', 'gg_ml') ?>`);
                        }
                        else {
                            $('.gg_wm_clean_status').html(`<?php esc_html_e('Error during the cache deletion', 'gg_ml') ?>`);
                        }
                    })
                    .fail(function(e) {
                        console.error(e);
                        $('.gg_wm_clean_status').html(`<?php esc_html_e('Error during the cache deletion', 'gg_ml') ?>`);
                    });	
                }
            });


            // set watermark position
            const gg_watermark_position = function(position) {
                $('.gg_sel_thumb_center td').removeClass('thumb_center');
                $('.gg_sel_thumb_center #gg_'+position).addClass('thumb_center');

                $('#gg_watermark_pos').val(position);	
            }
            gg_watermark_position( $('#gg_watermark_pos').val() );


            $(document).on('click', '.gg_sel_thumb_center td', function() {
                var new_position = jQuery(this).attr('id').substr(3);
                gg_watermark_position(new_position);
            }); 
        });
    })(jQuery);  
	</script>
    <?php
}



