<?php

/* ------------------------------------------------------------------*/
/* ADD CUSTOM SCRIPTS FOR JQUERY UI */
/* ------------------------------------------------------------------*/

function wprs_add_custom_scripts() {
	global $wprs_custom_meta_fields, $wprs_options;

	// Date Picker
	$output = '<script type="text/javascript">
				jQuery(function() {';

	foreach ($wprs_custom_meta_fields as $field) { // loop through the fields looking for certain types
		if($field['type'] == 'date')
			$output .= 'jQuery(".datepicker").datepicker();';
			
		// Slider
		if ($field['type'] == 'slider') {
			$field_id = $field['id'];
			$value = $wprs_options["$field_id"] != '' ? $wprs_options["$field_id"] : '0';
			
			$output .= '
					jQuery( "#'.$field['id'].'-slider" ).slider({
						value: '.$value.',
						min: '.$field['min'].',
						max: '.$field['max'].',
						step: '.$field['step'].',
						slide: function( event, ui ) {
							jQuery( "#wprs_val_slider_'.$field['id'].'" ).val( ui.value );
						}
					});';
		}
	}

	
	$output .= '});
		</script>';

	echo $output;
}

add_action('admin_head','wprs_add_custom_scripts');

/* ------------------------------------------------------------------*/
/* CREATE THE FIELDS AND DISPLAY THEM */
/* ------------------------------------------------------------------*/

function wprs_show_custom_tabs() {
	
	global $wprs_custom_tabs;
	
	echo '<h2 class="nav-tab-wrapper">';
	foreach ($wprs_custom_tabs as $tab) {
		echo '<a href="#'.$tab['id'].'" class="nav-tab">'.$tab['label'].'</a>';
	}
	echo '<a href="#help" class="nav-tab"><span class="fa fa-question-circle"></span> '.__('Help', 'wprs').'</a>';
	echo '</h2>';
}

/* ------------------------------------------------------------------*/
/* CREATE THE FIELDS AND DISPLAY THEM */
/* ------------------------------------------------------------------*/

function wprs_show_custom_fields() {

	global $wprs_custom_meta_fields;
	$wprs_prefix = 'wprs_';
	
	// Use nonce for verification
	echo '<input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';

	// Begin the field table and loop
	echo '<div id="tab_container">';

	
	
	foreach ($wprs_custom_meta_fields as $field) {
		// get value of this field if it exists for this post
		$wprs_options = get_option('wprs_options');
		
		// Begin a new tab
		if( $field['type'] == 'tab_start') {
			echo '<div class="tab_content" id="'.$field['id'].'">';
			echo '<table class="form-table">';
		}

		// begin a table row with
		echo '<tr>';

				if( $field['type'] != 'tab_start' && $field['type'] != 'tab_end') {
					if( $field['type'] == 'title') {
						echo '<th colspan="2"><h3 id="wprs_options['.$field['id'].']">'.$field['label'].'</h3></th>';
					} else {
						echo '<th><label for="wprs_options['.$field['id'].']">'.$field['label'].'</label></th>';
					}
				}
				
		if( $field['type'] != 'tab_start' && $field['type'] != 'tab_end') {
		echo	'<td>';
				if( isset( $wprs_options[$field['id']] ) ) {
					$meta = $wprs_options[$field['id']];
				} else {
					$meta = '';
				}
				
				switch($field['type']) {
					// text
					case 'text':
						echo '<input type="text" name="wprs_options['.$field['id'].']" id="wprs_options['.$field['id'].']" value="'.$meta.'" size="30" class="regular-text" />
							<span class="description">'.$field['desc'].'</span>';
					break;
					// text
					case 'text_tiny':
						echo '<input type="text" name="wprs_options['.$field['id'].']" id="wprs_options['.$field['id'].']" value="'.$meta.'" size="5" />
							<span class="description">'.$field['desc'].'</span>';
					break;
					// password
					case 'password':
						echo '<input type="password" name="wprs_options['.$field['id'].']" id="wprs_options['.$field['id'].']" value="'.$meta.'" size="30" class="regular-text" />
							<span class="description">'.$field['desc'].'</span>';
					break;
					// textarea
					case 'textarea':
						echo '<textarea name="wprs_options['.$field['id'].']" id="wprs_options['.$field['id'].']" cols="60" rows="4">'.$meta.'</textarea>
							<br /><br /><span class="description">'.$field['desc'].'</span>';
					break;
					// checkbox
					case 'checkbox':
						echo '<input type="checkbox" name="wprs_options['.$field['id'].']" id="wprs_options['.$field['id'].']" ',$meta != '' ? ' checked="checked"' : '',' />
							<label for="wprs_options['.$field['id'].']">
							<span class="description">'.$field['desc'].'</span></label>';
					break;
					// select
					case 'select':
						echo '<select name="wprs_options['.$field['id'].']" id="wprs_options['.$field['id'].']">';
						foreach ($field['options'] as $option) {
							echo '<option', $meta == $option['value'] ? ' selected="selected"' : '', ' value="'.$option['value'].'">'.$option['label'].'</option>';
						}
						echo '</select>&nbsp;<span class="description">'.$field['desc'].'</span>';
					break;
					// radio
					case 'radio':
						foreach ( $field['options'] as $option ) {
							echo '<input type="radio" name="wprs_options['.$field['id'].']" id="wprs_options['.$option['value'].']" value="'.$option['value'].'" ',$meta == $option['value'] ? ' checked="checked"' : '',' />
									<label for="'.$option['value'].'">'.$option['label'].'</label><br />';
						}
						echo '<br /><span class="description">'.$field['desc'].'</span>';
					break;
					// checkbox_group
					case 'checkbox_group':
						foreach ($field['options'] as $option) {
							echo '<input type="checkbox" value="'.$option['value'].'" name="wprs_options['.$field['id'].'][]" id="wprs_options['.$option['value'].']"',$meta && in_array($option['value'], $meta) ? ' checked="checked"' : '',' />
									<label for="'.$option['value'].'">'.$option['label'].'</label><br />';
						}
						echo '<br /><br /><span class="description">'.$field['desc'].'</span>';
					break;
					// tax_select
					case 'tax_select':
						echo '<select name="wprs_options['.$field['id'].']" id="wprs_options['.$field['id'].']">
								<option value="">-- '.__('Select','wprs').' --</option>'; // Select One
						$terms = get_terms($field['id'], 'get=all');
						$selected = wp_get_object_terms('', 'wprs_options['.$field['id'].']');
						foreach ($terms as $term) {
							if ($selected && $term->slug == $wprs_options[$field['id']] )
								echo '<option value="'.$term->slug.'" selected="selected">'.$term->name.'</option>';
							else
								echo '<option value="'.$term->slug.'">'.$term->name.'</option>';
						}
						$taxonomy = get_taxonomy($field['id']);
						echo '</select><br /><span class="description"><a href="'.get_bloginfo('home').'/wprs-admin/edit-tags.php?taxonomy='.$field['id'].'">'.__('Manage', 'wprs').' '.$taxonomy->label.'</a></span>';
					break; 
					// post_list
					case 'post_list':
						$items = get_posts( array (
							'post_type'	=> $field['post_type'],
							'posts_per_page' => -1
						));
						echo '<select name="wprs_options['.$field['id'].']" id="wprs_options['.$field['id'].']">
								<option value="">-- '.__('Select','wprs').' --</option>'; // Select One
							foreach($items as $item) {
								if( $item->post_type == 'page' OR $item->post_type == 'post') {
									$post_type = str_replace('page', __('page', 'wprs'), $item->post_type);
									$post_type = str_replace('post', __('post', 'wprs'), $item->post_type);
								} else { $post_type = $item->post_type; }
								echo '<option value="'.$item->ID.'"',$wprs_options[$field['id']] == $item->ID ? ' selected="selected"' : '','>'.$post_type.': '.$item->post_title.'</option>';
							} // end foreach
						echo '</select>&nbsp;<span class="description">'.$field['desc'].'</span>';
					break;     
					// date
					case 'date':
						echo '<input type="text" class="datepicker" name="wprs_options['.$field['id'].']" id="wprs_options['.$field['id'].']" value="'.$wprs_options[$field['id']].'" size="30" />
								<span class="description">'.$field['desc'].'</span>';
					break;
					// image
					case 'image':
						//$image = get_template_directory_uri().'/images/image.png';
						if ($wprs_options[$field['id']]) { 
							$image = wp_get_attachment_image_src($wprs_options[$field['id']], 'medium');
							$image = $image[0]; } 
						else { 
							$image = ''; 
						}
						echo '<span class="custom_default_image" style="display:none">'.$image.'</span>';
						echo	'<input name="wprs_options['.$field['id'].']" id="wprs_options['.$field['id'].']" type="hidden" class="custom_upload_image" value="'.$wprs_options[$field['id']].'" />
									<img src="'.$image.'" class="custom_preview_image" alt="" /><br />
										<input class="custom_upload_image_button button" type="button" value="'.__('Choose Image', 'wprs').'" />
										<small> <a href="#" class="custom_clear_image_button">'.__('Remove Image', 'wprs').'</a></small>
										<br clear="all" /><span class="description">'.$field['desc'].'';
					break;
					// slider
					case 'slider':
					$field_id = $field['id'];
					$value = $wprs_options["$field_id"] != '' ? $wprs_options["$field_id"] : '0';
						echo '<div id="'.$field['id'].'-slider"></div>
								<input type="text" name="wprs_options['.$field['id'].']" id="wprs_val_slider_'.$field['id'].'" value="'.$value.'" size="5" />
								<br /><span class="description">'.$field['desc'].'</span>';
					break;
					
					// repeatable
					// @since 1.1.9 
					case 'repeatable':
						
						$title= 'title';
						$desc= 'desc';
						$item_rating = 'rating';
						$item_range = 'range';
						
						echo '<ul id="wprs_options['.$field['id'].']-repeatable" class="custom_repeatable">';
						$i = 0;

						if ( isset($wprs_options[$field['id']]) && $wprs_options[$field['id']] ) {
							foreach($wprs_options[$field['id']] as $row) {
								echo '<li><span class="sort hndle fa fa-arrows icon-move"></span>
											<input type="text" name="wprs_options['.$field['id'].']['.$i.']['.$title.']" id="wprs_options['.$field['id'].']" value="'.$row['title'].'" placeholder=" Enter Unique ID" size="40" />
											<input type="text" name="wprs_options['.$field['id'].']['.$i.']['.$desc.']" id="wprs_options['.$field['id'].']" value="'.$row['desc'].'" placeholder=" Enter Title (best fit one word)" size="40" />
											<input type="text" name="wprs_options['.$field['id'].']['.$i.']['.$item_rating.']" id="wprs_options['.$field['id'].']" value="'.$row['rating'].'" placeholder=" Rating" size="6" /> %
											<a class="repeatable-remove fa fa-trash-o" title="Delete"></a></li>';
								$i++;
							}
						} else {
							echo '<li><span class="sort hndle fa fa-arrows icon-move"></span>
										<input type="text" name="wprs_options['.$field['id'].']['.$i.']['.$title.']" id="wprs_options['.$field['id'].']" value="" placeholder=" Enter Unique ID" size="40" />
										<input type="text" name="wprs_options['.$field['id'].']['.$i.']['.$desc.']" id="wprs_options['.$field['id'].']" value="" placeholder=" Enter Title (best fit one word)" size="40" />
										<input type="text" name="wprs_options['.$field['id'].']['.$i.']['.$item_rating.']" id="wprs_options['.$field['id'].']" value="" placeholder=" Rating" size="6" /> %
										<a class="repeatable-remove fa fa-trash-o" title="Delete"></a></li>';
						}
						echo '</ul>';
						echo '<a class="repeatable-add button" href="#">+ Add</a>';
						echo '<br /><br /><span class="description">'.$field['desc'].'</span>';
						
						// debug array output
						//echo '<br /><br />';
						//print_r($meta);
						//echo '<br /><br />';
						//echo 'count: '.count($meta);
						//echo '<br />';
						
					break;
					
					
					// update criteria
					case 'update_criteria':
						?>
                        <p>
                        <a href="admin.php?page=wprs&update_criteria=true" onclick="return confirm('Are you sure?')" class="button-secondary">
                        <i class="fa fa-refresh" style="margin-right:8px;"></i><?php echo __('Update Criteria','wprs'); ?></a>
                        <?php if (isset($_GET["update_criteria"])) {
									// update user criteria rating
									if (function_exists('wprs_update_criteria')){wprs_update_criteria();}
								} ?>
                        </p>
                        <?php
						echo '<p><span class="description">'.$field['desc'].'</span></p>';
					break;
					
					// colorpicker
					case 'colorpicker':
						echo '<input type="text" class="color" name="wprs_options['.$field['id'].']" id="wprs_options['.$field['id'].']" value="'.$wprs_options[$field['id']].'" size="30" />
								<span class="description">'.$field['desc'].'</span>';
					break;
					
					// spacer
					case 'spacer':
						echo '<div style="height: 10px; border-bottom: dotted 2px #ECEBEB;"></div>';
					break;
					
					// custom post type
					case 'cpt':	
						// builtin types needed
						$builtin = array(
							'post',
							'page',
						);
						// all CPTs.
						$cpts = get_post_types( array(
							'public'   => true,
							'_builtin' => false
						) );
						// merge Builtin types and 'important' CPTs to resulting array to use as argument.
						$post_types = array_merge($builtin, $cpts);
						// create the check boxes
						foreach ($post_types as $post_type ) {
							if( isset( $wprs_options[$field['id'].$post_type] ) ) {$meta = $wprs_options[$field['id'].$post_type];} else {$meta = '';}
							echo '<input type="checkbox" name="wprs_options['.$field['id'].$post_type.']'.'" id="wprs_options['.$field['id'].$post_type.']'.'" ',
								  $meta != '' ? ' checked="checked"' : '',' />
								  <label for="wprs_options['.$field['id'].$post_type.']'.'"><span style="margin-right:10px;">'.$post_type.'</span></label>';
						}
						echo '<br /><br /><span class="description">'.$field['desc'].'</span>';
					break;
					
					// update user rating / reviews
					case 'update_user_rating':
						?>
                        <p>
                        <a href="admin.php?page=wprs&update_rating=true" onclick="return confirm('Are you sure?')" class="button-secondary">
                        <i class="fa fa-refresh" style="margin-right:8px;"></i><?php echo __('Update User Reviews','wprs'); ?></a>
                        <?php if (isset($_GET["update_rating"])) {
									// update user rating
									if (function_exists('wprs_update_user_rating')){wprs_update_user_rating();}
								} ?>
                        </p>
                        <?php
						echo '<p><span class="description">'.$field['desc'].'</span></p>';
					break;
					
					// note
					case 'note':
						echo '<div style="padding:10px;margin:0;width:60%;background-color:#FCF8E3;border-color:#FBEED5;color:#C09853;border-radius:4px;">';
						echo '<p style="margin:0;"><span class="description">'.$field['desc'].'</span></p>';
						echo '</div>';
					break;
					
					// reset api
					case 'reset_api':
						echo '<div style="padding:10px;width:60%;background-color:#FFEFEF;border-color:#EED3D7;color:#B94A48;border-radius:4px;">';
						echo '<p style="color:#339933;"><span class="fa fa-power-off"></span> Plugin is active</p>';
						echo '<p><span class="icon-info-sign"></span> Use this feature only if you want to remove the plugin from your WordPress site.</p><br />';
        				echo 'Remove the validation key and options here ';
						?>
                        <input type="submit" class="button" onclick="return confirm('Are you sure?')" value="Reset" name="reset"/>
                        <?php
						echo '</div>';
					break;
					
					// Reset vote IPs
					case 'reset_vote_ips':
						?>
                        <p>
                        <a href="admin.php?page=wprs&reset_vote_ips=true" onclick="return confirm('Are you sure?')" class="button-secondary">
                        <i class="fa fa-refresh" style="margin-right:8px;"></i><?php echo __('Reset Vote IPs','wprs'); ?></a>
                        <?php if (isset($_GET["reset_vote_ips"])) {
									// Delete post meta
									delete_post_meta_by_key( '_wprs_post_user_rating_ips' );
								} ?>
                        </p>
                        <?php
						echo '<p><span class="description">'.$field['desc'].'</span></p>';
					break;
					
					// Reset vote IPs
					case 'reset_vote_all_data':
						?>
                        <p>
                        <a href="admin.php?page=wprs&reset_vote_all_data=true" onclick="return confirm('Are you sure?')" class="button-secondary">
                        <i class="fa fa-refresh" style="margin-right:8px;"></i><?php echo __('Reset Vote IPs','wprs'); ?></a>
                        <?php if (isset($_GET["reset_vote_all_data"])) {
									// Delete post meta
									delete_post_meta_by_key( '_wprs_post_user_rating_ips' );
									delete_post_meta_by_key( '_wprs_post_user_rating' );
									delete_post_meta_by_key( '_wprs_post_user_rating_all' );
									delete_post_meta_by_key( '_wprs_post_user_rating_count' );
									delete_post_meta_by_key( '_wprs_post_user_rating_array' );
								} ?>
                        </p>
                        <?php
						echo '<p><span class="description">'.$field['desc'].'</span></p>';
					break;
					
					// Misc
					case 'misc':
					?>
					<!-- start of insideer -->
                    
                    <div style="float:left; margin-left:10px; margin-right:60px;">
					<?php if (wprs_admin_links()) {echo wprs_admin_links;} // Extra admin links ?>
                    </div><!-- end of links box -->
                    
                    <div style="float:left; margin-right:60px; margin-top:20px;">
                    <!-- Place this tag where you want the +1 button to render -->
					<div class="g-plusone" data-size="tall" data-annotation="inline" data-width="250" data-href="http://authorhreview.com/"></div>
    				
                    <div class="clr"><br></div>
                    
                    <!-- Twitter follow us button -->
            		<div style="margin: auto;">
						<a href="https://twitter.com/authorhreview"
            			class="twitter-follow-button"
            			data-show-count="true"
       		    	 	data-lang="en"
            			data-size="normal">Follow @AuthorhReview</a>
						<script>!function(d,s,id)
							{var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id))
								{js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}
								(document,"script","twitter-wjs");
						</script>
					</div>   
                    <!-- end of Twitter follow us button -->  
                    </div><!-- end of second social box -->
                    
                    <div style="float:left; margin-top:20px;">
                    <!-- Facebook like and send buttons -->
                    <div id="fb_warper">
                    	<div class="fb-like" ref="wprs-dashboard" data-href="http://authorhreview.com/" data-send="true" data-width="250" data-show-faces="true" data-font="arial"></div>
					</div>
                    <!-- Facebook like and send buttons -->
                    </div><!-- end of third social box -->

            </div>
            <!-- end of insideer -->
            
            	
        <!-- for facebook like -->
        <div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
    FB.init({
      appId      : '301654169919795', // App ID
      channelUrl : 'http://authorhreview.com/channel.html', // Channel File
      status     : true, // check login status
      cookie     : true, // enable cookies to allow the server to access the session
      xfbml      : true  // parse XFBML
    });

    // Additional initialization code here
  };

  // Load the SDK Asynchronously
  (function(d){
     var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     ref.parentNode.insertBefore(js, ref);
   }(document));
</script>

	<!-- G+ render -->
<script type="text/javascript">
  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
</script>
            <?php
            break;
            
				} //end switch
		}
		echo '</td></tr>';
		
		
		// End a tab
		if( $field['type'] == 'tab_end') {
			echo '</table>';
			echo '</div>';
		}
		
	} // end foreach
	
	
	wprs_help_center();
	
	echo '</div>'; // End Div tab container
}


