<?php 
include_once(PC_DIR . '/classes/simple_form_validator.php');
include_once(PC_DIR . '/settings/settings_engine.php'); 
include_once(PC_DIR . '/settings/field_options.php'); 
include_once(PC_DIR . '/settings/custom_fields.php');
include_once(PC_DIR . '/settings/structure.php'); 

global $pc_wp_user;
?>

<div class="wrap lcwp_settings_wrap" style="direction: LTR; overflow-x: hidden;">  
	<div class="icon32" id="icon-pc_user_manage"><br></div>
    <h2 class="pc_page_title"><?php _e( 'PrivateContent Settings', 'pc_ml') ?></h2>  
    
	<?php
    $engine = new pc_settings_engine('pc_settings', $GLOBALS['pc_settings_tabs'], $GLOBALS['pc_settings_structure']);
    
    // get fetched data and allow customizations
    if($engine->form_submitted()) {
        $fdata = $engine->form_data;
        $errors = (!empty($engine->errors)) ? $engine->errors : array();


        // validate custom redirects
        if($fdata['pg_redirect_page'] == 'custom' && empty($fdata['pg_redirect_page_custom'])) {
            $errors[ __('Restriction redirect target / Custom URL', 'pc_ml') ] = __('Insert a valid URL', 'pc_ml'); 	
        }
        if($fdata['pg_logged_user_redirect'] == 'custom' && empty($fdata['pg_logged_user_redirect_custom'])) {
            $errors[ __('Logged In Users Redirect / Custom URL', 'pc_ml') ] = __('Insert a valid URL', 'pc_ml'); 	
        }
        if($fdata['pg_logout_user_redirect'] == 'custom' && empty($fdata['pg_logout_user_redirect_custom'])) {
            $errors[ __('Logged In Users Redirect / Custom URL', 'pc_ml') ] = __('Insert a valid URL', 'pc_ml'); 	
        }
        
        
		// Google Analytics - validate tracking code
		if(!empty($fdata['pg_analytics_id'])) {
			if(!preg_match('/^ua-\d{4,9}-\d{1,4}$/i', $fdata['pg_analytics_id'])) {
				$errors[ __('Google Analytics', 'pc_ml') ] = __('Tracking ID format is wrong', 'pc_ml'); 	
			}
		}
		
		
		// WP registration to PC - where enabled, require caregories
		if(!empty($fdata['wp_to_pc_sync_on_register']) && empty($fdata['wp_to_pc_sync_on_register_cats'])) {
			$errors[ __('WordPress to PrivateContent - Registration Sync', 'pc_ml') ] = __('Select at least one category', 'pc_ml'); 
		}
		
		
		// lightbox instances - validate and save
		if(isset($_POST['pc_lb_id'])) {
			$tot_lb = count($_POST['pc_lb_id']);
			$GLOBALS['pc_lb_data'] = array(); // utility array to keep changes also with errors 
			
			// check fields consistency
			if(
				(!is_array($_POST['pc_lb_note']) || count($_POST['pc_lb_note']) != $tot_lb) ||
				(!is_array($_POST['pc_lb_contents']) || count($_POST['pc_lb_contents']) != $tot_lb)
			) {
				$errors[ __('Lightbox instances', 'pc_ml') ] = __('Missing fields', 'pc_ml'); 		
			}
			
			else {
				// every field must be filled
				$a = 0;
				foreach($_POST['pc_lb_id'] as $lb_id) {
					$note 		= stripslashes($_POST['pc_lb_note'][$a]);
					$contents 	= stripslashes($_POST['pc_lb_contents'][$a]);
					
					$GLOBALS['pc_lb_data'][$lb_id] = array(
						'note' 		=> $note,
						'contents'	=> $contents
					);
					
					if(empty($note) || empty($contents)) {
						$errors[ __('Lightbox instances', 'pc_ml') ] = __('Every field must be filled', 'pc_ml'); 	
					}
					else {
						wp_update_term($lb_id, 'pc_lightboxes', array(
						  'name' 		=> $note,
						  'description'	=> base64_encode($contents)
						));
						
						// sync with WPML
						if(function_exists('icl_register_string')) {
							icl_register_string('PrivateContent Lightboxes', 'Lightbox #'.$lb_id, $contents);
						}
						
						// sync with Polylang
						if(function_exists('pll_register_string')) {
							pll_register_string('PrivateContent Lightboxes', $contents, 'Lightbox #'.$lb_id, true);
						}
					}
					
					$a++;
				}
			}
		}
		
		
        // custom restrictions - check data existence in arrays
        if(!empty($fdata['pg_cr_url'])) {
            for($a=0; $a < count($fdata['pg_cr_url']); $a++) {
                if(empty($fdata['pg_cr_url'][$a]) || !isset($fdata['pg_cr_allow'][$a]) || empty($fdata['pg_cr_allow'][$a])) {
                    
                    $errors[ __('Custom Restrictions', 'pc_ml') ] = __('Each restriction must have an "allow" value', 'pc_ml'); 	
                    break;	
                }
            }
        }
        

        // PC-FILTER - manipulate setting errors - passes errors array and form values - error subject as index + error text as val
        $errors = apply_filters('pc_setting_errors', $errors, $fdata);	
        
        
        // save or print error
        if(empty($errors)) {
            
            // apply custom WPS roles
            if($fdata['pg_wp_user_sync'] && !empty($fdata['pg_custom_wps_roles'])) {
                $old_roles = $pc_wp_user->get_wps_custom_roles();
                $new_roles = array_unique( array_merge(array('pvtcontent'), (array)$fdata['pg_custom_wps_roles']));
                
                sort($old_roles); sort($new_roles);
                
                if($old_roles !== $new_roles) {
                    $pc_wp_user->wps_roles = $new_roles;
                    $pc_wp_user->set_wps_custom_roles();
                    
                    $fdata['pg_custom_wps_roles'] = $new_roles;
                }	
            }
            
            // PC-FILTER - allow data manipulation (or custom actions) before settings save - passes form values
            $engine->form_data = apply_filters('pc_before_save_settings', $fdata); 
            
            
            // save
            $engine->save_data();

            // create custom style css file
            if(!get_option('pg_inline_css') && $fdata['pg_style'] == 'custom') {
                if(!pc_create_custom_style()) {
                    update_option('pg_inline_css', 1);	
                    echo '<div class="updated"><p>'. __('An error occurred during dynamic CSS creation. Code will be used inline anyway', 'pc_ml') .'</p></div>';
                }
                else {delete_option('pg_inline_css');}
            }
			
			
			// refresh to allow saved values to be spread in structure
			wp_redirect( str_replace( '%7E', '~', $_SERVER['REQUEST_URI']) . '&lcwp_sf_success');
  			exit;
        }
        
        // compose and return errors
        else {
            $err_elems = array();
            foreach($errors as $i => $v) {
                if(is_numeric($i)) {
                    $err_elems[] = $v;	
                }
                else {
                    $err_elems[] = $i .' - '. $v;	
                }
            }
            
            echo '<div class="error lcwp_settings_result"><p>'. implode(' <br/> ', $err_elems) .'</p></div>';	
        }
    }
	
	
	// if successdully saved
	if(isset($_GET['lcwp_sf_success'])) {
		echo '<div class="updated lcwp_settings_result" style="display: none;"><p><strong>'. __('Options saved', 'pc_ml') .'</strong></p></div>';	
	}
	
	// print form code
    echo $engine->get_code();
    ?>
</div>




<?php // CUSTOM CSS ?>
<style type="text/css">
#rf_builder {
	border-bottom: none;	
}
.pc_pg_analytics_id input {
	max-width: 212px;	
}
</style>



<?php
// FIELDS ICON WIZARD
include_once(PC_DIR . '/classes/lc_font_awesome_helper.php');
$fa = new lc_fontawesome_helper;

echo '
<div id="pc_icons_list" style="display: none;">
	<div class="pc_lb_icons_wizard">
		<p rel="" class="pctoi_no_icon"><a>'. __('no icon', 'pc_ml') .'</a></p>';
	
		foreach($fa->sorted_icons as $cat => $icons) {
			echo '<h4>'. $cat .'</h4>';
			
			foreach($icons as $iid => $unicode) {
				$idata = $fa->icons[$iid];
				echo '<i rel="'.$idata->class.'" class="fa '.$idata->class.'" title="'.$idata->name.'"></i>';
			}
		}

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



<?php // SCRIPTS ?>
<script src="<?php echo PC_URL; ?>/js/lc-switch/lc_switch.min.js" type="text/javascript"></script>
<script src="<?php echo PC_URL; ?>/js/chosen/chosen.jquery.min.js" type="text/javascript"></script>
<script src="<?php echo PC_URL; ?>/js/colpick/js/colpick.min.js" type="text/javascript"></script>

<link rel="stylesheet" href="<?php echo PC_URL; ?>/js/codemirror/codemirror.css">
<script src="<?php echo PC_URL; ?>/js/codemirror/codemirror.min.js" type="text/javascript"></script>
<script src="<?php echo PC_URL; ?>/js/codemirror/languages/css.min.js" type="text/javascript"></script>

<script type="text/javascript" charset="utf8">
// codemirror - execute before tabbing
jQuery('.lcwp_sf_code_editor').each(function() {
	CodeMirror.fromTextArea( jQuery(this)[0] , {
		lineNumbers: true,
		mode: "css"
	});
});


jQuery(document).ready(function($) {
	var rf_is_acting = false; // registration form builder flag 
	var li_is_acting = false; // lightbox instance flag  
	var wps_is_acting = false; // WP user sync flag 
	var pc_nonce = '<?php echo wp_create_nonce('lcwp_ajax') ?>';
	
	
	// lightbox instance - add 
	jQuery('body').delegate('#pc_add_lb_trig', 'click', function() {
		li_is_acting = true;
		
		var $parent = jQuery(this).parents('h3');
		$parent.append('<span class="pc_loading" style="position: relative; left: 10px; bottom: -7px;"></span>');
		
		var data = {
			action: 'pc_add_lightbox',
			pc_nonce: pc_nonce
		};
		jQuery.post(ajaxurl, data, function(response) {
			$parent.find('.pc_loading').remove();
			li_is_acting = false;
			
			if(jQuery.trim(response) == 'error') {
				alert("<?php _e('Error creating lightbox term', 'pc_ml') ?>");	
			}
			else {
				if(!jQuery('#pc_lb_inst li').length) {
					jQuery('#pc_lb_inst li em').remove();	
				}
				
				jQuery('#pc_lb_inst').append(response);	
			}
		});
	});
	
	
	// lightbox instance - remove
	jQuery('body').delegate('#pc_lb_inst li .pc_del_field', 'click', function() {
		if(!li_is_acting && confirm("<?php echo addslashes( __("Once deleted, you won't be able to use this trigger's class. Continue?", 'pc_ml')) ?>")) {
			
			var $li = jQuery(this).parents('li');
			var lb_id = jQuery(this).attr('rel');
			
			li_is_acting = true;
			$li.fadeTo(200, 0.5);
			
			var data = {
				action	: 'pc_del_lightbox',
				lb_id	: jQuery(this).attr('rel'),
				pc_nonce: pc_nonce
			};
			jQuery.post(ajaxurl, data, function(response) {
				li_is_acting = false;

				if(jQuery.trim(response) != 'success') {
					alert(response);	
					$li.fadeTo(200, 1);
				} else {
					$li.remove();
				}
			});
		}
	});
	
	
	/////////////////////////////////////////////////////////////////////
	
	
	// custom restrictions - add 
	jQuery('body').delegate('#pc_add_cr_trig', 'click', function() {
		if(jQuery('#pc_cr_list em').length) {jQuery('#pc_cr_list').empty();}
		
		jQuery('#pc_cr_list').append(' <?php echo addslashes(str_replace(array("\r", "\n", "\t", "\v"), '', pc_cr_template())); ?> ');
		pc_live_chosen();
	});
	
	
	// custom restrictions - remove
	jQuery('body').delegate('#pc_cr_list li .pc_del_field', 'click', function() {
		if(confirm("<?php echo addslashes( __("Remove this restriction?", 'pc_ml')) ?>")) {
			jQuery(this).parents('li').slideUp(function() {
				jQuery(this).remove();
			});
		}
	});
	
	
	// custom restrictions - avoid empty "allow/block" dropdown
	jQuery("form.form-wrap").submit(function(e) {
		jQuery('#pc_cr_list .pg_cr_allow').each(function() {
        	if(jQuery(this).val() == null) {
				jQuery(this).replaceWith('<input type="hidden" name="pg_cr_allow[][]" value="" />');	
			}
        });
		
		jQuery('#pc_cr_list .pg_cr_block').each(function() {
        	if(jQuery(this).val() == null) {
				jQuery(this).replaceWith('<input type="hidden" name="pg_cr_block[][]" value="" />');	
			}
        });
	});
	
	
	// custom restrictions - all/unlogged toggles
	jQuery('body').delegate('#pc_cr_list li select', 'change', function() {
		var pc_sel = jQuery(this).val();
		if(!pc_sel) {pc_sel = jQuery.makeArray();}
		
		// if ALL is selected, discard the rest
		if(jQuery.inArray("all", pc_sel) >= 0) {
			jQuery(this).find('option').prop('selected', false);
			jQuery(this).find('.pc_all_field').prop('selected', true);
			
			jQuery(this).trigger("chosen:updated");
		}
		
		// if UNLOGGED is selected, discard the rest
		else if(jQuery.inArray("unlogged", pc_sel) >= 0) {
			jQuery(this).find('option').prop('selected', false);
			jQuery(this).find('.pc_unl_field').prop('selected', true);
			
			jQuery(this).trigger("chosen:updated");
			var unlogged_chosen = true;
		}	
	});
	
	
	// custom restrictions - set allow/block dropdown indexes to allow multidimensional saving
	jQuery("form.form-wrap").submit(function() {
		jQuery('#pc_cr_list > li').each(function(i, v) {
            jQuery(this).find('.pg_cr_allow').attr('name', 'pg_cr_allow['+ i +'][]');
			jQuery(this).find('.pg_cr_block').attr('name', 'pg_cr_block['+ i +'][]');
        });
		
		return true;
	});
	
	
	// custom restrictions - sortable
	jQuery("#pc_cr_list").sortable({ 
		handle: '.pc_move_field',
		axis: "y" 
	});
	jQuery("#pc_cr_list .pc_move_field").disableSelection();
	
	
	/////////////////////////////////////////////////////////////////////
	
	
	// registration form builder - add form
	jQuery('body').delegate('#pc_reg_form_add', 'click', function() {
		var name = jQuery.trim( jQuery('#pc_new_reg_form_name').val());
		if(!name || rf_is_acting) {return false;}
		
		rf_is_acting = true;
		jQuery('#pc_reg_form_loader').html('<span class="pc_loading"></span>');
		
		var data = {
			action: 'pc_add_reg_form',
			form_name: name,
			pc_nonce: pc_nonce
		};
		jQuery.post(ajaxurl, data, function(response) {
			jQuery('#pc_reg_form_loader').empty();
			rf_is_acting = false;
			
			if(jQuery.isNumeric(response)) {
				jQuery('.pc_form_builder_dd option').removeAttr('selected');
				jQuery('.pc_form_builder_dd').append('<option value="'+ response +'" selected="selected">'+ response +' - '+ name +'</option>');
				
				jQuery('#pc_new_reg_form_name').val('');
				jQuery('.pc_form_builder_dd').trigger("chosen:updated").trigger('change');
			}
			else {
				alert(response);	
			}
		});
	});
	
	
	// registration form builder - load builder
	jQuery('body').delegate('.pc_form_builder_dd', 'change', function() {
		var val = jQuery(this).val();
		if(!val) {
			jQuery('#pc_reg_form_cmd').css('visibility', 'hidden');
			jQuery('#pc_reg_form_builder').empty();
			return false;
		}
		
		if(rf_is_acting) {return false;}
		rf_is_acting = true;
		jQuery('#pc_reg_form_loader').html('<span class="pc_loading"></span>');
		
		var data = {
			action: 'pc_reg_form_builder',
			form_id: val,
			pc_nonce: pc_nonce
		};
		jQuery.post(ajaxurl, data, function(response) {
			jQuery('#pc_reg_form_cmd').css('visibility', 'visible');
			jQuery('#pc_reg_form_builder').html(response);
			
			pc_live_checks();
			pc_live_chosen();
			
			/*** sort formbuilder rows ***/
			jQuery( "#pc_reg_form_builder tbody" ).sortable({ 
				handle: '.pc_move_field',
				axis: "y" 
			});
			jQuery( "#pc_reg_form_builder tbody td .pc_move_field" ).disableSelection();
			
			jQuery('#pc_reg_form_loader').empty();
			rf_is_acting = false;
		});
	});
	// on start - load first form
	if(jQuery('.pc_form_builder_dd option').size()) {
		jQuery('.pc_form_builder_dd').trigger('change');	
	}
	

	// add field to builder
	jQuery('body').delegate('#pc_rf_add_field', 'click', function() { 
		var f_val = jQuery('.pc_rf_fields_dd').val();
		var f_name = jQuery('.pc_rf_fields_dd option[value="'+ f_val +'"]').text();
		
		if(f_val != 'custom|||text' && f_val != 'custom|||page' && jQuery('#pc_rf_builder_table tr[rel="'+ f_val +'"]').size()) {
			alert("<?php _e('Field already in the form', 'pc_ml') ?>");
			return false;	
		}
		
		var required = (f_val == 'categories') ? 'checked="checked"' : '';
		var disabled = (f_val == 'categories') ? 'disabled="disabled"' : ''; 
		
		if(f_val == 'custom|||text') {
			var code = 
			'<td colspan="2">'+
				'<input type="hidden" name="pc_reg_form_field[]" value="'+ f_val +'" class="pc_reg_form_builder_included" />'+
				'<textarea name="pc_reg_form_texts[]" placeholder="<?php _e('Supports HTML and shortcodes', 'pc_ml') ?>"></textarea>'+
			'</td>';
		}
		else if(f_val == 'custom|||page') {
			var code = 
			'<td colspan="2" class="pc_paginator_td">'+
				'<input type="hidden" name="pc_reg_form_field[]" value="'+ f_val +'" class="pc_reg_form_builder_included" />'+
				'<?php _e('PAGINATOR', 'pc_ml') ?>'+
			'</td>';
		}
		else {
			var code = 
			'<td>'+
				'<input type="hidden" name="pc_reg_form_field[]" value="'+ f_val +'" class="pc_reg_form_builder_included" />'+
				f_name +
			'</td>'+
			'<td>'+
				'<input type="checkbox" name="pc_reg_form_req[]" value="'+ f_val +'" '+required+' '+disabled+' class="lcwp_sf_check pc_reg_form_builder_required" autocomplete="off" />'+
			'</td>';	
		}
		
		jQuery('#pc_rf_builder_table tbody').append(
		'<tr rel="'+ f_val +'">'+
			'<td><span class="pc_del_field" title="<?php _e('remove field', 'pc_ml') ?>"></span></td>'+
			'<td><span class="pc_move_field" title="<?php _e('sort field', 'pc_ml') ?>"></span></td>'+
			code +
		'</tr>');
		
		pc_live_checks();
	});
	
	
	// delete form field
	jQuery('body').delegate('#pc_rf_builder_table .pc_del_field', 'click', function() { 
		if(!rf_is_acting) {
			jQuery(this).parents('tr').fadeOut(400 ,function() {
				jQuery(this).remove();
			});
		}
	});
	
	
	// update form structure 
	jQuery('body').delegate('.pc_reg_form_save', 'click', function() {
		if(rf_is_acting) {return false;}
		
		rf_is_acting = true;
		jQuery('#pc_reg_form_loader').html('<span class="pc_loading"></span>');
		
		var form_id = jQuery('.pc_form_builder_dd').val();
		var form_name = jQuery('#pc_rf_name').val();

		// create fields + required array
		var included = jQuery.makeArray();
		var required = jQuery.makeArray();
		var texts 	= jQuery.makeArray();
		
		jQuery('#pc_rf_builder_table tbody tr').each(function(i,v) {
        	var f = jQuery(this).find('.pc_reg_form_builder_included').val();
		    included.push(f);
			
			if(f == 'custom|||text') {
				texts.push( jQuery(this).find('textarea').val() );	
			}
			else {
				if( jQuery(this).find('.pc_reg_form_builder_required').is(':checked') ) {
					required.push(f);	
				}
			}
        });
		
		var data = {
			action: 'pc_update_reg_form',
			form_id: form_id,
			form_name: form_name, 
			fields_included: included,
			fields_required: required,
			texts: texts,
			pc_nonce: pc_nonce
		};
		jQuery.post(ajaxurl, data, function(response) {
			jQuery('#pc_reg_form_loader').empty();
			rf_is_acting = false;
			
			if(jQuery.trim(response) == 'success') {
				jQuery('.pc_form_builder_dd option[value='+ form_id +']').html( form_id+' - '+form_name );
				jQuery('.pc_form_builder_dd').trigger("chosen:updated");	
				
				jQuery('.pc_reg_form_save').css('background-color', '#3C7336').css('color', '#fff');
				setTimeout(function(){
					jQuery('.pc_reg_form_save').css('background-color', '').css('color', '');
				}, 500);
			}
			else {alert(response);}
		});	
	});
	
	
	// delete form - leaving one
	jQuery('body').delegate('#pc_reg_form_del', 'click', function() {
		if(jQuery('.pc_form_builder_dd option').size() == 1) {
			alert("<?php _e('At least one form is required', 'pc_ml') ?>");
			return false;	
		}
		
		var form_id = jQuery('.pc_form_builder_dd').val();
		if(!form_id) {return false;}
		
		if(confirm("<?php _e('Delete this form? Related shortcodes will show the first one', 'pc_ml') ?>")) {
			rf_is_acting = true;
			jQuery('#pc_reg_form_loader').html('<span class="pc_loading"></span>');

			var data = {
				action: 'pc_del_reg_form',
				form_id: form_id,
				pc_nonce: pc_nonce
			};
			jQuery.post(ajaxurl, data, function(response) {
				jQuery('#pc_reg_form_loader').empty();
				rf_is_acting = false;
				
				if(jQuery.trim(response) == 'success') {
					jQuery('.pc_form_builder_dd option[value='+ form_id +']').remove();
					jQuery('.pc_form_builder_dd option').first().attr('selected', 'selected');
					jQuery('.pc_form_builder_dd').trigger("chosen:updated").trigger('change');	
					
					jQuery('#pc_reg_form_del').css('background-color', '#BB7071').css('color', '#fff');
					setTimeout(function(){
						jQuery('#pc_reg_form_del').css('background-color', '').css('color', '');
					}, 500);
				}
				else {alert(response);}
			});	
		}
	});
	
	
	///////////////////////////////////////////////////
	
	// sync WP users sync
	jQuery('body').delegate('#pc_do_wp_sync', 'click', function() {
		if(!wps_is_acting && confirm("<?php _e('Mirror wordpress users will be created. Continue?', 'pc_ml') ?>")) {
			
			wps_is_acting = true;
			var $result_wrap = jQuery(this).next('span');
			$result_wrap.html('<div class="pc_loading" style="margin-bottom: -7px;"></div>');
			
			var data = {
				action: 'pc_wp_global_sync',
				pc_nonce: pc_nonce
			};
			jQuery.post(ajaxurl, data, function(response) {
				$result_wrap.html(response);
				wps_is_acting = false;
			});
		}
	});
	
	// clean WP users sync
	jQuery('body').delegate('#pc_clean_wp_sync', 'click', function() {
		if(!wps_is_acting && confirm("<?php _e('WARNING: this will delete connected wordpress users and any related content will be lost. Continue?', 'pc_ml') ?>")) {
			
			wps_is_acting = true;
			var $result_wrap = jQuery(this).next('span');
			$result_wrap.html('<div class="pc_loading" style="margin-bottom: -7px;"></div>');
			
			var data = {
				action: 'pc_wp_global_detach',
				pc_nonce: pc_nonce
			};
			jQuery.post(ajaxurl, data, function(response) {
				$result_wrap.html(response);
				wps_is_acting = false;
			});
		}
	});
	
	// search existing matches and sync
	jQuery('body').delegate('#pc_wps_matches_sync', 'click', function() {
		if(!wps_is_acting && confirm("<?php _e('WARNING: this will turn matched WP userse into PrivateContent mirrors. Continue?', 'pc_ml') ?>")) {
			
			wps_is_acting = true;
			var $result_wrap = jQuery(this).next('span');
			$result_wrap.html('<div class="pc_loading" style="margin-bottom: -7px;"></div>');
			
			var data = {
				action: 'pc_wps_search_and_sync_matches',
				pc_nonce: pc_nonce
			};
			jQuery.post(ajaxurl, data, function(response) {
				$result_wrap.html(response);
				wps_is_acting = false;
			});
		}
	});
	
	//////////////////////////////////////
	
	
	//// redirects toggle
	// redirect target
	jQuery('body').delegate('#pc_redirect_page', 'change', function(){
		var red_val = jQuery(this).val();
		
		if(red_val == 'custom') {jQuery('#pc_redirect_page_cst_wrap td').fadeIn();}
		else {jQuery('#pc_redirect_page_cst_wrap td').fadeOut();}
	});
	
	// login redirect 
	jQuery('body').delegate('#pc_logged_user_redirect', 'change', function(){
		var red_val = jQuery(this).val();
		
		if(red_val == 'custom') {jQuery('#pc_logged_user_redirect_cst_wrap td').fadeIn();}
		else {jQuery('#pc_logged_user_redirect_cst_wrap td').fadeOut();}
	});
	
	// logout redirect 
	jQuery('body').delegate('#pc_logout_user_redirect', 'change', function(){
		var red_val = jQuery(this).val();
		
		if(red_val == 'custom') {jQuery('#pc_logout_user_redirect_cst_wrap td').fadeIn();}
		else {jQuery('#pc_logout_user_redirect_cst_wrap td').fadeOut();}
	});


	//////////////////////////////////////////////////
	
	
	// launch option icon wizard
	var $sel_type_opt = false;
	jQuery('body').delegate('.pc_field_icon_trigger i', "click", function() {
		$sel_type_opt = jQuery(this).parent();
		
		tb_show('Choose an icon' , '#TB_inline?inlineId=pc_icons_list');
		setTimeout(function() {
			jQuery('#TB_ajaxContent').css('width', 'auto');
			jQuery('#TB_ajaxContent').css('height', (jQuery('#TB_window').height() - 47) );
		}, 50);
	});
	jQuery(window).resize(function() {
		if( jQuery('#TB_ajaxContent .pc_lb_icons_wizard').length ) {
			jQuery('#TB_ajaxContent').css('height', (jQuery('#TB_window').height() - 47) );	
		}
	});
	
	
	// select icon
	jQuery('body').delegate('#TB_ajaxContent .pc_lb_icons_wizard > *', "click", function() {
		var val = jQuery(this).attr('rel');
		
		$sel_type_opt.find('input').val(val);
		$sel_type_opt.find('i').attr('class', 'fa '+val);
		
		tb_remove();
		$sel_type_opt = false;
	});	
	
	
	//////////////////////////////////////////////////
	
	
	// replacing jQuery UI tabs 
	jQuery('.lcwp_settings_tabs').each(function() {
    	var sel = '';
		var hash = window.location.hash;
		
		var $form = jQuery(".lcwp_settings_form");
		var form_act = $form.attr('action');

		// track URL on opening
		if(hash && jQuery(this).find('.nav-tab[href='+ hash +']').length) {
			jQuery(this).find('.nav-tab').removeClass('nav-tab-active');
			jQuery(this).find('.nav-tab[href='+ hash +']').addClass('nav-tab-active');	
			
			$form.attr('action', form_act + hash);
		}
		
		// if no active - set first as active
		if(!jQuery(this).find('.nav-tab-active').length) {
			jQuery(this).find('.nav-tab').first().addClass('nav-tab-active');	
		}
		
		// hide unselected
		jQuery(this).find('.nav-tab').each(function() {
            var id = jQuery(this).attr('href');
			
			if(jQuery(this).hasClass('nav-tab-active')) {
				sel = id
			}
			else {
				jQuery(id).hide();
			}
        });
		
		// scroll to top by default
		jQuery("html, body").animate({scrollTop: 0}, 0);
		
		// track clicks
		if(sel) {
			jQuery(this).find('.nav-tab').click(function(e) {
				e.preventDefault();
				if(jQuery(this).hasClass('nav-tab-active')) {return false;}
				
				var sel_id = jQuery(this).attr('href');
				window.location.hash = sel_id.replace('#', '');
				
				$form.attr('action', form_act + sel_id);
				
				// show selected and hide others
				jQuery(this).parents('.lcwp_settings_tabs').find('.nav-tab').each(function() {
                    var id = jQuery(this).attr('href');
					
					if(sel_id == id) {
						jQuery(this).addClass('nav-tab-active');
						jQuery(id).show();		
					}
					else {
						jQuery(this).removeClass('nav-tab-active');
						jQuery(id).hide();	
					}
                });
			});
		}
   });
   
  
   
	// sliders
	pc_slider_opt = function() {
		var a = 0; 
		$('.lcwp_sf_slider_wrap').each(function(idx, elm) {
			var sid = 'slider'+a;
			jQuery(this).attr('id', sid);	
		
			svalue = parseInt(jQuery("#"+sid).next('input').val());
			minv = parseInt(jQuery("#"+sid).attr('min'));
			maxv = parseInt(jQuery("#"+sid).attr('max'));
			stepv = parseInt(jQuery("#"+sid).attr('step'));
			
			jQuery('#' + sid).slider({
				range: "min",
				value: svalue,
				min: minv,
				max: maxv,
				step: stepv,
				slide: function(event, ui) {
					jQuery('#' + sid).next().val(ui.value);
				}
			});
			jQuery('#'+sid).next('input').change(function() {
				var val = parseInt(jQuery(this).val());
				var minv = parseInt(jQuery("#"+sid).attr('min'));
				var maxv = parseInt(jQuery("#"+sid).attr('max'));
				
				if(val <= maxv && val >= minv) {
					jQuery('#'+sid).slider('option', 'value', val);
				}
				else {
					if(val <= maxv) {jQuery('#'+sid).next('input').val(minv);}
					else {jQuery('#'+sid).next('input').val(maxv);}
				}
			});
			
			a = a + 1;
		});
	}
	pc_slider_opt();
	
	
	// colorpicker
	pc_colpick = function () {
		jQuery('.lcwp_sf_colpick input').each(function() {

			var curr_col = jQuery(this).val().replace('#', '');
			jQuery(this).colpick({
				layout:'rgbhex',
				submit: 0,
				color: curr_col,
				onChange:function(hsb,hex,rgb, el, fromSetColor) {
					if(!fromSetColor){ 
						jQuery(el).val('#' + hex);
						jQuery(el).parents('.lcwp_sf_colpick').find('.lcwp_sf_colblock').css('background-color','#'+hex);
					}
				}
			}).keyup(function(){
				jQuery(this).colpickSetColor(this.value);
				jQuery(this).parents('.lcwp_sf_colpick').find('.lcwp_sf_colblock').css('background-color', this.value);
			});  
		});
	}
	pc_colpick();
   
  
   // lc switch
	var pc_live_checks = function() { 
		jQuery('.lcwp_sf_check').lc_switch('YES', 'NO');
	}
	pc_live_checks();
	
	
	
	// chosen
	var pc_live_chosen = function() { 
		jQuery('.lcwp_sf_chosen').each(function() {
			var w = jQuery(this).css('width');
			jQuery(this).chosen({width: w}); 
		});
		jQuery(".lcweb-chosen-deselect").chosen({allow_single_deselect:true});
	}
	pc_live_chosen();
	
	
	
	//////////////////////////////////////////////////
	
	
	// fixed submit position
	var pc_fixed_submit = function(btn_selector) {
		var $subj = jQuery(btn_selector);
		if(!$subj.length) {return false;}
		
		var clone = $subj.clone().wrap("<div />").parent().html();

		setInterval(function() {
			
			// if page has scrollers or scroll is far from bottom
			if((jQuery(document).height() > jQuery(window).height()) && (jQuery(document).height() - jQuery(window).height() - jQuery(window).scrollTop()) > 130) {
				if(!jQuery('.lcwp_settings_fixed_submit').length) {	
					$subj.after('<div class="lcwp_settings_fixed_submit">'+ clone +'</div>');
				}
			}
			else {
				if(jQuery('.lcwp_settings_fixed_submit').length) {	
					jQuery('.lcwp_settings_fixed_submit').remove();
				}
			}
		}, 50);
	};
	pc_fixed_submit('.lcwp_settings_submit');
	
	
	//////////////////////////////////////////////////
	
	
	
	// toast message for better visibility
	if(jQuery('.lcwp_settings_result').length) {
		jQuery('body').append('<div id="lc_toast_mess"></div>');
		
		var $subj = jQuery('.lcwp_settings_result');
		var subj_txt = $subj.find('p').html();
		
		jQuery('head').append(
		'<style type="text/css">' +
		'#lc_toast_mess,#lc_toast_mess *{-moz-box-sizing:border-box;box-sizing:border-box}#lc_toast_mess{background:rgba(20,20,20,.2);position:fixed;top:0;right:-9999px;width:100%;height:100%;margin:auto;z-index:99999;opacity:0;filter:alpha(opacity=0);-webkit-transition:opacity .15s ease-in-out .05s,right 0s linear .5s;-ms-transition:opacity .15s ease-in-out .05s,right 0s linear .5s;transition:opacity .15s ease-in-out .05s,right 0s linear .5s}#lc_toast_mess.lc_tm_shown{opacity:1;filter:alpha(opacity=100);right:0;-webkit-transition:opacity .3s ease-in-out 0s,right 0s linear 0s;-ms-transition:opacity .3s ease-in-out 0s,right 0s linear 0s;transition:opacity .3s ease-in-out 0s,right 0s linear 0s}#lc_toast_mess:before{content:"";display:inline-block;height:100%;vertical-align:middle}#lc_toast_mess>div{position:relative;padding:13px 16px!important;border-radius:2px;box-shadow:0 2px 17px rgba(20,20,20,.25);display:inline-block;width:310px;margin:0 0 0 50%!important;left:-155px;top:-13px;-webkit-transition:top .2s linear 0s;-ms-transition:top .2s linear 0s;transition:top .2s linear 0s}#lc_toast_mess.lc_tm_shown>div{top:0;-webkit-transition:top .15s linear .1s;-ms-transition:top .15s linear .1s;transition:top .15s linear .1s}#lc_toast_mess>div>span:after{font-family:dashicons;background:#fff;border-radius:50%;color:#d1d1d1;content:"";cursor:pointer;font-size:23px;height:15px;padding:5px 9px 7px 2px;position:absolute;right:-7px;top:-7px;width:15px}#lc_toast_mess>div:hover>span:after{color:#bbb}#lc_toast_mess .lc_error{background:#fff;border-left:4px solid #dd3d36}#lc_toast_mess .lc_success{background:#fff;border-left:4px solid #7ad03a}' +
		'</style>');	
		
		// close toast message
		jQuery(document.body).off('click tap', '#lc_toast_mess');
		jQuery(document.body).on('click tap', '#lc_toast_mess', function() {
			jQuery('#lc_toast_mess').removeClass('lc_tm_shown');
		});
		
		
		// if success - simply hide main one
		if($subj.hasClass('updated')) {
			jQuery('#lc_toast_mess').empty().html('<div class="lc_success"><p>'+ subj_txt +'</p><span></span></div>');	
			$subj.remove();	
			
			// remove &lcwp_sf_success
			history.replaceState(null, null, window.location.href.replace('&lcwp_sf_success', ''));
		}
		
		// show errors but keep them visible on top
		else {
			jQuery('#lc_toast_mess').empty().html('<div class="lc_error"><p><?php _e('One or more errors occurred', 'pc_ml') ?></p><span></span></div>');
			jQuery("html, body").animate({scrollTop: 0}, 0);		
		}
		
		// use a micro delay to let CSS animations act
		setTimeout(function() {
			jQuery('#lc_toast_mess').addClass('lc_tm_shown');
		}, 30);
		
		// auto-close after a while
		setTimeout(function() {
			jQuery('#lc_toast_mess.lc_tm_shown span').trigger('click');
		}, 2300);	
	}
		
});
</script>


<?php
// PC-ACTION - allow extra code printing in settings (for javascript/css)
do_action('pc_settings_extra_code');
?>
