<?php
add_action( 'admin_init', 'imwb_zonpress_theme_ads_init' );
add_action( 'admin_menu', 'imwb_zonpress_theme_ads_add_page' );

/**
 * Init plugin options to white list our options
 */
function imwb_zonpress_theme_ads_init(){
	register_setting( 'imwb_zonpress_ads', 'imwb_zonpress_theme_ads', 'imwb_zonpress_theme_ads_validate' );
	wp_register_script( 'imwb_zonpress-theme-ads-script', get_template_directory_uri().'/js/admin_ads.js' );
}

/**
 * Load up the menu page
 */
function imwb_zonpress_theme_ads_add_page() {

	$page = add_theme_page( __( 'Theme Ads', 'imwb_zonpress' ), __( 'Theme Ads', 'imwb_zonpress' ), 'edit_theme_options', 'imwb_zonpress_theme_ads', 'imwb_zonpress_theme_ads_do_page' );
	
	/* Using registered $page handle to hook stylesheet loading */
   add_action( 'admin_print_styles-' . $page, 'imwb_zonpress_admin_styles' );
   add_action( 'admin_print_scripts-' . $page, 'imwb_zonpress_admin_ads_scripts' );
}

function imwb_zonpress_admin_ads_scripts() {
   wp_enqueue_script( 'farbtastic' );
   wp_enqueue_script('imwb_zonpress-theme-ads-script');
   
   wp_localize_script('imwb_zonpress-theme-ads-script', 'IMWB_ZP_Ads', array( 'curAdNum' => 1 ));
}

/**
 * Returns the next ad to be shown
 *
 * Passed a counter indicating the number of ads already shown, so we can avoid duplication
 *
 */
function imwb_zonpress_get_advert($ads_shown) {

   $numAds = imwb_zonpress_get_ads_option('numads');
   $orderby = imwb_zonpress_get_ads_option('orderby');
   $lastadshown = imwb_zonpress_get_ads_option('lastadshown');
     
   // Get them in order
   if($orderby == 1) {
      if(is_array($lastadshown)) $lastadshown = 0;
      $lastadshown++;
      if($lastadshown > $numAds)
         $lastadshown = 1;
         
      $adNum = imwb_zonpress_update_ads_option('lastadshown', $lastadshown);
   }
   // Or randomly
   else {
   
    $adshownarray = imwb_zonpress_get_ads_option('adshownarray');

    if(count($adshownarray) >= $numAds) {
       $adshownarray = Array();
       $adshownarray[$lastadshown] = 1;
    }
    $ads_array = array_fill ( 1, $numAds, 1 );
    $ads_array = array_diff_key($ads_array, $adshownarray);

    $ad_to_show = array_rand($ads_array);
    $adshownarray[$ad_to_show] = 1;

    imwb_zonpress_update_ads_option('adshownarray', $adshownarray);
    $adNum = imwb_zonpress_update_ads_option('lastadshown', $ad_to_show);
   }
   
   $result['title'] = imwb_zonpress_get_ads_option('adtitle_'.$adNum);
   $result['content'] = imwb_zonpress_get_ads_option('adcontent_'.$adNum);
   
   return $result;

}

function imwb_zonpress_update_ads_option($element, $value) {

   $defaults = imwb_zonpress_get_default_theme_ads_options();

   $current_ads_options = get_option('imwb_zonpress_theme_ads', $defaults);
   
   $current_ads_options[$element] = $value;
   
   update_option('imwb_zonpress_theme_ads', $current_ads_options);
   
   return $value;
}

function imwb_zonpress_get_ads_option($element) {
	
   $defaults = imwb_zonpress_get_default_theme_ads_options();
	
	$imwb_zonpress_current_ads_options = get_option('imwb_zonpress_theme_ads', $defaults);

   if(isset($imwb_zonpress_current_ads_options[$element]) && is_array($imwb_zonpress_current_ads_options[$element]))
      return $imwb_zonpress_current_ads_options[$element];
	else if(isset($imwb_zonpress_current_ads_options[$element]))
		return stripslashes($imwb_zonpress_current_ads_options[$element]); 
	else if ( isset($defaults[$element]) ) 
		return stripslashes($defaults[$element]); 
	else
		return false;
}

/**
 * Returns the default options for Twenty Eleven.
 *
 */
function imwb_zonpress_get_default_theme_ads_options() {
	$default_theme_ads_options = array(
  	   'numads' => '0',
  	   'adsperpage' => '0',
  	   'postsshownfrom' => '3',
  	   'postsshownto' => '5',  	   
  	   'orderby' => '1',
  	   'adtitle_1' => 'Advertisement',
  	   'adcontent_1' => '',
      'adtitle_2' => 'Advertisement',
      'adcontent_2' => '',
      'adtitle_3' => 'Advertisement',
      'adcontent_3' => '',
      'adtitle_4' => 'Advertisement',
      'adcontent_4' => '',
      'adtitle_5' => 'Advertisement',
      'adcontent_5' => '',
      'lastadshown' => 0,
      'adshownarray' => Array()
	);

	return $default_theme_ads_options;
}

$orderby_options = array(
	'1' => array('label' => __('In Order', 'imwb_zonpress')),
	'0' => array('label' => __('Random', 'imwb_zonpress'))
);


/**
 * Create the options page
 */
function imwb_zonpress_theme_ads_do_page() {
   global $orderby_options;
   
	?>
	
	<div class="wrap">
	<div id="imwb_plugin_header">
	<a href="http://imwealthbuilders.com" target="_blank"><img src="<?php echo get_template_directory_uri(). '/images/imwblogo.png';?>"></a>
	<span id="imwb_plugin_header_link"><a href="http://imwealthbuilders.com/newplugins" target="_blank">Click Here To See Our Latest WP Plugins</a></span>
	<h2>Covert Store Builder Theme</h2>
	<div style="clear: both"></div>
	</div>
   <?php if(isset($_REQUEST['page']) && $_REQUEST['page'] == 'imwb_zonpress_theme_ads' && isset($_REQUEST['action']) && $_REQUEST['action'] == 'update') : ?>
      <div class="imwb_cabar_active_panel"><p><strong><?php _e( 'Options saved', 'imwb_zonpress' ); ?></strong></p></div>
   <?php endif; ?>
	<div id="imwb_plugin_options_editor">
		
		<?php screen_icon(); echo "<h2>" . __( 'Theme Ads', 'imwb_zonpress' ) . ' - <small><a href="http://covertstorebuilder.com/help/std_help.html#ads" target="_blank">Click Here For Help</a></small></h2>'; ?>
	
		<form method="post" action="">
			<?php settings_fields( 'imwb_zonpress_ads' ); ?>
         <br>
         <table class="widefat">
          <thead>
           <tr>
            <th scope="col" colspan="2"><?php _e( 'Settings', 'imwb_zonpress' ); ?></th>
           </tr>
          </thead>
           <tbody style="display: table-row-group;">
           <tr><td colspan='2'><div class="imwb_cabar_active_panel">
           <?php _e( 'These settings allow you to setup ads that are shown on the home page interspersed between your posts. You specify how many ads to configure and how they are shown. Ads can be up to 300&nbsp;x&nbsp;440 in size.', 'imwb_zonpress' ); ?>
           </div></td></tr>
 				<tr><td width="350px"><?php _e( 'Number of Ads', 'imwb_zonpress' ); ?></td>
 				 	 <td>
 				 	 <select id="imwb_zonpress_theme_ads[numads]" class="regular-text" type="text" name="imwb_zonpress_theme_ads[numads]" />
 				 	 <?php 
 				 	  for($i = 0; $i < 6; $i++) {
 				 	     $selected = (imwb_zonpress_get_ads_option('numads') == $i) ? " selected" : "";
 				 	     echo "<option value='{$i}'{$selected}>{$i}</option>";
 				 	  }
 				 	 ?>
 				 	 </select>
 				 	</td>
 				</tr> 
 				<tr><td width="350px"><?php _e( 'Ads shown per Page', 'imwb_zonpress' ); ?></td>
 					 <td><input type="text" name="imwb_zonpress_theme_ads[adsperpage]" value="<?php echo esc_attr( imwb_zonpress_get_ads_option('adsperpage') ); ?>" size="5"/> <span id="error-msg" class="alertCol"></span>
 					</td>
 				</tr> 
 				<tr><td width="350px"><?php _e( 'Posts shown before ads', 'imwb_zonpress' ); ?></td>
 					 <td><?php _e( 'Between', 'imwb_zonpress' ); ?> <input type="text" name="imwb_zonpress_theme_ads[postsshownfrom]" value="<?php echo esc_attr( imwb_zonpress_get_ads_option('postsshownfrom') ); ?>" size="5"/> <?php _e( 'and', 'imwb_zonpress' ); ?> <input type="text" name="imwb_zonpress_theme_ads[postsshownto]" value="<?php echo esc_attr( imwb_zonpress_get_ads_option('postsshownto') ); ?>" size="5"/> <span id="error-msg" class="alertCol"></span>
 					</td>
 				</tr> 
 				<tr valign="top"><td width="350px"><?php _e( 'Show Ads', 'imwb_zonpress' ); ?></td>
 				<td>
 					<select id="imwb_zonpress_theme_ads[orderby]" class="regular-text" type="text" name="imwb_zonpress_theme_ads[orderby]" />
 					<?php 
 					 foreach ($orderby_options as $key => $value) {
 				       $selected = (imwb_zonpress_get_ads_option('orderby') == $key) ? " selected" : "";
 					    echo "<option value='{$key}'{$selected}>{$value['label']}</option>";
 					 }
 					?>
 					</select>
 				</td>
 				</tr> 
          </tbody>
 			</table>
 			
 		   <div id="zp-ads-wrapper" <?php echo imwb_zonpress_get_ads_option('numads') == 0 ? 'class="hidden"' : '';?>>
 			
 			<div class="icon32" id="icon-edit-pages"><br></div>
 			<h2 class="imwb-nav-tab-wrapper">
 			<?php
 			for($i = 1; $i <= 5; $i++) {
 			?>
 			<a id="zp_ad_<?php echo $i;?>" href="#zp_ad_<?php echo $i;?>" class="imwb-nav-tab <?php echo $i == 1 ? "imwb-nav-tab-active" : "";?> <?php echo $i > imwb_zonpress_get_ads_option('numads') ? "hidden" : "";?>"><?php echo _e( 'Ad Widget ', 'imwb_zonpress' ).' '.$i;?></a>
 			<?php
 			}
 			?>
 			</h2>
 			<?php
 			for($i = 1; $i <= 5; $i++) {
 			?>
 			  <input type="hidden" name="imwbZonPressAd_Title[<?php echo $i;?>]" value="<?php echo imwb_zonpress_get_ads_option('adtitle_'.$i); ?>">
 			  <textarea name="imwbZonPressAd_Content[<?php echo $i;?>]" style="display: none"><?php echo imwb_zonpress_get_ads_option('adcontent_'.$i); ?></textarea>
 			<?php 
 			}
 			?>
 			<div id="imwb_nav_panel" class="imwb_nav_panel_entry">
 			<h3>Title</h3>
 			<input type=text name="imwbZonPressAd_TitleFld" style="width: 40%;" value="<?php echo imwb_zonpress_get_ads_option('adtitle_1'); ?>">
 			<h3>Content</h3> 
 			 <textarea name="imwbZonPressAd_ContentFld" rows="20" style="width: 99%;"><?php echo imwb_zonpress_get_ads_option('adcontent_1'); ?></textarea>
 			
 			</div>
 			</div>
 			
			<p class="submit">
				<input type="submit" class="button-primary" value="<?php _e( 'Save Ads', 'imwb_zonpress' ); ?>" />
			</p>
		</form>
		</div>
  </div>
	<?php
}

/**
 * Sanitize and validate input. Accepts an array, return a sanitized array.
 */

function imwb_zonpress_theme_ads_validate( $input ) {
   $output = imwb_zonpress_get_default_theme_ads_options();
   
   foreach ($input as $key => $value) {
		$output[$key] = trim($input[$key]);
	}

  	return $output;
 }


// See if were saving theme options
if(isset($_REQUEST['page']) && $_REQUEST['page'] == 'imwb_zonpress_theme_ads' && isset($_REQUEST['action']) && $_REQUEST['action'] == 'update') {    

   // Save options
   $updatedOptions = imwb_zonpress_theme_ads_validate($_REQUEST['imwb_zonpress_theme_ads']);

   for($i = 1; $i <= 5; $i++) {   
      $updatedOptions['adtitle_'.$i] = $_POST['imwbZonPressAd_Title'][$i];
   	$updatedOptions['adcontent_'.$i] = $_POST['imwbZonPressAd_Content'][$i];
   }  

   update_option('imwb_zonpress_theme_ads', $updatedOptions);
   
}

?>