<?php
add_action( 'admin_init', 'imwb_zonpress_theme_products_init' );
add_action( 'admin_menu', 'imwb_zonpress_theme_products_add_page' );

require_once ( get_template_directory() . '/modules/amazon.php' ); 
require_once ( get_template_directory() . '/modules/commissionjunction.php' );  
require_once ( get_template_directory() . '/modules/ebay.php' );  

/**
 * Init plugin options to white list our options
 */
function imwb_zonpress_theme_products_init(){
	register_setting( 'imwb_zonpress_products', 'imwb_zonpress_theme_products', 'imwb_zonpress_theme_products_validate' );
	wp_register_script( 'imwb_zonpress-theme-products-script', get_template_directory_uri().'/js/admin_products.js' );
	wp_register_script( 'imwb_zonpress-theme-search-products-script', get_template_directory_uri().'/js/admin_search_products.js' );
}

/**
 * Load up the menu page
 */
function imwb_zonpress_theme_products_add_page() {
	
	$page = add_menu_page( __( 'CSB Products', 'imwb_zonpress' ), __( 'CSB Products', 'imwb_zonpress' ), 'edit_theme_options', 'imwb_zonpress_theme_products', 'imwb_zonpress_theme_products_do_page', null, 61 );
	
	/* 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_products_scripts' );
   
   $page= add_submenu_page('imwb_zonpress_theme_products', __( 'Settings', 'imwb_zonpress' ), __( 'Settings', 'imwb_zonpress' ), 'edit_theme_options', 'imwb_zonpress_theme_products', 'imwb_zonpress_theme_products_do_page');	

   add_action( 'admin_print_styles-' . $page, 'imwb_zonpress_admin_styles' );
   add_action( 'admin_print_scripts-' . $page, 'imwb_zonpress_admin_products_scripts' );
   
   $page= add_submenu_page('imwb_zonpress_theme_products', __( 'Search For Products', 'imwb_zonpress' ), __( 'Search For Products', 'imwb_zonpress' ), 'edit_theme_options', 'imwb_zonpress_theme_products-search', 'imwb_zonpress_theme_products_do_search');	

   add_action( 'admin_print_styles-' . $page, 'imwb_zonpress_admin_styles' );
   add_action( 'admin_print_scripts-' . $page, 'imwb_zonpress_admin_search_products_scripts' );
}

function imwb_zonpress_admin_products_scripts() {
   wp_enqueue_script('imwb_zonpress-theme-products-script');
}

function imwb_zonpress_admin_search_products_scripts() {
   wp_enqueue_script('imwb_zonpress-theme-search-products-script');
   
   wp_localize_script('imwb_zonpress-theme-search-products-script', 'IMWB_ZP_Search_Products', array( 'nonce' =>  wp_create_nonce( "imwb_zonpress_theme_products_search" ), 'admin_url' => admin_url( "admin-ajax.php" )));
}

function imwb_zonpress_update_products_option($element, $value) {

   $defaults = imwb_zonpress_get_default_theme_products_options();

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

function imwb_zonpress_get_products_option($element) {
	
   $defaults = imwb_zonpress_get_default_theme_products_options();
	
	$imwb_zonpress_current_products_options = get_option('imwb_zonpress_theme_products', $defaults);

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

function imwb_zonpress_get_products_options() {
	
   $defaults = imwb_zonpress_get_default_theme_products_options();
	
	$imwb_zonpress_current_products_options = get_option('imwb_zonpress_theme_products', $defaults);

   return $imwb_zonpress_current_products_options;
}

/**
 * Returns the default product options for the theme
 *
 */
function imwb_zonpress_get_default_theme_products_options() {
	$default_theme_products_options = array(
   'createtags' => 'N',
   'badtags' => 'all,and,here,this,that,then,make,what,which,where,when,does,with,while,your,other,will',
   'addcomments' => 'N',
   'randcomments' => 'N',
   'amzaffid' => '',
   'amzpubkey' => '',
   'amzprikey' => '',
   'amzregion' => 'com',
   'amzincfeatures' => 'N',
   'amzpricetoson' => 'Y',
   'amzpriceupdate' => 'Y',
   'cjdevkey' => '',
   'cjwebpid' => '',
   'cjadvertiserids' => 'J',
   'cjcids' => '',
   'ebayid' => '',
   'ebayappid' => '',
   'ebaysiteid' => '0'
	);

	return $default_theme_products_options;
}

$region_options = array(
		    			"com" => array("label" =>  "US (default)"),
		    			"co.uk" => array("label" => "United Kingdom"),
		    			"ca" => array("label" => "Canada"),
		    			"cn" => array("label" => "China"),
  						"fr" => array("label" => "France"),
		    			"de" => array("label" => "Germany"),
		    			"in" => array("label" => "India"),
                  "it" => array("label" => "Italy"),		    
		    			"co.jp" => array("label" => "Japan"),
		    			"es" => array("label" => "Spain")); 		  
		    			
$ebay_country_options = array("0" => array("label" => "United States"),
                     	 "3" => array("label" => "United Kingdom"),
                      	 "2" => array("label" => "Canada"),
                       	 "210" => array("label" => "Canada (French)"),
                     	 "15" => array("label" => "Australia"),
                     	 "16" => array("label" => "Austria"),
                     	 "123" => array("label" => "Belgium (Dutch)"),                     	 
                     	 "23" => array("label" => "Belgium (French)"),
                     	 "223" => array("label" => "China"),                     	 
                     	 "71" => array("label" => "France"),
                     	 "77" => array("label" => "Germany"),
                      	 "201" => array("label" => "Hong Kong"),
                     	 "100" => array("label" => "eBay Motors"),
                     	 "203" => array("label" => "India"),                     	 
                     	 "205" => array("label" => "Ireland"),                           	 
                     	 "101" => array("label" => "Italy"),
                     	 "146" => array("label" => "Netherlands"),
                     	 "186" => array("label" => "Spain"),
                     	 "193" => array("label" => "Switzerland"),
                     	 "196" => array("label" => "Taiwan")); 
		    			  			
		    			
$currency_symbols = Array('AUD' => '$',
                        'BWP'  => 'Pu',
                        'CAD'  => '$',
                        'DKK'  => 'kr',
                        'GBP'  => '£',
                        'HKD'  => 'HK$',
                        'EUR'  => '€',
                        'INR'  => '₹',
                        'NGN'  => '₦',
                        'PHP'  => 'Php',
                        'USD'  => '$',
                        'ZAR'  => 'R',
                        'ZWD'  => 'Z$',
                        'JPY'  => '￥',
                        'CNY'  => '￥',
                        'CHF'  => 'CHF',
                        'TWD'  => 'TW$');
                        
$region_currency_symbols = array('com' => "$",
              		    			   'co.uk' => "£",
               		    			'ca' => "$",
               		    			'cn' => '￥',
  						               'fr' => '€',
		    			               'de' => '€',
                                 'it' => '€',		    
		    			               'co.jp' => '￥',
		    			               'es' => '￥'); 
//US
$searchIndex_options['com'] = Array("All" => "All", "Apparel" => "Apparel", "Appliances" => "Appliances", "ArtsAndCrafts" => "ArtsAndCrafts", "Automotive" => "Automotive", "Baby" => "Baby", "Beauty" => "Beauty", "Books" => "Books", "Classical" => "Classical", "Collectibles" => "Collectibles", "DigitalMusic" => "DigitalMusic", "Grocery" => "Grocery", "DVD" => "DVD", "Electronics" => "Electronics", "HealthPersonalCare" => "HealthPersonalCare", "HomeGarden" => "HomeGarden", "Industrial" => "Industrial", "Jewelry" => "Jewelry", "KindleStore" => "KindleStore", "Kitchen" => "Kitchen", "LawnAndGarden" => "LawnAndGarden", "Magazines" => "Magazines", "Merchants" => "Merchants", "Miscellaneous" => "Miscellaneous", "MobileApps" => "MobileApps", "MP3Downloads" => "MP3Downloads", "Music" => "Music", "MusicalInstruments" => "MusicalInstruments", "MusicTracks" => "MusicTracks", "OfficeProducts" => "OfficeProducts", "OutdoorLiving" => "OutdoorLiving", "PCHardware" => "PCHardware", "PetSupplies" => "PetSupplies", "Photo" => "Photo", "Shoes" => "Shoes", "Software" => "Software", "SportingGoods" => "SportingGoods", "Tools" => "Tools", "Toys" => "Toys", "UnboxVideo" => "UnboxVideo", "VHS" => "VHS", "Video" => "Video", "VideoGames" => "VideoGames", "Watches" => "Watches", "Wireless" => "Wireless", "WirelessAccessories" => "WirelessAccessories");
//UK
$searchIndex_options['co.uk'] = Array("All" => "All","Apparel" => "Apparel","Automotive" => "Automotive","Baby" => "Baby","Beauty" => "Beauty","Books" => "Books","Classical" => "Classical","DVD" => "DVD","Electronics" => "Electronics","Grocery" => "Grocery","HealthPersonalCare" => "HealthPersonalCare","HomeGarden" => "HomeGarden","Jewelry" => "Jewelry","KindleStore" => "KindleStore","Kitchen" => "Kitchen","Lighting" => "Lighting", "MP3Downloads" => "MP3Downloads","Music" => "Music","MusicalInstruments" => "MusicalInstruments","MusicTracks" => "MusicTracks","OfficeProducts" => "OfficeProducts","OutdoorLiving" => "OutdoorLiving","Outlet" => "Outlet","Shoes" => "Shoes","Software" => "Software","SoftwareVideoGames" => "SoftwareVideoGames","Toys" => "Toys","VHS" => "VHS","Video" => "Video","VideoGames" => "VideoGames","Watches" => "Watches");
//JP
$searchIndex_options['co.jp'] = Array("All" => "All","Apparel" => "Apparel","Appliances" => "Appliances","Automotive" => "Automotive","Baby" => "Baby","Beauty" => "Beauty","Books" => "Books","Classical" => "Classical","DVD" => "DVD","Electronics" => "Electronics","ForeignBooks" => "ForeignBooks","Grocery" => "Grocery","HealthPersonalCare" => "HealthPersonalCare","Hobbies" => "Hobbies","HomeImprovement" => "HomeImprovement","Jewelry" => "Jewelry","KindleStore" => "KindleStore","Kitchen" => "Kitchen","MobileApps" => "MobileApps","MP3Downloads" => "MP3Downloads","Music" => "Music","MusicalInstruments" => "MusicalInstruments","MusicTracks" => "MusicTracks","OfficeProducts" => "OfficeProducts","Shoes" => "Shoes","Software" => "Software","SportingGoods" => "SportingGoods","Toys" => "Toys","VHS" => "VHS","Video" => "Video","VideoGames" => "VideoGames","Watches" => "Watches");
//IT
$searchIndex_options['it'] = Array("All" => "All","Automotive" => "Automotive","Baby" => "Baby","Books" => "Books","DVD" => "DVD","Electronics" => "Electronics","ForeignBooks" => "ForeignBooks","Garden" => "Garden","KindleStore" => "KindleStore","Kitchen" => "Kitchen","Lighting" => "Lighting","MP3Downloads" => "MP3Downloads","Music" => "Music","Shoes" => "Shoes","Software" => "Software","Toys" => "Toys","VideoGames" => "VideoGames","Watches" => "Watches");
//FR
$searchIndex_options['fr'] = Array("All" => "All","Apparel" => "Apparel","Automotive" => "Automotive","Baby" => "Baby","Beauty" => "Beauty","Books" => "Books","Classical" => "Classical","DVD" => "DVD","Electronics" => "Electronics","ForeignBooks" => "ForeignBooks","HealthPersonalCare" => "HealthPersonalCare","HomeImprovement" => "HomeImprovement","Jewelry" => "Jewelry","KindleStore" => "KindleStore","Kitchen" => "Kitchen","Lighting" => "Lighting","MP3Downloads" => "MP3Downloads","Music" => "Music","MusicalInstruments" => "MusicalInstruments","MusicTracks" => "MusicTracks","OfficeProducts" => "OfficeProducts","Outlet" => "Outlet","PetSupplies" => "PetSupplies","Shoes" => "Shoes","Software" => "Software","SoftwareVideoGames" => "SoftwareVideoGames","VHS" => "VHS","Video" => "Video","VideoGames" => "VideoGames","Watches" => "Watches");
//ES
$searchIndex_options['es'] = Array("All" => "All","Automotive" => "Automotive","Baby" => "Baby","Books" => "Books","DVD" => "DVD","Electronics" => "Electronics","ForeignBooks" => "ForeignBooks","KindleStore" => "KindleStore","Kitchen" => "Kitchen","MP3Downloads" => "MP3Downloads","Music" => "Music","Shoes" => "Shoes","Software" => "Software","Toys" => "Toys","VideoGames" => "VideoGames","Watches" => "Watches");
//DE
$searchIndex_options['de'] = Array("All" => "All","Apparel" => "Apparel","Automotive" => "Automotive","Baby" => "Baby","Beauty" => "Beauty","Books" => "Books","Classical" => "Classical","DVD" => "DVD","Electronics" => "Electronics","ForeignBooks" => "ForeignBooks","Grocery" => "Grocery","HealthPersonalCare" => "HealthPersonalCare","HomeGarden" => "HomeGarden","Jewelry" => "Jewelry","KindleStore" => "KindleStore","Kitchen" => "Kitchen","Lighting" => "Lighting","Magazines" => "Magazines","MP3Downloads" => "MP3Downloads","Music" => "Music","MusicalInstruments" => "MusicalInstruments","MusicTracks" => "MusicTracks","OfficeProducts" => "OfficeProducts","OutdoorLiving" => "OutdoorLiving","Outlet" => "Outlet","PCHardware" => "PCHardware","Photo" => "Photo","Software" => "Software","SoftwareVideoGames" => "SoftwareVideoGames","SportingGoods" => "SportingGoods","Tools" => "Tools","Toys" => "Toys","VHS" => "VHS","Video" => "Video","VideoGames" => "VideoGames","Watches" => "Watches");
//CN
$searchIndex_options['cn'] = Array("All" => "All","Apparel" => "Apparel","Appliances" => "Appliances","Automotive" => "Automotive","Baby" => "Baby","Beauty" => "Beauty","Books" => "Books","Electronics" => "Electronics","Grocery" => "Grocery","HealthPersonalCar" => "HealthPersonalCare","Home" => "Home","HomeImprovement" => "HomeImprovement","Jewelry" => "Jewelry","KindleStore" => "KindleStore","Misc" => "Misc","Music" => "Music","OfficeProducts" => "OfficeProducts","PetSupplies" => "PetSupplies","Photo" => "Photo","Shoes" => "Shoes","Software" => "Software","SportingGoods" => "SportingGoods","Toys" => "Toys","Video" => "Video","VideoGames" => "VideoGames","Watches" => "Watches");
//CA
$searchIndex_options['ca'] = Array("All" => "All","Baby" => "Baby","Beauty" => "Beauty","Books" => "Books","Classical" => "Classical","DVD" => "DVD","Electronics" => "Electronics","ForeignBooks" => "ForeignBooks","HealthPersonalCare" => "HealthPersonalCare","KindleStore" => "KindleStore","Kitchen" => "Kitchen","LawnAndGarden" => "LawnAndGarden","Music" => "Music","PetSupplies" => "PetSupplies","Software" => "Software","SoftwareVideoGames" => "SoftwareVideoGames","VHS" => "VHS","Video" => "Video","VideoGames" => "VideoGames");
//IN
$searchIndex_options['in'] = Array("Books" => "Books","DVD" => "DVD","Electronics" => "Electronics");  		    			               
                        
/**
 * Create the options page
 */
function imwb_zonpress_theme_products_do_page() {
   global $region_options, $ebay_country_options;
   
	?>
	
	<div class="wrap">
	
	<div id="imwb_plugin_options_editor">
      <div class="icon32" id="icon-link-manager"><br></div>
		<?php echo "<h2>" . __( 'Product Settings', 'imwb_zonpress' ) . ''; ?>
<?php if(isset($_REQUEST['page']) && $_REQUEST['page'] == 'imwb_zonpress_theme_products' && isset($_REQUEST['imwb_covertstorecontent_pro_update_cache'])) : 
      imwb_zonpress_theme_products_update_amazon_cache(true);
      echo '<div class="imwb_cabar_active_panel"><p><strong>'.__( 'Amazon Product Advertising Content Cache Updated', 'imwb_zonpress' ).'</strong></p></div>';
 elseif (isset($_REQUEST['page']) && $_REQUEST['page'] == 'imwb_zonpress_theme_products' && 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; ?>		
		<form method="post" action="">
<?php if(imwb_zonpress_get_products_option('amzpriceupdate') == 'Y' && imwb_zonpress_get_products_option('amzpubkey') !='' && imwb_zonpress_get_products_option('amzprikey') != '') { ?>
		<div class="imwb_cabar_active_panel">
		<p><strong><?php _e( 'Amazon Product Advertising Content Cache Update.', 'imwb_zonpress' ); ?></strong></p>
		<p><?php _e( 'Next scheduled cache update is', 'imwb_zonpress' ); ?>
		<?php 
		$nextRun = wp_next_scheduled('imwb_zonpress_amazon_cron_event');
		echo date_i18n(get_option('date_format') ,$nextRun+get_option( 'gmt_offset' ) * 3600).' at ';
		echo date_i18n(get_option('time_format') ,$nextRun+get_option( 'gmt_offset' ) * 3600);
		?>
		 <input class="button-primary" type="submit" name="imwb_covertstorecontent_pro_update_cache" value="<?php _e('Update Now', 'imwb_covertstorecontent') ?>" />
		 </p>
		</div>
<?php } ?>		
			<?php settings_fields( 'imwb_zonpress_products' ); ?>
         <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 width="400px"><?php _e( 'Automatically create Tags', 'imwb_zonpress' ); ?><br><small><?php _e('(Tags 3 characters or less are ignored)', 'imwb_zonpress' ); ?></small></td>
 				 	 <td><input id="imwb_zonpress_theme_products[createtags]" type="checkbox" name="imwb_zonpress_theme_products[createtags]" value="Y" <?php echo imwb_zonpress_get_products_option('createtags') == "Y" ? "checked='Yes'" : "" ?> /> 
 				 	</td>
 				</tr> 
 				<tr><td width="400px"><?php _e( 'Don\'t Create These Tags', 'imwb_zonpress' ); ?></td>
 					 <td><textarea id="imwb_zonpress_theme_products[badtags]" name="imwb_zonpress_theme_products[badtags]" cols=80 rows=5><?php echo imwb_zonpress_get_products_option('badtags') ?></textarea>
 					</td>
 				</tr> 
 				<tr><td width="400px"><?php _e( 'Add any available comments to post', 'imwb_zonpress' ); ?></td>
 					 <td><input id="imwb_zonpress_theme_products_addcomments" type="checkbox" name="imwb_zonpress_theme_products[addcomments]" value="Y" <?php echo imwb_zonpress_get_products_option('addcomments') == "Y" ? "checked='Yes'" : "" ?> /> 
 					 </td>
 				</tr> 
 				<tr valign="top"><td width="400px"><?php _e( 'Randomize comments added to vary the number per post.', 'imwb_zonpress' ); ?></td>
 				<td><input id="imwb_zonpress_theme_products_randcomments" type="checkbox" name="imwb_zonpress_theme_products[randcomments]" value="Y" <?php echo imwb_zonpress_get_products_option('randcomments') == "Y" ? "checked='Yes'" : "" ?> />
 				</td>
 				</tr> 
          </tbody>
 			</table>
 			
 			<br>
 			<table class="widefat">
 			 <thead>
 			  <tr>
 			   <th scope="col" colspan="2"><?php _e( 'Amazon', 'imwb_zonpress' ); ?></th>
 			  </tr>
 			 </thead>
 			  <tbody style="display: table-row-group;">
 			  <tr valign="top"><td width="400px"><?php _e( 'Amazon Affiliate ID', 'imwb_zonpress' ); ?><br><small><?php _e('You will need to add your ID in order to earn commission', 'imwb_zonpress' ); ?></small></td>
       		<td><input id="imwb_zonpress_theme_products[amzaffid]" type="text" name="imwb_zonpress_theme_products[amzaffid]" value="<?php echo imwb_zonpress_get_products_option('amzaffid') ?>" size="30">
       		</td>	  
       	  </tr>
       	  <tr valign="top"><td width="400px"><?php _e( 'API Access Key ID', 'imwb_zonpress' ); ?><br><small><?php _e('Required to access Amazon API.', 'imwb_zonpress' ); ?> <a href="http://aws-portal.amazon.com/gp/aws/developer/account/index.html" target="_blank"><?php _e( 'Click Here', 'imwb_zonpress' ); ?></a> <?php _e( 'for more information', 'imwb_zonpress' ); ?></small></td>
       	  	<td><input id="imwb_zonpress_theme_products[amzpubkey]" type="text" name="imwb_zonpress_theme_products[amzpubkey]" value="<?php echo imwb_zonpress_get_products_option('amzpubkey') ?>" size="30">
       	  	</td>	  
       	  </tr>
       	  <tr valign="top"><td width="400px"><?php _e( 'API Secret Access Key', 'imwb_zonpress' ); ?><br><small><?php _e('Required to access Amazon API.', 'imwb_zonpress' ); ?> <a href="http://aws-portal.amazon.com/gp/aws/developer/account/index.html" target="_blank"><?php _e( 'Click Here', 'imwb_zonpress' ); ?></a> <?php _e( 'for more information', 'imwb_zonpress' ); ?></small></td>
       	  	<td><input id="imwb_zonpress_theme_products[amzprikey]" type="text" name="imwb_zonpress_theme_products[amzprikey]" value="<?php echo imwb_zonpress_get_products_option('amzprikey') ?>" size="30">
       	  	</td>	  
       	  </tr>
       	  <tr valign="top"><td width="400px"><?php _e( 'Region', 'imwb_zonpress' ); ?></td>
       	  	<td><select id="imwb_zonpress_theme_products[amzregion]" class="regular-text" type="text" name="imwb_zonpress_theme_products[amzregion]" />
       	  	<?php 
       	  	 foreach ($region_options as $key => $value) {
       	  	    $selected = (imwb_zonpress_get_products_option('amzregion') == $key) ? " selected" : "";
       	  	    echo "<option value='{$key}'{$selected}>{$value['label']}</option>";
       	  	 }
       	  	?>
       	  	</select>       	  	
       	  	</td>	  
       	  </tr>
       	  <tr><td width="400px"><?php _e( 'Include product features in description', 'imwb_zonpress' ); ?></td>
       	  	 <td><input id="imwb_zonpress_theme_products[amzincfeatures]" type="checkbox" name="imwb_zonpress_theme_products[amzincfeatures]" value="Y" <?php echo imwb_zonpress_get_products_option('amzincfeatures') == "Y" ? "checked='Yes'" : "" ?> /> 
       	  	 </td>
       	  </tr> 
       	  <tr><td width="400px"><?php _e( 'Show date/time stamp adjacent to pricing', 'imwb_zonpress' ); ?></td>
       	  	 <td><input id="imwb_zonpress_theme_products[amzpricetoson]" type="checkbox" name="imwb_zonpress_theme_products[amzpricetoson]" value="Y" <?php echo imwb_zonpress_get_products_option('amzpricetoson') == "Y" ? "checked='Yes'" : "" ?> /> 
       	  	 </td>
       	  </tr> 
       	  <tr><td width="400px"><?php _e( 'Refresh product prices every 24 hours or so', 'imwb_zonpress' ); ?></td>
       	  	 <td><input id="imwb_zonpress_theme_products[amzpriceupdate]" type="checkbox" name="imwb_zonpress_theme_products[amzpriceupdate]" value="Y" <?php echo imwb_zonpress_get_products_option('amzpriceupdate') == "Y" ? "checked='Yes'" : "" ?> /> 
       	  	 </td>
       	  </tr> 
 			  </tbody>
 			  </table>
 			  
 			  <br>
 			  <table class="widefat">
 			   <thead>
 			    <tr>
 			     <th scope="col" colspan="2"><?php _e( 'Commission Junction', 'imwb_zonpress' ); ?></th>
 			    </tr>
 			   </thead>
 			    <tbody style="display: table-row-group;">
 			    <tr valign="top"><td width="400px"><?php _e( 'Developer Key', 'imwb_zonpress' ); ?><br><small><?php _e('Required to access Commission Junction API', 'imwb_zonpress' ); ?></small></td>
 			  	<td><input id="imwb_zonpress_theme_products[cjdevkey]" type="text" name="imwb_zonpress_theme_products[cjdevkey]" value="<?php echo imwb_zonpress_get_products_option('cjdevkey') ?>" size="33">
 			  	</td>	  
 			    </tr>
            <tr valign="top"><td width="400px"><?php _e( 'Website PID', 'imwb_zonpress' ); ?><br><small><?php _e('Required to access Commission Junction API', 'imwb_zonpress' ); ?></small></td>
            	<td><input id="imwb_zonpress_theme_products[cjwebpid]" type="text" name="imwb_zonpress_theme_products[cjwebpid]" value="<?php echo imwb_zonpress_get_products_option('cjwebpid') ?>" size="33">
            	</td>	  
            </tr>
            <tr valign="top"><td width="400px"><?php _e( 'Advertiser Id\'s', 'imwb_zonpress' ); ?><br><small><?php _e('You may provide a list of one or more advertiser CIDs, separated by commas, to limit the results to a specific sub-set of merchants.', 'imwb_zonpress' ); ?></small></td>
            	<td><input id="imwb_zonpress_theme_products[cjcids]" type="text" name="imwb_zonpress_theme_products[cjcids]" value="<?php echo imwb_zonpress_get_products_option('cjcids') ?>" size="33">
            	</td>	  
            </tr>
            </tbody>
            </table>      

            <br>
            <table class="widefat">
             <thead>
              <tr>
               <th scope="col" colspan="2"><?php _e( 'eBay', 'imwb_zonpress' ); ?></th>
              </tr>
             </thead>
              <tbody style="display: table-row-group;">
              <tr valign="top"><td width="400px"><?php _e( 'Campaign ID', 'imwb_zonpress' ); ?><br><small><?php _e('You will need to add your ID in order to earn commission', 'imwb_zonpress' ); ?></small></td>
            	<td><input id="imwb_zonpress_theme_products[ebayid]" type="text" name="imwb_zonpress_theme_products[ebayid]" value="<?php echo imwb_zonpress_get_products_option('ebayid') ?>" size="33">
            	</td>	  
              </tr>
            <tr valign="top"><td width="400px"><?php _e( 'Application ID', 'imwb_zonpress' ); ?><br><small><?php _e('Required to access eBay API', 'imwb_zonpress' ); ?>. <?php _e('This is the application ID (AppID) you obtain from the', 'imwb_zonpress' ); ?> <a href="http://developer.ebay.com" target="_blank"><?php _e( 'eBay Developers Program', 'imwb_zonpress' ); ?> </a></small></td>
            
            	<td><input id="imwb_zonpress_theme_products[ebayappid]" type="text" name="imwb_zonpress_theme_products[ebayappid]" value="<?php echo imwb_zonpress_get_products_option('ebayappid') ?>" size="33">
            	</td>	  
            </tr>
            <tr valign="top"><td width="400px"><?php _e( 'Region', 'imwb_zonpress' ); ?></td>
            	<td><select id="imwb_zonpress_theme_products[ebaysiteid]" class="regular-text" type="text" name="imwb_zonpress_theme_products[ebaysiteid]" />
            	<?php 
            	 foreach ($ebay_country_options as $key => $value) {
            	    $selected = (imwb_zonpress_get_products_option('ebaysiteid') == $key) ? " selected" : "";
            	    echo "<option value='{$key}'{$selected}>{$value['label']}</option>";
            	 }
            	?>
            	</select>       	  	
            	</td>	  
            </tr>
            </tbody>
            </table>              
			<p class="submit">
				<input type="submit" class="button-primary" value="<?php _e( 'Update Settings', 'imwb_zonpress' ); ?>" />
			</p>
		</form>
		</div>
  </div>
	<?php
}

/**
 * Create the product search page
 */
function imwb_zonpress_theme_products_do_search() {
   global $region_options, $currency_symbols, $searchIndex_options;
?>
	<div class="wrap">
	
	<?php 
	// See if were importing products
	if(isset($_REQUEST['page']) && $_REQUEST['page'] == 'imwb_zonpress_theme_products-search' && isset($_REQUEST['action']) && $_REQUEST['action'] == 'import-products') {    
	
      $poststatus = $_REQUEST['submit'];
      $postcat = $_REQUEST['category'];

	   $errors = Array();
	   // See what network the products to import belong too
	   if(isset($_REQUEST['itemids'])) {
	      foreach ($_REQUEST['itemids'] as $network => $itemids) {
	
	         switch ($network) {
	            case 'Amazon': $amazon = new IMWB_Zonpress_module_amazon(imwb_zonpress_get_products_options(),$currency_symbols);
	                           $results = $amazon->import_items($itemids, $poststatus, $postcat);
	                           break;
               case 'Commission Junction': $cj = new IMWB_Zonpress_module_commissionjunction(imwb_zonpress_get_products_options(),$currency_symbols);
                              $results = $cj->import_items($itemids, $poststatus, $postcat);
                              break;	
               case 'eBay': $ebay = new IMWB_Zonpress_module_ebay(imwb_zonpress_get_products_options(),$currency_symbols);
                              $results = $ebay->import_items($itemids, $poststatus, $postcat);
                              break;	                           
	         }
	         
	         if(!empty($results)) 
   	         $errors = array_merge($errors, $results);
	      }
	   
	   }
      if(!empty($results)) {
	?>
      <div class="imwb_cabar_active_panel error"><p><strong><?php _e( 'The Following Errors Occured', 'imwb_zonpress' ); ?>:</strong><br>
      <?php 
         foreach($errors as $error)
            echo $error;
      ?>
      </p></div>	
	<?php } ?>
      <div class="imwb_cabar_active_panel"><p><strong>
      <?php if($poststatus == 'draft') 
          _e( 'Products have been imported and are available as draft posts for further refining and publishing', 'imwb_zonpress' );
        else
          _e( 'Products have been imported and are now live.', 'imwb_zonpress' );
      ?>    
            </strong></p></div>
   <?php }?>
	<div id="imwb_plugin_options_editor">
      <div class="icon32" id="icon-link-manager"><br></div>
		<?php echo "<h2>" . __( 'Search For Products', 'imwb_zonpress' ) . ''; ?>  			   	
		<table class="widefat">
		  <tbody style="display: table-row-group;">
			<tr>
			  <td width="200px"><h4><?php _e( 'Product Keyword', 'imwb_zonpress' ); ?></h4></td>
			  <td><input type="text" name="imwb_zonpress_theme_products[keyword]" value="" size="60"/> <span class="error keyword"></span></td>
			</tr>
		   <tr>
		     <td width="200px"><h4><?php _e( 'Affiliate Networks', 'imwb_zonpress' ); ?></h4></td>
		     <td>
            <?php if(imwb_zonpress_get_products_option('amzpubkey') !=""  && imwb_zonpress_get_products_option('amzprikey') != "") { ?>
		        <input id="imwb_zonpress_theme_products[networks]" type="checkbox" name="imwb_zonpress_theme_options[networks][]" value="A" /> <?php _e( 'Amazon', 'imwb_zonpress' ); ?>
		      <?php } ?>
            <?php if(imwb_zonpress_get_products_option('cjdevkey') !=""  && imwb_zonpress_get_products_option('cjwebpid') != "") { ?>
		      	<input id="imwb_zonpress_theme_products[networks]" type="checkbox" name="imwb_zonpress_theme_options[networks][]" value="C" /> <?php _e( 'Commission Junction', 'imwb_zonpress' ); ?>
		      <?php } ?>
		      <?php if(imwb_zonpress_get_products_option('ebayid') !=""  && imwb_zonpress_get_products_option('ebayappid') != "") { ?>
		      	<input id="imwb_zonpress_theme_products[networks]" type="checkbox" name="imwb_zonpress_theme_options[networks][]" value="E" /> <?php _e( 'eBay', 'imwb_zonpress' ); ?>
		      <?php } ?>
		          <span class="error networks"></span>
		     </td>
		   </tr>
<?php if(imwb_zonpress_get_products_option('amzpubkey') !=""  && imwb_zonpress_get_products_option('amzprikey') != "") { ?>
         <tr id="amzSearchIndex" class="hidden">
          <td width="200px"><h4><?php _e( 'Amazon Search Index', 'imwb_zonpress' ); ?></h4></td>
          <td>
          <select id="imwb_zonpress_theme_products[searchindex]" name="imwb_zonpress_theme_products[searchindex]">
          <?php 
           foreach ($searchIndex_options[imwb_zonpress_get_products_option('amzregion')] as $key => $label) {
              echo "<option value='{$key}'>{$label}</option>";
           }
          ?>
          </select>
          </td>
          </tr>
<?php } ?>		   		   
		   <tr>
		     <td width="200px"><h4><?php _e( 'Maximum Products Returned', 'imwb_zonpress' ); ?></h4></td>
		     <td><select id="imwb_zonpress_theme_products[retunred]" class="regular-text" type="text" name="imwb_zonpress_theme_products[retunred]" />
         		   <option value='5'>5</option>
         		   <option value='10' selected>10</option>
         		   <option value='15'>15</option>
         		   <option value='20'>20</option>
		        </select></td>
		   </tr>
		    </tbody>
		   </table>
		   
		   <p>
			   <input id="btnSearchProducts" type="button" class="button-primary" value="<?php _e( 'Search', 'imwb_zonpress' ); ?>" />
		   </p>
		   <form id="import-products" method="post" action="">
		   <input type='hidden' name='action' value='import-products'>
  		   <input type='hidden' name='submit' value='submit-draft'>
		   <table class="widefat product-searching">
		   	<tr>
		         <td class="indicator">
		            <span>Searching for products</span>
		            <img src="<?php echo get_template_directory_uri();?>/images/productloading.gif">
		            <span>Please Wait...</span>
		         </td>
		      </tr>
		   </table>
		   <table class="widefat product-results">
		   	<tr>
		         <td class="indicator">
                  <span>Searching for products</span>
                  <img src="<?php echo get_template_directory_uri();?>/images/productloading.gif">
                  <span>Please Wait...</span>
		         </td>
		      </tr>
		   </table>
		   
		   <p class="submit hidden">
		      <input type="button" class="button-primary pull-right" value="<?php _e( 'View More Products', 'imwb_zonpress' ); ?>" /><br>
<?php		   
            $dropdown_options = array(
            	'hide_empty' => 0,
            	'hierarchical' => 1,
            	'show_count' => 0,
            	'orderby' => 'name',
            	'selected' => 0,
            	'name' => 'category'
            );
?>
            <strong><?php _e( 'Category', 'imwb_zonpress' ); ?></strong><br>
            <select style="width:340px; height:auto;" size="10" multiple="multiple" name="category[]" id="category" >
				<?php echo csp_get_blog_categories(0); ?>
				</select>
            <br><br>	   			
		      <input id="submit-draft" type="submit" class="button-primary" value="<?php _e( 'Import Selected Products (Draft)', 'imwb_zonpress' ); ?>" />
  		      <input id="submit-live"  type="submit" class="button-primary" value="<?php _e( 'Import Selected Products (Live)', 'imwb_zonpress' ); ?>" />
		   </p>
		   
		   </form>
  	   </div>	
  </div>
	<?php
}


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

function imwb_zonpress_theme_products_validate( $input ) {

   if(!isset($input['amzpricetoson'])) 
      $input['amzpricetoson'] = 'N';
      
   if(!isset($input['amzpriceupdate'])) 
      $input['amzpriceupdate'] = 'N';
      
   $output = imwb_zonpress_get_default_theme_products_options();
   
   foreach ($input as $key => $value) {
		$output[$key] = trim($input[$key]);
	}

  	return $output;
 }


// See if were saving product settings
if(isset($_REQUEST['page']) && $_REQUEST['page'] == 'imwb_zonpress_theme_products' && isset($_REQUEST['action']) && $_REQUEST['action'] == 'update') {    

   // Save options
   $updatedOptions = imwb_zonpress_theme_products_validate($_REQUEST['imwb_zonpress_theme_products']);

   update_option('imwb_zonpress_theme_products', $updatedOptions);
   
}

/**
 * Stores the passed in image URL in the media library and set the posts featured image
 *
 */
function imwb_zonpress_theme_products_set_featured_image($postId, $imgUrl) {

   $response = wp_remote_get($imgUrl);
 
   if( is_wp_error( $response ) ) 
      return false;
        
   $filename = urldecode(basename( $imgUrl ));
   $filename = explode('?', $filename);
   
   $filename = sanitize_file_name($filename[0]);
   $mimeType = $response['headers']['content-type'];
           
   if(empty($filename)) {
    $filename = 'img_'.uniqid();
   }             
   
   // Check for file extentions
   $fileExt = pathinfo($filename, PATHINFO_EXTENSION);
          
   if(empty($fileExt)) {
      switch($mimeType) {
         case 'image/gif': $filename = $filename.".gif";
                         break;
         case 'image/png': $filename = $filename.".png";
                         break;
         case 'image/jpeg':
         case 'image/jpeg':
         case 'image/pjpeg':$filename = $filename.".jpg";
                         break;
      }
   }
   
//   echo "Filename to Use: ".$filename."<br>";             
   $upload = wp_upload_bits( $filename, null, $response['body'] );
   $filename = $upload['file'];
   
   $wp_filetype = wp_check_filetype(basename($filename), null );
   $wp_upload_dir = wp_upload_dir();
   $attachment = array(
     'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ), 
     'post_mime_type' => $wp_filetype['type'],
     'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
     'post_content' => '',
     'post_status' => 'inherit'
   );
   $attach_id = wp_insert_attachment( $attachment, $filename, $postId );
   // you must first include the image.php file
   // for the function wp_generate_attachment_metadata() to work
   require_once(ABSPATH . 'wp-admin/includes/image.php');
   $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
   wp_update_attachment_metadata( $attach_id, $attach_data );
   
   set_post_thumbnail( $postId, $attach_id );
   
   return true;
}

function imwb_zonpress_theme_products_get_tags($content, $badtags) {

	$contentTags = array();				
	$badtags =  explode(',', htmlspecialchars(stripslashes($badtags)));
	$badchars = array(",", ":", "(", ")", "]", "[", "?", "!", ";", "-", '"');
		
	$content = str_replace($badchars, "", $content);
		
  	$tags = explode(' ', $content);
			
	foreach ($tags as $key => $value) {
		if (strlen($value) > 3) {
			if (!in_array(strtolower($value), $badtags)) {
				$contentTags[] = $value;
			}
		}
	}

	return $contentTags;
}

/**
 * Randomly Generate a set of counts of $n length totaling $total
 * This is to spread the required posts over each selected network
 */
function imwb_zonpress_theme_products_rand_posts($n, $total) {

   for($i = 0; $i<$n; $i++)
      $x[$i] =  mt_rand(1, 9) / 10;
   
   $k = $total / array_sum($x);
   
   for($i = 0; $i<$n; $i++)
      $rv[$i] = floor($x[$i] * $k);
      
   $rv[mt_rand(0, $n-1)] += ($total-array_sum($rv));

   return $rv;

}

/*
 * Called by cron job to update the amazon product price
 *
 */
function imwb_zonpress_theme_products_update_amazon_cache($showErrors = false) {
   global $wpdb, $currency_symbols;
   
   if(imwb_zonpress_get_products_option('amzpriceupdate') != 'Y')
      return;
   
   $wpdb->hide_errors();
 
   $yesterday = time()-3600*24;
   
   $num_products = $wpdb->query( $wpdb->prepare("SELECT SQL_CALC_FOUND_ROWS ".$wpdb->prefix."posts.ID, wpm1.meta_value AS ASIN FROM ".$wpdb->prefix."posts INNER JOIN ".$wpdb->prefix."postmeta wpm1 ON (".$wpdb->prefix."posts.ID = wpm1.post_id) AND (wpm1.meta_key = %s)
                    LEFT OUTER JOIN ".$wpdb->prefix."postmeta wpm2 ON (".$wpdb->prefix."posts.ID = wpm2.post_id) AND (wpm2.meta_key = %s )
                    WHERE 1=1 AND post_status = 'publish' AND DATE_SUB(CURDATE(),INTERVAL 1 DAY)  > post_date
                    AND wpm2.meta_value IS NULL OR wpm2.meta_value < %d", 
                    'imwb_cc_amazon_asin', '_imwb_cc_amazon_asin_updated', $yesterday) );

   $errors = Array();

   if($num_products > 0) {

     $amazon = new IMWB_Zonpress_module_amazon(imwb_zonpress_get_products_options(),$currency_symbols);
     
     foreach($wpdb->last_result as $product) {
         $result = $amazon->update_item($product->ID, $product->ASIN);
         if(is_array($result) && $showErrors) {
            echo '<div class="imwb_cabar_active_panel alert-error"><p>'.$result["error"]["message"].'</p></div>';
         }
         
     }
   }
   
   $wpdb->show_errors();
}

function imwb_zonpress_theme_products_update_amazon_cache_filter_where( $where = '' ) {
	// posts for March 1 to March 15, 2010
	$where .= " AND DATE_SUB(CURDATE(),INTERVAL 1 DAY)  > post_date";
	return $where;
}

/*
 * Search for products AJAX funtion
 *
 */
function imwb_zonpress_theme_products_search() {
   global $currency_symbols;
   
   $keyword = stripslashes($_REQUEST['keyword']);
   $num_posts = $_REQUEST['numPosts'];
   $nonce = $_REQUEST['nonce'];
   $networks = $_REQUEST['networks'];
   $amzPage = $_REQUEST['amzpage'];
   $amzIndex = $_REQUEST['amzIndex'];
   $cjPage = $_REQUEST['cjpage'];
   $ebayPage = $_REQUEST['ebaypage'];   

   // check to see if the submitted nonce matches with the
   // generated nonce we created earlier
   if ( ! wp_verify_nonce( $nonce, 'imwb_zonpress_theme_products_search' ) )
      die ( 'Busted!');
   
   $aResponse['errors'] = Array(); 
   $aResponse['results'] = Array();
   
   // Randomise the number of requested posts over the selected networks
   $networkPosts = imwb_zonpress_theme_products_rand_posts(count($networks), $num_posts);
   $hiddenFields = "";

   // Do Amazon Search   
   if(in_array('A', $networks)) {
   
      $amazon = new IMWB_Zonpress_module_amazon(imwb_zonpress_get_products_options(), $currency_symbols);
   
      $results = $amazon->search($keyword, array_shift($networkPosts), $amzPage, $amzIndex);
      if(isset($results["error"])) 
         $aResponse['errors'].= "<tr><td colspan='7'><div class='alert alert-error'><strong>".$results["error"]["module"].":</strong> ".$results["error"]["message"]."</div></td></tr>";
      elseif(isset($results["results"])) {
         $aResponse['results'][]  = $results["results"];
         $hiddenFields.= '<input type="hidden" name="amzpage" value="'.$results["next_page"].'">';
      }
   }
   
   // Do Commission Junction search
   if(in_array('C', $networks)) {
   
      $cj = new IMWB_Zonpress_module_commissionjunction(imwb_zonpress_get_products_options(), $currency_symbols);
   
      $results = $cj->search($keyword, array_shift($networkPosts), $cjPage);
      if(isset($results["error"])) 
         $aResponse['errors'].= "<tr><td colspan='7'><div class='alert alert-error'><strong>".$results["error"]["module"].":</strong> ".$results["error"]["message"]."</td></tr>";
      elseif(isset($results["results"])) {
         $aResponse['results'][]  = $results["results"];
         $hiddenFields.= '<input type="hidden" name="cjpage" value="'.$results["next_page"].'">';
      }
   }
   
   // Do eBay search
   if(in_array('E', $networks)) {
   
      $ebay = new IMWB_Zonpress_module_ebay(imwb_zonpress_get_products_options(), $currency_symbols);
   
      $results = $ebay->search($keyword, array_shift($networkPosts), $ebayPage);
      if(isset($results["error"])) 
         $aResponse['errors'].= "<tr><td colspan='7'><div class='alert alert-error'><strong>".$results["error"]["module"].":</strong> ".$results["error"]["message"]."</td></tr>";
      elseif(isset($results["results"])) {
         $aResponse['results'][]  = $results["results"];
         $hiddenFields.= '<input type="hidden" name="ebaypage" value="'.$results["next_page"].'">';
      }
   }
   
   // Check for empty results and return no products found message
   
   // Build the table rows of the results  
   if(!empty($aResponse['results'])) {

      $table_results  = '<thead><tr>';
      $table_results .= '<th class="check-column"><input id="cb-select-all-products" type="checkbox">'.$hiddenFields.'</td>';
      $table_results .= '<th>Network</th>';
      $table_results .= '<th>Title</th>';
      $table_results .= '<th>Description</th>';
      $table_results .= '<th>Image</th>';                  
      $table_results .= '<th>Price</th>';  
      $table_results .= '<th></th>';        
      $table_results .= '</tr></thead>';  
      $table_results .= '<tbody>';  
      $i=0;
      foreach ($aResponse['results'] as $items) {
         foreach ($items as $itemid => $data) {
            $table_results .= ($i % 2 == 0) ? '<tr class="alternate">' : '<tr>';
            $table_results .= '<td><input class="cb-select-product" type="checkbox" value="'.$itemid.'" name="itemids['.$data['network'].'][]"></td>';
            $table_results .= '<td>'.$data['network'].'</td>';
            $table_results .= '<td>'.$data['title'].'</td>';
            $table_results .= '<td><div class="description">'.$data['desc'].'</div></td>';
            $table_results .= '<td><img src="'.$data['image'].'"></td>';
            $table_results .= '<td>'.$data['price'].'</td>';                  
            $table_results .= '<td><a href="'.$data['sourceUrl'].'" target="_blank">View&nbsp;Product</a></td>';  
            $table_results .= '</tr>';   
            $i++;    
         }
      }
      $table_results .= '</tbody>';        
      
      $aResponse['results'] = $table_results;
   }
      
      
   $aResponse['message'] = 'Search Complete';
   
   echo json_encode($aResponse);
   die();

}

?>