<?php
define('IMWB_ZONPRESS_VERSION', '1.4');

require_once ( get_template_directory() . '/theme-options.php' );
require_once ( get_template_directory() . '/theme-ads.php' );
require_once ( get_template_directory() . '/theme-products.php' );  
require_once ( get_template_directory() . '/csscolor.php' );
require_once ( get_template_directory() . '/widget.php' );

add_action("after_setup_theme", "imwb_zonpress_setup");
add_action('switch_theme', 'imwb_zonpress_theme_deactivation'); 
add_action("widgets_init", "imwb_zonpress_widgets_init");
add_action('wp_head','imwb_zonpress_head',50);
add_action( 'wp_footer', 'imwb_zonpress_footer', 50 );
add_filter('imwb_zonpress_filter_content', 'imwb_zonpress_content_filter', 10, 2);
add_filter('excerpt_more', 'imwb_zonpress_excerpt_more');
add_filter('excerpt_length', 'imwb_zonpress_excerpt_length');
add_filter( 'show_admin_bar', '__return_false' );
add_filter('wpseo_whitelist_permalink_vars', 'imwb_zonpress_wpseo_whitelist_vars');
	
if (!is_admin()) {
   add_action('wp_enqueue_scripts', 'imwb_zonpress_enqueue_scripts');
   add_action( 'pre_get_posts', 'imwb_zonpress_posts_query' );
   add_filter('get_meta_sql', 'imwb_zonpress_meta_sql');   
} 
else {
   
   // Theme Update Check
   require_once('theme-admin-update.php');
   // Initialize Update Object
   $themeUpdate = new imwb_zonpress_Update('imwb_zonpress');	
   $themeUpdate->lastUpdateCheck();
   if($themeUpdate->update['latest_version'] > IMWB_ZONPRESS_VERSION)
      add_action('admin_notices', 'imwb_zonpress_admin_update_notice');
      
  	add_action('admin_head', 'imwb_zonpress_save_header_options');
      
   add_action( 'wp_ajax_update_ctr_action', 'imwb_zonpress_update_ctr' );
   add_action( 'wp_ajax_nopriv_update_ctr_action', 'imwb_zonpress_update_ctr' );
   add_action( 'wp_ajax_update_wishlist_action', 'imwb_zonpress_update_wishlist' );
   add_action( 'wp_ajax_nopriv_update_wishlist_action', 'imwb_zonpress_update_wishlist' );
   add_action( 'wp_ajax_delete_wishlist_action', 'imwb_zonpress_delete_wishlist' );
   add_action( 'wp_ajax_nopriv_delete_wishlist_action', 'imwb_zonpress_delete_wishlist' );
   
   add_action( 'wp_ajax_search_for_products', 'imwb_zonpress_theme_products_search' );
   
   add_filter('manage_posts_columns', 'imwb_zonpress_manage_post_add_column');
   add_action('manage_posts_custom_column', 'imwb_zonpress_manage_post_show_column', 5, 2);
}

   function imwb_zonpress_admin_update_notice(){
      GLOBAL $themeUpdate;
       
   }
	
	function imwb_zonpress_get_blogtitle() {
		wp_title("|", true, "right");
		bloginfo("name");
	}
	
	function imwb_zonpress_setup() {

      load_theme_textdomain( 'imwb_zonpress', get_template_directory() . '/languages' );

      add_theme_support("automatic-feed-links");
      add_theme_support("post-thumbnails");
      set_post_thumbnail_size( 300, 250, false );
      
      $bgDefaults = array(
      	'default-color' => 'ffffff'
      );
      
      $headerDefaults = array(
      	'default-image'          => '',
      	'random-default'         => false,
      	'width'                  => 970,
      	'height'                 => 130,
      	'default-text-color'     => '2C2C2C',
      	'header-text'            => true,
      	'uploads'                => true,
      	'admin-head-callback'    => 'imwb_zonpress_admin_header_style',
      	'admin-preview-callback' => 'imwb_zonpress_admin_header_image',
      );
      
      if ( imwb_zonpress_is_wp_version( '3.4' ) ) {
      	add_theme_support( 'custom-background', $bgDefaults); 
      	add_theme_support( 'custom-header', $headerDefaults);
      }
      else {
         define( 'HEADER_TEXTCOLOR', $headerDefaults['default-text-color'] );
         define( 'HEADER_IMAGE', '' );
         define( 'HEADER_IMAGE_WIDTH', $headerDefaults['width'] );
         define( 'HEADER_IMAGE_HEIGHT', $headerDefaults['height'] );
         add_custom_background( 'imwb_zonpress_custom_background_callback' );
         add_custom_image_header( $headerDefaults['wp-head-callback'], $headerDefaults['admin-head-callback'], $headerDefaults['admin-preview-callback'] );
         
      }
      
      add_action('custom_header_options', 'imwb_zonpress_custom_header_options');
      
		add_image_size( 'imwb-zonpress-carousel', 300, 250 );	
		add_image_size( 'imwb-zonpress-large-thumb', 153, 128 );	
		add_image_size( 'imwb-zonpress-cat-thumb', 170, 140 );	
		add_image_size( 'imwb-zonpress-small-thumb', 50, 50 );	
	}
	
	function imwb_zonpress_enqueue_styles() {
	   wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/css/bootstrap.css', false, '1.1');
	   wp_enqueue_style( 'theme-style', get_bloginfo( 'stylesheet_url' ), array('bootstrap'), '1.1');
	}
	
	function imwb_zonpress_enqueue_scripts() {
	   imwb_zonpress_enqueue_styles();
	
   	wp_enqueue_script( 'jquery' );
   	wp_enqueue_script( 'simplemodal', get_template_directory_uri() . '/js/jquery.simplemodal.1.4.4.min.js', array( 'jquery' ), '1.4.4');
   	wp_enqueue_script( 'bootstrap', get_template_directory_uri() . '/js/bootstrap.js', array( 'jquery' ), '1.1');
   	wp_enqueue_script( 'theme-script', get_template_directory_uri() . '/js/script.js', array( 'jquery' ), '1.1');
   	
   	wp_localize_script('theme-script', 'SimpleModalLoginL10n', array("empty_username" => __("The username field is empty.", 'imwb_zonpress' ), "empty_password" => __("The password field is empty.", 'imwb_zonpress' ), "empty_email" => __("The email field is empty.", 'imwb_zonpress' ), "empty_all" => __("All fields are required.", 'imwb_zonpress' ), "empty_firstname" => __("The first name field is empty.", 'imwb_zonpress' ), "empty_lastname" => __("The last name field is empty.", 'imwb_zonpress' ), 'carousel-interval' => (imwb_zonpress_get_option('delayrotator') > 0) ? imwb_zonpress_get_option('delayrotator') * 1000 : false ));
	}
	
	function imwb_zonpress_get_option($element) {
		
      $defaults = imwb_zonpress_get_default_theme_options();
		
		$imwb_zonpress_current_options = get_option('imwb_zonpress_theme_options', $defaults);
	
		if(isset($imwb_zonpress_current_options[$element]) && $imwb_zonpress_current_options[$element] == '#')
			return stripslashes($defaults[$element]); 		
      else if(isset($imwb_zonpress_current_options[$element]))
			return stripslashes($imwb_zonpress_current_options[$element]); 
		else if ( isset($defaults[$element]) ) 
			return stripslashes($defaults[$element]); 
		else
			return false;
	}
	
	function imwb_zonpress_widgets_init() {
	
   	register_sidebar(array(
   		 "name" => __( 'Featured Posts Sidebar', 'imwb_zonpress' )
   		,"id"	=> "sidebar-featured-widget"
   		,"description" => __( 'A 300x250 ad space that appears next to the featured post rotator.', 'imwb_zonpress' )
   		,"before_widget"=> '<li id="%1$s" class="widget-container %2$s">'
   		,"after_widget"	=> "</li>"
   		,"before_title"	=> "<h3 class=\"widget-title\">"
   		,"after_title"	=> "</h3>"
   	));
         
		register_sidebar(array(
			 "name"			=> "Single Post Sidebar"
			,"id"			=> "sidebar-post-widget"
			,"description" => __("An optional sidebar and widget area for use on single post's", 'imwb_zonpress' )
			,"before_widget"=> '<li id="%1$s" class="widget-container %2$s">'
			,"after_widget"	=> "</li>"
			,"before_title"	=> "<h3 class=\"widget-title\">"
			,"after_title"	=> "</h3>"
		));
		
		register_sidebar(array(
			 "name"			=> "Single Page Sidebar"
			,"id"			=> "sidebar-page-widget"
			,"description" => __("An optional sidebar and widget area for use on single page's", 'imwb_zonpress' )
			,"before_widget"=> '<li id="%1$s" class="widget-container %2$s">'
			,"after_widget"	=> "</li>"
			,"before_title"	=> "<h3 class=\"widget-title\">"
			,"after_title"	=> "</h3>"
		));
		
		register_sidebar(array(
			 "name"			=> "Category Page Sidebar"
			,"id"			=> "sidebar-catpage-widget"
			,"description" => __("An optional sidebar and widget area for use on category page's", 'imwb_zonpress' )
			,"before_widget"=> '<li id="%1$s" class="widget-container %2$s">'
			,"after_widget"	=> "</li>"
			,"before_title"	=> "<h3 class=\"widget-title\">"
			,"after_title"	=> "</h3>"
		));

      register_sidebar(array(
      	 "name"			=> "Wishlist Page Sidebar"
      	,"id"			=> "sidebar-wishlist-widget"
      	,"description" => __("An optional sidebar and widget area for use on category page's", 'imwb_zonpress' )
      	,"before_widget"=> '<li id="%1$s" class="widget-container %2$s">'
      	,"after_widget"	=> "</li>"
      	,"before_title"	=> "<h3 class=\"widget-title\">"
      	,"after_title"	=> "</h3>"
      ));
      
      		
		register_sidebar( array(
			 "name" => "Footer Area One"
			,"id" => "sidebar-footer-1"
			,"description" => __("An optional widget area for your site footer", 'imwb_zonpress' )
         ,"before_widget"=> '<li id="%1$s" class="widget-container %2$s">'
         ,"after_widget"	=> "</li>"
         ,"before_title"	=> "<h3 class=\"widget-title\">"
         ,"after_title"	=> "</h3>"
		) );
	
		register_sidebar( array(
      	 "name" => "Footer Area Two"
      	,"id" => "sidebar-footer-2"
      	,"description" => __("An optional widget area for your site footer", 'imwb_zonpress' )
         ,"before_widget"=> '<li id="%1$s" class="widget-container %2$s">'
         ,"after_widget"	=> "</li>"
         ,"before_title"	=> "<h3 class=\"widget-title\">"
         ,"after_title"	=> "</h3>"
      ) );
	
		register_sidebar( array(
      	 "name" => "Footer Area Three"
      	,"id" => "sidebar-footer-3"
      	,"description" => __("An optional widget area for your site footer", 'imwb_zonpress' )
         ,"before_widget"=> '<li id="%1$s" class="widget-container %2$s">'
         ,"after_widget"	=> "</li>"
         ,"before_title"	=> "<h3 class=\"widget-title\">"
         ,"after_title"	=> "</h3>"
      ) );

      $active_widgets = get_option( 'sidebars_widgets' );

	}
	
	/**
	 * Count the number of footer sidebars to enable dynamic classes for the footer
	 */
	function imwb_zonpress_footer_sidebar_class() {
		$count = 0;
	
		if ( is_active_sidebar( 'sidebar-footer-1' ) )
			$count++;
	
		if ( is_active_sidebar( 'sidebar-footer-2' ) )
			$count++;
	
		if ( is_active_sidebar( 'sidebar-footer-3' ) )
			$count++;
	
		$class = '';
	
		switch ( $count ) {
			case '1':
				$class = 'one';
				break;
			case '2':
				$class = 'two';
				break;
			case '3':
				$class = 'three';
				break;
		}
	
		if ( $class )
			echo 'class="' . $class . '"';
	}
	
	function imwb_zonpress_content_filter($content, $postImageSrc)
	{
	    if($postImageSrc == '')
   	    $content = preg_replace('#(<[/]?img.*>)#U', '', $content); 
	    else 
	       $content = preg_replace('#<\s*img.+src=["\']'.preg_quote($postImageSrc).'["\'].*>#Ui', '', $content); 
	       
	    return $content;
	}
	
	function imwb_zonpress_excerpt_length($length) {	   
	   if((is_home() || is_search()) && imwb_zonpress_get_option('postcontent') == 'C')
	      return imwb_zonpress_get_option('postchars');
	      
      return $length;
	}
	
	function imwb_zonpress_excerpt_more($more) {
	   global $post;
	   if(is_single())
	      return '';
	       
		return ' <a class="moretag" data-post-item="'.get_the_ID().'" href="'.get_permalink().'" '.imwb_zonpress_get_post_link_target().'>'.imwb_zonpress_get_option('postmoretext').'</a>';
	}
	
	function imwb_zonpress_strip_embed_code($text) {
	    $tags = array('iframe','object','embed','param');
	    foreach ($tags as $tag){
	        while(preg_match('/<'.$tag.'(|\W[^>]*)>(.*)<\/'. $tag .'>/iusU', $text, $found)){
	            $text = str_replace($found[0],$found[2],$text);
	        }
	    }

       $text =  preg_replace('/(<('.join('|',$tags).')(|\W.*)\/>)/iusU', '', $text);
       
       return $text;
	}
   
	
 /**
  * Works out the default post list order and returns it
  */	
 function imwb_zonpress_list_order() {
 
    $option = isset($_REQUEST['so']) ? $_REQUEST['so'] : 'def';
    
    // Use option settings is not already set
    if($option == 'def') {
    
       switch(imwb_zonpress_get_option('listorder')) {
          case '0': $option = 'trs';
                    break;
          case '1': $option = 'mrs';
                    break;        
          case '2': $option = 'hps';
                    break;   
          case '3': $option = 'lps';
                    break;                                 
       }
    }
    
    return $option;
 }

 /**
  * Alters the main home page query to sort by Most Rated/Viewed if selected
  */
 function imwb_zonpress_posts_query($query) {
 
    if( $query->is_main_query() && is_home()) {
             
       $query->set('posts_per_page', get_option('posts_per_page'));
       
       $hpexcludecats = imwb_zonpress_get_option('hpexcludecats');
       if(!empty($hpexcludecats)) {
          $cats = explode(",", htmlspecialchars($hpexcludecats));
          foreach ($cats as $key => $value) {
             $cats[$key] = "-".$value;
          }      
          $query->set('cat', implode(',', $cats));
       }
 
       $option = imwb_zonpress_list_order();

       switch ( strtolower($option) ) {
          case 'trs': $query->set( 'orderby', 'meta_value_num' );
                      $query->set( 'meta_key', '_imwb_zonpress_post_ctr' ); 
                      $query->set( 'order', 'DESC' );
                      break;
          case 'mrs': $query->set( 'orderby', 'date');
                      $query->set( 'order', 'DESC' );
                      break;  
          case 'hps': $query->set( 'orderby', 'meta_value_num' );
                      $query->set( 'meta_key', 'imwb_zonpress_post_price' ); 
                      $query->set( 'order', 'DESC' );
                      break;                 
          case 'lps': $query->set( 'orderby', 'meta_value_num' );
                      $query->set( 'meta_key', 'imwb_zonpress_post_price' ); 
                      $query->set( 'order', 'ASC' );
                      break;              
      }
    }
    else if( $query->is_main_query() && is_category()) {
       $query->set('posts_per_page', imwb_zonpress_get_option('postspercat'));
    }
    
 }
 
 /**
  * Alters the main home page meta query to first get posts that match the meta query, then
  * all other posts after that
  */
 function imwb_zonpress_meta_sql($clauses)
 {
     global $wp_query;
     
     if( $wp_query->is_main_query()) {
 
     // check for order by custom_order
        if (($wp_query->get('meta_key') == 'imwb_zonpress_post_price' || $wp_query->get('meta_key') == '_imwb_zonpress_post_ctr') && $wp_query->get('orderby') == 'meta_value_num')
        {   
            // change the inner join to a left outer join, 
            // and change the where so it is applied to the join, not the results of the query
            $clauses['join'] = str_replace('INNER JOIN', 'LEFT OUTER JOIN', $clauses['join']).$clauses['where'];
            $clauses['where'] = '';
        }
        return $clauses;
     }
 }
	
 /**
  * Post List, Meta Data Box and Custom fields
  *
  */
  
  function imwb_zonpress_manage_post_add_column( $columns ) {
     	return array_merge( $columns, 
     	              array('imp' => __('Imps', 'imwb_zonpress'),
     	                    'clicks' => __('Clicks', 'imwb_zonpress'),
     	                    'ctr' => __('CTR %', 'imwb_zonpress')) );  }
  
  function imwb_zonpress_manage_post_show_column( $column, $post_id) {
  
     switch ( $column ) {
	      case 'imp': 
		   case 'clicks': 
         case 'ctr': 
                     $imp = get_post_meta( $post_id, '_imwb_zonpress_post_imp', true );
                     $value = get_post_meta( $post_id, '_imwb_zonpress_post_'.$column, true );
                     break;             
     }
     
     if(empty($imp) || $imp == 0)
        echo "";
     else if($column == 'ctr')
        echo number_format($value, 2);
     else 
        echo $value;
  }
  
  add_action( 'load-post.php', 'imwb_zonpress_meta_boxes_setup' );
  add_action( 'load-post-new.php', 'imwb_zonpress_meta_boxes_setup' );
  
  function imwb_zonpress_meta_boxes_setup() {
  
  	   /* Add meta boxes on the 'add_meta_boxes' hook. */
  	   add_action( 'add_meta_boxes', 'imwb_zonpress_add_post_meta_boxes' );
  	   add_action( 'save_post', 'imwb_zonpress_save_post_bookmark_meta' );
  }
  
  function imwb_zonpress_add_post_meta_boxes() {
  
  	add_meta_box(
  		'imwb_zonpress-post-product',			// Unique ID
  		esc_html__( 'Product Details', 'imwb_zonpress' ),		// Title
  		'imwb_zonpress_post_product_meta_box',		// Callback function
  		'post',					// Admin page (or post type)
  		'normal',					// Context
  		'high'					// Priority
  	);
  	
  }
  
  function imwb_zonpress_post_product_meta_box( $object, $box ) {
  
  	wp_nonce_field( basename( __FILE__ ), 'imwb_zonpress-post-product_nonce' );
?> 
   <p>
	   <label for="imwb_zonpress_post-producturl"><?php _e('Product Url', 'imwb_zonpress');?>:</label>
		<input type="text" name="imwb_zonpress_post-producturl" id="imwb_zonpress_post-producturl" value="<?php echo esc_attr( get_post_meta( $object->ID, 'imwb_zonpress_post_producturl', true ) ); ?>" size="100" />
   </p> 
  	<p>
  		<label for="imwb_zonpress_post-price"><?php _e('Product Price', 'imwb_zonpress');?>:</label>
  		<input type="text" name="imwb_zonpress_post-price" id="imwb_zonpress_post-price" value="<?php echo esc_attr( get_post_meta( $object->ID, 'imwb_zonpress_post_price', true ) ); ?>" size="10" />
    </p> 	
    <p>
 		<label for="imwb_zonpress_post-currency"><?php _e('Currency:', 'imwb_zonpress');?></label>
 		<input type="text" name="imwb_zonpress_post-currency" id="imwb_zonpress_post-currency" value="<?php echo esc_attr( get_post_meta( $object->ID, 'imwb_zonpress_post_currency', true ) ); ?>" size="5" />
    </p> 	
    <p>
    <label for="imwb_zonpress_post-imp"><?php _e('Impressions', 'imwb_zonpress');?>:</label>	<input type="text" name="imwb_zonpress_post-imp" id="imwb_zonpress_post-imp" value="<?php echo esc_attr( get_post_meta( $object->ID, '_imwb_zonpress_post_imp', true ) ); ?>" size="10" />
 	   <label for="imwb_zonpress_post-clicks"><?php _e('Clicks', 'imwb_zonpress');?>:</label>	<input type="text" name="imwb_zonpress_post-clicks" id="imwb_zonpress_post-clicks" value="<?php echo esc_attr( get_post_meta( $object->ID, '_imwb_zonpress_post_clicks', true ) ); ?>" size="10" />
 	 </p>
  	 <div style="clear: both"></div>
<?php }
  
  function imwb_zonpress_save_post_bookmark_meta($post_id) {
  
    // verify if this is an auto save routine. 
    // If it is our form has not been submitted, so we dont want to do anything
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
        return;
        
  	/* Verify the nonce before proceeding. */
  	if ( !isset( $_POST['imwb_zonpress-post-product_nonce'] ) || !wp_verify_nonce( $_POST['imwb_zonpress-post-product_nonce'], basename( __FILE__ ) ) )
  		return $post_id;
  
   // Check permissions
   if ( 'page' == $_POST['post_type'] ) 
         return;
   else
   {
     if ( !current_user_can( 'edit_post', $post_id ) )
         return;
   }
   
   if(wp_is_post_revision($post_id))
      return;
    
	/* Get the posted data and update meta value */
	/* Product Url */
	$vc_meta_value = ( isset( $_POST['imwb_zonpress_post-producturl'] ) ? $_POST['imwb_zonpress_post-producturl'] : '' );
	if ( !update_post_meta( $post_id, 'imwb_zonpress_post_producturl', $vc_meta_value ) ) 
	   add_post_meta( $post_id, 'imwb_zonpress_post_producturl', $vc_meta_value, true );
	   
	/* Price */
	$vc_meta_value = ( isset( $_POST['imwb_zonpress_post-price'] ) ? $_POST['imwb_zonpress_post-price'] : '' );
   if(empty($vc_meta_value))
      $vc_meta_value = '0';
      
   if ( !update_post_meta( $post_id, 'imwb_zonpress_post_price', $vc_meta_value ) ) 
      add_post_meta( $post_id, 'imwb_zonpress_post_price', $vc_meta_value, true );
      
   /* Currency */
   $vc_meta_value = ( isset( $_POST['imwb_zonpress_post-currency'] ) ? $_POST['imwb_zonpress_post-currency'] : '' );
   if(empty($vc_meta_value))
      $vc_meta_value = '0';
      
   if ( !update_post_meta( $post_id, 'imwb_zonpress_post_currency', $vc_meta_value ) ) 
      add_post_meta( $post_id, 'imwb_zonpress_post_currency', $vc_meta_value, true );

   /* Impressions */
   $vc_imp_value = ( isset( $_POST['imwb_zonpress_post-imp'] ) ? $_POST['imwb_zonpress_post-imp'] : '0' );
   if(empty($vc_imp_value) || !is_numeric($vc_imp_value))
      $vc_imp_value = '0';
      
   if ( !update_post_meta( $post_id, '_imwb_zonpress_post_imp', $vc_imp_value ) ) 
      add_post_meta( $post_id, '_imwb_zonpress_post_imp', $vc_imp_value, true );
      	            
   /* Clicks */
   $vc_clicks_value = ( isset( $_POST['imwb_zonpress_post-clicks'] ) ? $_POST['imwb_zonpress_post-clicks'] : '0' );
   if(empty($vc_clicks_value) || !is_numeric($vc_clicks_value))
      $vc_clicks_value = '0';
      
   if ( !update_post_meta( $post_id, '_imwb_zonpress_post_clicks', $vc_clicks_value ) ) 
      add_post_meta( $post_id, '_imwb_zonpress_post_clicks', $vc_clicks_value, true );
      
   if(!empty($vc_imp_value)) 
      $ctr = ($vc_clicks_value / $vc_imp_value)*100;   
   else 
      $ctr = 0;

   if ( !update_post_meta( $post_id, '_imwb_zonpress_post_ctr', $ctr ) ) 
      add_post_meta( $post_id, '_imwb_zonpress_post_ctr', $ctr, true );
      
  }
  
  // checks is WP is at least a certain version (makes sure it has sufficient comparison decimals
  function imwb_zonpress_is_wp_version( $is_ver ) {
      $wp_ver = explode( '.', get_bloginfo( 'version' ) );
      $is_ver = explode( '.', $is_ver );
      for( $i=0; $i<=count( $is_ver ); $i++ )
          if( !isset( $wp_ver[$i] ) ) array_push( $wp_ver, 0 );
   
      foreach( $is_ver as $i => $is_val )
          if( $wp_ver[$i] < $is_val ) return false;
      return true;
  }
  
  function imwb_zonpress_custom_background_callback() {
  
      /* Get the background image. */
      $image = get_background_image();
      
      /* If there's an image, just call the normal WordPress callback. We won't do anything here. */
      if ( !empty( $image ) ) {
      	_custom_background_cb();
      	return;
      }
      
      /* Get the background color. */
      $color = get_background_color();
      
      /* If no background color, return. */
      if ( empty( $color ) ) {
         echo '<style type="text/css">body { background: url('.get_template_directory_uri() . '/images/background.png); }</style>';
      }
      
      /* Use 'background' instead of 'background-color'. */
      $style = "background: #{$color};";
      
      ?>
      <style type="text/css">body { <?php echo trim( $style ); ?> }</style>
      <?php
  
  }
  
  /**
   * Preview and Styles the header image displayed on the Appearance > Header admin panel.
   *
   */
   function imwb_zonpress_admin_header_image() { 	?>
   	<div id="headimg" style="background: url(<?php header_image(); ?>) no-repeat scroll top; background-size: 970px auto;">
   		<?php $style = ' style="color:#' . get_header_textcolor() . '; text-align:'.get_theme_mod( 'zp_header_text_align', 'center' ).'"'; ?>
   		<div class="hgroup">
   			<h1 id="name"<?php echo $style; ?>><?php bloginfo( 'name' ); ?></h1>
   			<h2 id="desc"<?php echo $style; ?>><?php bloginfo( 'description' ); ?></h2>
   		</div>
   	</div>
<?php }

  function imwb_zonpress_admin_header_style() {
  	$header_image = get_header_image();
  ?>
  <script>
  jQuery(document).ready(function($) {
     $('#zp_header_text_align').change(function(){
        $('#name').css('textAlign', $(this).val());
        $('#desc').css('textAlign', $(this).val());
     });  
  });
  </script>
  	<style type="text/css">
  	.appearance_page_custom-header #headimg {
  		border: none;
  		-webkit-box-sizing: border-box;
  		-moz-box-sizing:    border-box;
  		box-sizing:         border-box;
  		<?php
  		if ( ! empty( $header_image ) ) {
  			echo 'background: url(' . esc_url( $header_image ) . ') no-repeat scroll top; background-size: 1600px auto;';
  		} ?>
  		padding: 0 20px;
  	}
  	#headimg .hgroup {
  		-webkit-box-sizing: border-box;
  		-moz-box-sizing:    border-box;
  		box-sizing:         border-box;
  		margin: 0 auto;
  		max-width: 970px;
      min-height: 130px;
  		width: 100%;
  	}
  	<?php if ( ! display_header_text() ) : ?>
  	#headimg h1,
  	#headimg h2 {
  		position: absolute !important;
  		clip: rect(1px 1px 1px 1px); /* IE7 */
  		clip: rect(1px, 1px, 1px, 1px);
  	}
  	<?php endif; ?>
  	#headimg h1 {
  		font: bold 35px/1 "Helvetica Neue",Helvetica,Arial,sans-serif;
  		margin: 0;
  		padding: 15px 0 10px;
  	}
  	#headimg h1 a {
  		text-decoration: none;
  	}
  	#headimg h1 a:hover {
  		text-decoration: underline;
  	}
  	#headimg h2 {
      font-weight: 300;
      font-size: 15px;
  		margin: 0;
  		text-shadow: none;
  		line-height: 15px;
  		padding: 0px;
  	}
  	.default-header img {
  		max-width: 230px;
  		width: auto;
  	}
  	</style>
  <?php
  }
  
  function imwb_zonpress_custom_header_options() {
?>
  <table class="form-table">
  	<tbody>
  		<tr valign="top" class="hide-if-no-js displaying-header-text">
  			<th scope="row"><?php _e( 'Header Text Alignment', 'imwb_zonpress' ); ?>:</th>
  			<td>
  				<p>
  				<select name="zp_header_text_align" id="zp_header_text_align">
  				<option value="left" <?php echo get_theme_mod( 'zp_header_text_align', 'center' ) == 'left' ? 'selected' : '';?>><?php _e('Left', 'imwb_zonpress' );?></option>
  				<option value="center" <?php echo get_theme_mod( 'zp_header_text_align', 'center' ) == 'center' ? 'selected' : '';?>><?php _e('Center', 'imwb_zonpress' );?></option>
  				</select>
  				</p>
  			</td>
  		</tr>
  	</tbody>
  </table>
<?php  
  }
  
  function imwb_zonpress_save_header_options() {
     if ( isset( $_POST['zp_header_text_align'] ) ) {
  			// validate the request itself by verifying the _wpnonce-custom-header-options nonce
  			// (note: this nonce was present in the normal Custom Header form already, so we didn't have to add our own)
  			check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' );
  
  			// be sure the user has permission to save theme options (i.e., is an administrator)
  			if ( current_user_can('manage_options') )
  				set_theme_mod( 'zp_header_text_align', $_POST['zp_header_text_align'] );
  	  }
  	  return;
  }
  
  function imwb_zonpress_head() {
  
     imwb_zonpress_open_graph_head();
?>     
<script type="text/javascript">
	var imwbvp_ajaxurl = '<?php echo admin_url( 'admin-ajax.php' );?>';
// ]]>
</script>
<?php  
  }
  
  function imwb_zonpress_footer() {
      if ( is_feed())
         return;
      
  		echo "";
  
  }
  
  // build ogp meta
  function imwb_zonpress_open_graph_head() {
  
  	global $post;
  
	echo "\n<!-- Open Graph protocol meta data -->\n";
		
	// Which URL we need
	if (is_home() || is_front_page() || is_search() || is_category() )
		$ogp_url = get_bloginfo( 'url' );
	else 
		$ogp_url = 'http' . (is_ssl() ? 's' : '') . "://".$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
	
	echo '<meta property="og:url" content="' . esc_url($ogp_url) . '">' . "\n";
	
	// Site Title
	echo '<meta property="og:title" content="' . esc_attr( wp_title("|", false, "right").get_bloginfo( 'name' ) ) . '">' . "\n";
	
	//  Site Name
	echo '<meta property="og:site_name" content="' . get_bloginfo( 'name' ) . '">' . "\n";
	
	// Descriptions
	if ( is_single() || is_page() ) {
		if ( has_excerpt( $post->ID ) )
			$ogp_description = strip_tags( get_the_excerpt( $post->ID ) );
		else 
			$ogp_description = str_replace( "\r\n", ' ' , substr( strip_tags( strip_shortcodes( $post->post_content ) ), 0, 160 ) );
	} 
	else 
		$ogp_description = get_bloginfo( 'description' );
	
	echo '<meta property="og:description" content="' . esc_attr( $ogp_description ). '">' . "\n";
	
	// OG Type
	if ( is_single() || is_page()) {
		$ogp_type = 'article';
	} else {
		$ogp_type = 'website';
	}
	echo '<meta property="og:type" content="' . esc_attr($ogp_type) . '">' . "\n";
	
	// Find/output any images for use in the OGP tags
	$wpfbogp_images = array();
		
	// Image details
   if ( is_single() || is_page()) {
	
  /* 	$postImage = imwb_zonpress_get_the_image(Array('image_class' => 'tack_entry_img', "link_to_post" => false, 'echo' => false, 'size' => '', 'use_image_scan_link' => true));
	   preg_match_all( '|<img.*?src=[\'"](.*?)[\'"].*?>|i', $postImage, $matches );
   	$postImageSrc = $matches[1][0];
   */
   	 $postImageSrc = imwb_zonpress_post_thumbnail_img_src();  	
		echo '<meta property="og:image" content="' . esc_url($postImageSrc) . '">' . "\n";
	}
	else 
    	echo '<meta property="og:image" content="' . esc_url(imwb_zonpress_get_option('defOGPImg')) . '">' . "\n";
	
	// Locale
	echo '<meta property="og:locale" content="' . strtolower( esc_attr( get_locale() ) ) . '">' . "\n";
	echo "<!--  Open Graph protocol meta data  -->\n";

  }
  
   function imwb_zonpress_get_product_href($post_id = null) {
      // Get the post ID if none is provided
      if ( $post_id == null OR $post_id == '' ) $post_id = get_the_ID();
               
      $postLink = get_post_meta( $post_id, 'imwb_zonpress_post_producturl', true );
      
      if(empty($postLink))   
         $postLink = get_permalink();
   
      return $postLink;
   }
   
   function imwb_zonpress_get_post_link_target() {
      
      if(imwb_zonpress_get_option('linknewwin') == '1') 
         $target = " target='_blank'";
      else 
         $target = "";
         
      return $target;
   }
   
   function imwb_zonpress_is_product($post_id = null) {
      // Get the post ID if none is provided
      if ( $post_id == null OR $post_id == '' ) $post_id = get_the_ID();
      
      $postLink = get_post_meta( $post_id, 'imwb_zonpress_post_producturl', true );
      $price = get_post_meta( $post_id, 'imwb_zonpress_post_price', true );
      
      if(empty($postLink) && (empty($price) || $price == 0)) 
         return false;
         
      return true;
   }
   
   function imwb_zonpress_get_post_permalink($linkType = 'title', $post_id = null) {
      // Get the post ID if none is provided
      if ( $post_id == null OR $post_id == '' ) $post_id = get_the_ID();
      
      // See if product url attached to post
      $postLink = get_post_meta( $post_id, 'imwb_zonpress_post_producturl', true );
      if(empty($postLink) || imwb_zonpress_get_option($linkType.'links') == '1')   
         $postLink = get_permalink();
         
      return $postLink;
   } 	  
    	  	
  	/* 
  	 * Thumbnail Functions
  	 */

   function imwb_zonpress_the_post_thumbnail ( $post_id = null, $width = '170', $height = '140', $singlePost = false, $class = false  ) {
      echo imwb_zonpress_get_post_thumbnail($post_id, $width, $height, $singlePost, $class);
   
   }
   
   function imwb_zonpress_get_post_thumbnail ( $post_id = null, $width = '170', $height = '140', $singlePost = false, $class = false ) {

      // Get the post ID if none is provided
      if ( $post_id == null OR $post_id == '' ) $post_id = get_the_ID();
      
      $image_src = imwb_zonpress_post_thumbnail_img_src ( $post_id, $singlePost, $width, $height, $alt_attr);
      
      if(empty($image_src))
         return '';
      
      $attr = apply_filters( 'the_title', get_post_field( 'post_title', $post_id ) );
      
      if(!empty($height))
         $height = sprintf('height="%spx"',  $height);

      if(!empty($width))
         $width = sprintf('width="%spx"',  $width);
         
      if(!empty($class))
         $class = 'class="'.$class.'"';
         
      if(!empty($alt_attr))
         $alt_attr = ' alt="'.$alt_attr.'"';
   
//      return sprintf('<img %s src="%s" %s %s title="%s">', $class, $image_src, $width, $height,  $attr);
     return sprintf('<img %s src="%s" title="%s"%s>', $class, $image_src, $attr, $alt_attr);
   }
   
   function imwb_zonpress_post_thumbnail_img_src ( $post_id = null, $singlePost = false, $width = '170', $height = '140', &$alt_attr = '') {
   
      // Get the post ID if none is provided
      if ( $post_id == null OR $post_id == '' ) $post_id = get_the_ID();
   
      // If featured image set, use that one
      if(has_post_thumbnail($post_id)) {
         $post_thumbnail_id = get_post_thumbnail_id( $post_id );
         $image_attributes =  wp_get_attachment_image_src($post_thumbnail_id, Array($width, $height) );
         $alt_attr = trim(strip_tags( get_post_meta($post_thumbnail_id, '_wp_attachment_image_alt', true) ));
         return $image_attributes[0];
     }
     
     // If Single Post Page then see if Covert Content Generated post
//     if($singlePost) {
        $imgScan = false;

        $isCCT = get_post_meta( $post_id, 'imwb_cc_amazon_asin', true );   
        if(!empty($isCCT)) $imgScan = true;
        
        $isCCT = get_post_meta( $post_id, 'imwb_cc_flicker_pid', true );   
        if(!empty($isCCT)) $imgScan = true;
        
        if($imgScan) {        
           preg_match_all( '|<img.*?src=[\'"](.*?)[\'"].*?>|i', get_post_field( 'post_content', $args['post_id'] ), $matches );
           /* If there is a match for the image, return its URL. */
           if ( isset( $matches ) && !empty( $matches[1][0] ) )
              return $matches[1][0];
           else 
              return "";
        }
                
//     }
     
     // If Covert Socil Content image attached then use that one
     if( ( $thumbnail_meta = get_post_meta( $post_id, '_imwb_zonpress_post_image_url', true ) ) != '' ) {
        return $thumbnail_meta;
     }    

     // If Covert Video Content Thumbnail attached then use that one
     if( ( $thumbnail_meta = get_post_meta( $post_id, '_video_thumbnail', true ) ) != '' ) {
     	return $thumbnail_meta;
     }
     
     // See if custom image set in theme options
     if(imwb_zonpress_get_option('custdefaultimg') != '')
        return imwb_zonpress_get_option('custdefaultimg');
     
     // Else use default image
     return  get_template_directory_uri() .'/images/default.png';
   
   }
   
   /*
    * Page Numbers & Navigation Functions
    */
    function imwb_zonpress_page_numbers($range = 4) {
    	global $wp_query;
     
    	$big = 999999999; // This needs to be an unlikely integer
      $pages = $wp_query->max_num_pages;
      $paged = max( 1, get_query_var('paged'));
     
    	// For more options and info view the docs for paginate_links()
    	// http://codex.wordpress.org/Function_Reference/paginate_links
    	$paginate_links = paginate_links( array(
    		'base' => str_replace( $big, '%#%', get_pagenum_link($big) ),
    		'current' => $paged,
    		'total' => $pages,
    		'mid_size' => 5
    	) );
     
    	// Display the pagination if more than one page is found
    	if ( $paginate_links ) {
    	   echo '<div class="pagination_wrapper">';
    		echo '<div class="pagination"><span>Page '.$paged.' of '.$pages.'</span>';
    		echo $paginate_links;
    		echo '</div>';
    		echo '</div>';
    	}
    }   
    
    /**
     * Display the price for the current post.
     *
     */
    function imwb_zonpress_post_price($post_id = null) {
      global $region_currency_symbols;
    
    	// Get the post ID if none is provided
    	if ( $post_id == null OR $post_id == '' ) $post_id = get_the_ID();
    
    	$price = get_post_meta( $post_id, 'imwb_zonpress_post_price', true );
    	if(empty($price)) 
    	   $price = '0.0';
    	$currency = get_post_meta( $post_id, 'imwb_zonpress_post_currency', true );
    	if(empty($currency)) 
    	   $currency = $region_currency_symbols[imwb_zonpress_get_amazon_region()];
    	   
    	$amzAsin = get_post_meta( $post_id, 'imwb_cc_amazon_asin', true);
    	
    	if(imwb_zonpress_get_amazon_pricetoson() == 'Y' && !empty($amzAsin)) {
    	
       	$tzstring = get_option('timezone_string');
       	date_default_timezone_set($tzstring);
         $amzRegion = imwb_zonpress_get_amazon_region();
       	
    	   $postTime = get_post_meta( $post_id, '_imwb_cc_amazon_asin_updated', true);
    	   if(empty($postTime)) $postTime = get_post_time('U', true, $post_id);
    	   
    	   $date = date('d/m/Y', $postTime);
    	   if($date == date('d/m/Y')) 
    	      $date_fmt = get_option('time_format').' T';
    	   else
       	   $date_fmt = get_option('date_format').' '.get_option('time_format').' T';
       	   
      	echo '<span class="price">'.$currency.number_format($price,2).'</span>';
      	
      	
      	// Set back to UTC.
      	date_default_timezone_set('UTC');
      }
      else
       	echo '<span class="price">'.$currency.number_format($price,2).'</span>';
    } 
    
    function imwb_zonpress_get_amazon_region() {
       
    	 $product_options = get_option('imwb_zonpress_theme_products');
    	 if ($product_options === false)
    	    return 'com';
    	    
    	 return empty($product_options['amzregion']) ? 'com' : $product_options['amzregion'];
    }
    
    function imwb_zonpress_get_amazon_pricetoson() {
       
    	 $product_options = get_option('imwb_zonpress_theme_products');
    	 if ($product_options === false)
    	    return 'Y';
    	    
    	 return empty($product_options['amzpricetoson']) ? 'Y' : $product_options['amzpricetoson'];
    }
    
    function imwb_zonpress_update_imp($post_id = null) {
    
      // Get the post ID if none is provided
      if ( $post_id == null OR $post_id == '' ) $post_id = get_the_ID();
         
      $imp = get_post_meta( $post_id, '_imwb_zonpress_post_imp', true );
      if(empty($imp) || !is_numeric($imp))
          $imp = 1;
      else
          $imp++;
       
      if ( !update_post_meta( $post_id, '_imwb_zonpress_post_imp', $imp ) ) 
           add_post_meta( $post_id, '_imwb_zonpress_post_imp', $imp, true );        
       
      $clicks = get_post_meta( $post_id, '_imwb_zonpress_post_clicks', true );   
      if(empty($clicks))
       $clicks = 0;
            
      $ctr = ($clicks / $imp)*100;
      
      if ( !update_post_meta( $post_id, '_imwb_zonpress_post_ctr', $ctr ) ) 
           add_post_meta( $post_id, '_imwb_zonpress_post_ctr', $ctr, true );         
                      
      return true;
    }
        
    function imwb_zonpress_update_ctr() {
       $post_id = intval($_POST['postid']);

       $nonce = $_POST['nonce'];
    
       // check to see if the submitted nonce matches with the
       // generated nonce we created earlier
       if ( ! wp_verify_nonce( $nonce, 'imwb_zonpress_update_ctr' ) )
           die ( 'Busted!');
           
       $imp = get_post_meta( $post_id, '_imwb_zonpress_post_imp', true );
       if(empty($imp) || !is_numeric($imp))
           $imp = 1;
       
       $clicks = get_post_meta( $post_id, '_imwb_zonpress_post_clicks', true );   
       if(empty($clicks))
           $clicks = 1;    
       else
           $clicks++;    
           
       if ( !update_post_meta( $post_id, '_imwb_zonpress_post_clicks', $clicks ) ) 
           add_post_meta( $post_id, '_imwb_zonpress_post_clicks', $clicks, true );          
           
       $ctr = ($clicks / $imp)*100;
      
       if ( !update_post_meta( $post_id, '_imwb_zonpress_post_ctr', $ctr ) ) 
           add_post_meta( $post_id, '_imwb_zonpress_post_ctr', $ctr, true );  
                        
       $aResponse['ctr'] = $ctr;       
     
       echo json_encode($aResponse);
       die();
    }
    
    function imwb_zonpress_post_onwishlist($user_id, $post_id) {
    
      if($user_id == NULL) return false;
        
      $result = get_user_meta( $user_id, '_imwb_zonpress_user_wishlist', true );
      
      $wish_list = explode(",", $result);
      if(in_array($post_id,$wish_list))
         return true;
         
      return false;
    } 
    
    function imwb_zonpress_update_wishlist() {
       $post_id = intval($_POST['postid']);
       $user_id = intval($_POST['userid']);
     
       $nonce = $_POST['nonce'];
   
       // check to see if the submitted nonce matches with the
       // generated nonce we created earlier
       if ( ! wp_verify_nonce( $nonce, 'imwb_zonpress_update_wishlist' ) )
          die ( 'Busted!');
     
       $result = get_user_meta( $user_id, '_imwb_zonpress_user_wishlist', true );
       
       $wish_list = explode(",", $result);
       if(!in_array($post_id,$wish_list))
          $wish_list[] = $post_id;
          
       $count = count($wish_list)-1;
        
       $result = implode(",", $wish_list);  
       
       if ( !update_user_meta( $user_id, '_imwb_zonpress_user_wishlist', $result ) ) 
          add_user_meta( $user_id, '_imwb_zonpress_user_wishlist', $result, true ); 
                      
       $aResponse['message'] = $count;
       $aResponse['html'] = '<span class="wishlistlink">'.imwb_zonpress_get_option('onwishlisttext').'</span>';
      
       echo json_encode($aResponse);
       die();
    }
    
    function imwb_zonpress_delete_wishlist() {
       $post_id = intval($_POST['postid']);
       $user_id = intval($_POST['userid']);
     
       $nonce = $_POST['nonce'];
   
       // check to see if the submitted nonce matches with the
       // generated nonce we created earlier
       if ( ! wp_verify_nonce( $nonce, 'imwb_zonpress_delete_wishlist' ) )
          die ( 'Busted!');
     
       $result = get_user_meta( $user_id, '_imwb_zonpress_user_wishlist', true );
       
       $wish_list = explode(",", $result);
       foreach ($wish_list as $key => $value) { 
         if($value == $post_id)
            unset($wish_list[$key]);
       }          
       
       $count = count($wish_list)-1;
        
       $result = implode(",", $wish_list);  
       
       if ( !update_user_meta( $user_id, '_imwb_zonpress_user_wishlist', $result ) ) 
          add_user_meta( $user_id, '_imwb_zonpress_user_wishlist', $result, true ); 
                      
       $aResponse['message'] = $count;
      
       echo json_encode($aResponse);
       die();
    }    
    
    /*
     * Membership functions
     *
     */
   function imwb_zonpress_signin_user() {  
      $creds = array();
      
      $creds['user_login'] = $_REQUEST['log'];
      $creds['user_password'] = $_REQUEST['pwd'];
      if(isset($_REQUEST['rememberme']))
         $creds['remember'] = true;
      
     $user = wp_signon();
     
     if ( is_wp_error($user) ){
        $error_string = $user->get_error_message();
        $errors = '<div id="login_error">' . $error_string . "</div>\n";
        return $errors;
     }
     
     return '<div id="smcf-login-redirect">'.get_bloginfo( 'url' ).'</div>';
     
   }
   
   function imwb_zonpress_register_user() {
      $errors = Array();
    
      $firstname = $_REQUEST['firstname'];
      if(empty($firstname))
         $errors['firstname'] = __('Please Enter Your First Name', 'imwb_zonpress');
          
      $lastname = $_REQUEST['lastname'];
      if(empty($lastname))
         $errors['lastname'] = __('Please Enter Your Last Name', 'imwb_zonpress');
       
      $username = strtolower($_REQUEST['user_login']);
      if(empty($username))
         $errors['user_login'] = __('Please Enter a username', 'imwb_zonpress');
      else if (get_user_by('login', $username) !== false) 
         $errors['user_login'] = __('Username already in use', 'imwb_zonpress');
       
      $email = strtolower($_REQUEST['user_email']);
      if(empty($email))
         $errors['user_email'] = __('Please Enter a email', 'imwb_zonpress');
      else if (get_user_by('email', $email) !== false) 
         $errors['user_email'] = __('Email already in use', 'imwb_zonpress');
         
      $password = $_REQUEST['user_pass'];
      if(empty($password))
         $errors['password'] = __('Please Enter A Password', 'imwb_zonpress');         
   
      if(!empty($errors)) {
         $field_errors = "";
         foreach ($errors as $key => $value) {
            $field_errors .= '	' . $value . "<br>\n";
   
         }
         $errors = '<div id="login_error">' . $field_errors . "</div>\n";
         return $errors;
      }
         
      $user_data = array(
             'user_pass' => $password,
             'user_login' => $username,
             'user_nicename' => $firstname.' '.$lastname,
             'user_email' => $email,
             'display_name' => $firstname.' '.$lastname,
             'first_name' => $firstname,
             'last_name' => $lastname,
             'user_registered' => date('Y-m-d H:i:s', current_time('timestamp')),
             'role' => 'subscriber');
   
      $user_id = wp_insert_user($user_data);

      if (is_wp_error($user_id)) {
         $error_string = $user_id->get_error_message();
         $errors = '<div id="login_error">' . $error_string . "</div>\n";
         return $errors;
      }
               
      $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);   
      
      if(imwb_zonpress_get_option('newmemberadminmail') == '1') {
   
         $message  = sprintf(__('A new member has registered on your site %s:', 'imwb_zonpress'), $blogname) . "\r\n\r\n";
   	   $message .= sprintf(__('Username: %s', 'imwb_zonpress'), $username) . "\r\n\r\n";
         $message .= sprintf(__('E-mail: %s', 'imwb_zonpress'), $email) . "\r\n";
   
         @wp_mail(get_option('admin_email'), sprintf(__('[%s] New Member Registration Alert', 'imwb_zonpress'), $blogname), $message);
      }
   	
      if(imwb_zonpress_get_option('newmembermail') == '1') {
      
         $subject = imwb_zonpress_get_option('newmembermailsubj');
         $message = imwb_zonpress_get_option('newmembermailbody');
         
         $subject = str_replace('{SITE_NAME}', $blogname, $subject);
         $subject = str_replace('{SITE_URL}',  home_url( '/' ), $subject);
         $subject = str_replace('{USERNAME}',  $username, $subject);
         $subject = str_replace('{PASSWORD}',  $password, $subject);
   	   
         $message = str_replace('{SITE_NAME}', $blogname, $message);
         $message = str_replace('{SITE_URL}',  home_url( '/' ), $message);
         $message = str_replace('{USERNAME}',  $username, $message);
         $message = str_replace('{PASSWORD}',  $password, $message);   	 
         
         @wp_mail($email, $subject, $message);          
      }
      
      // Do any AR Stuff
      if(imwb_zonpress_get_option('newmemberaroption') == 'G') { // Get Response
         require_once ( get_template_directory() . '/getresponse-api/jsonRPCClient.php' ); 
         $GR_client = new jsonRPCClient('http://api2.getresponse.com');
         try {
              $result = $GR_client->add_contact(imwb_zonpress_get_option('getresponse_api_key'),
                              array ("campaign" =>  imwb_zonpress_get_option('getresponse_campaign'),
                                     "name" => $firstname.' '.$lastname,
                                     "email" => $email,
                                     "cycle_day" =>'0',
                                     "ip" => $_SERVER['REMOTE_ADDR']
                               ));
           } catch (Exception $e) { 
              //return '<div class="message">GetResponse API Error: '.$e->getMessage().'</div>'; 
           }
         
      }
      else if(imwb_zonpress_get_option('newmemberaroption') == 'A' && imwb_zonpress_get_option('aweber_auth_code') != '' && imwb_zonpress_get_option('aweber_consumer_key') != '') { // AWeber
      
            require_once ( get_template_directory() . '/aweber_api/aweber_api.php');      
      
            $aweber = new AWeberAPI(imwb_zonpress_get_option('aweber_consumer_key'), imwb_zonpress_get_option('aweber_consumer_secret'));
            
            try {
                $account = $aweber->getAccount(imwb_zonpress_get_option('aweber_access_key'), imwb_zonpress_get_option('aweber_access_secret'));
                $subs = $account->loadFromUrl('/accounts/'.$account->id.'/lists/'.imwb_zonpress_get_option('aweber_list'). '/subscribers');

                # create a subscriber
                $params = array(
                    'email' => $email,
                    'ip_address' => $_SERVER['REMOTE_ADDR'],
                    'ad_tracking' => 'covert store builder',
                    'name' => $firstname.' '.$lastname
                );

                $new_subscriber = $subs->create($params);
             
            } catch(AWeberAPIException $exc) {
               return '<div class="message"><h3>AWeberAPIException:</h3><li> Type: '.$exc->type.'<br><li> Msg : '.$exc->message.'<br><li> Docs: '.$exc->documentation_url.'<br><hr>';
            }
      }
      else if(imwb_zonpress_get_option('newmemberaroption') == 'I' || imwb_zonpress_get_option('newmemberaroption') == 'M'
               || imwb_zonpress_get_option('newmemberaroption') == 'O') {
      
         $ar_data = get_option('imwb_zonpress_theme_ar_data');
         
         foreach ($ar_data['form_data'] as $key => $value) {
				if($value == "%%EMAIL%%") $ar_data['form_data'][$key] = urldecode($email);
				if($value == "%%NAME%%") $ar_data['form_data'][$key] = urldecode($firstname.' '.$lastname);
				if($value == "%%FNAME%%") $ar_data['form_data'][$key] = urldecode($firstname);
				if($value == "%%LNAME%%") $ar_data['form_data'][$key] = urldecode($lastname);				
			}
			$args = array('method' => 'POST','timeout' => 45,'redirection' => 5,'httpversion' => '1.0','blocking' => true,'headers' => array(),'body' => $ar_data['form_data'],'cookies' => array());
         $response = wp_remote_post($ar_data['action'],$args);
      }
      
      return '<div class="message">'.__('Registration Complete', 'imwb_zonpress').'</div>';
    
    }
    
    /*
     * Filter to add permalink variables to Yoast WP SEO whitelist
     *
     */
    function imwb_zonpress_wpseo_whitelist_vars($vars) {
    
       $my_vars = array('so', 'action', 'submit-link-input');
       return array_merge($vars, $my_vars);
    }
    
/*
* Cron function
*
*/   
$imwb_zonpress_cron_checkPeriod = 4;
$imwb_zonpress_cron_scheduleName = 'every'.$imwb_zonpress_cron_checkPeriod.'hours';

add_filter('cron_schedules', 'imwb_zonpress_cron_addCustomSchedule');
 
function imwb_zonpress_cron_addCustomSchedule($schedules) {
   global $imwb_zonpress_cron_checkPeriod, $imwb_zonpress_cron_scheduleName;

	$schedules[$imwb_zonpress_cron_scheduleName] = array(
		'interval' => $imwb_zonpress_cron_checkPeriod * 3600, 
		'display' => sprintf('Every %d hours', $imwb_zonpress_cron_checkPeriod),
	);
	
	return $schedules;
}

add_action('imwb_zonpress_amazon_cron_event', 'imwb_zonpress_amazon_cron_Job');

if (!wp_next_scheduled('imwb_zonpress_amazon_cron_event')) {
	wp_schedule_event( current_time( 'timestamp' ), $imwb_zonpress_cron_scheduleName, 'imwb_zonpress_amazon_cron_event');
} 

function imwb_zonpress_amazon_cron_Job() {
   global $imwb_zonpress_cron_scheduleName;
   
   imwb_zonpress_theme_products_update_amazon_cache();

   if ( !wp_next_scheduled( 'imwb_zonpress_amazon_cron_event' ) ) {
	   wp_schedule_event( current_time( 'timestamp' ), $imwb_zonpress_cron_scheduleName, 'imwb_zonpress_amazon_cron_event');
   }
}

function imwb_zonpress_theme_deactivation() {
	wp_clear_scheduled_hook('imwb_zonpress_amazon_cron_event');
}    

/*
* RSS Feed functions
*/

add_action('rss2_ns', 'imwb_zonpress_yahoo_media_tag');
add_action('rss_item', 'imwb_zonpress_feed_item');
add_action('rss2_item', 'imwb_zonpress_feed_item');

function imwb_zonpress_yahoo_media_tag() {
	echo 'xmlns:media="http://search.yahoo.com/mrss/"';
}

function imwb_zonpress_feed_item($content) {
	global $post;
	
	$postImage = imwb_zonpress_post_thumbnail_img_src();
	
	$wp_filetype = wp_check_filetype(basename($postImage), null );
	    	
	if (!empty($postImage)) {   
		echo '<enclosure url="' . $postImage . '" type="'.$wp_filetype['type'].'" />';				
		echo '<media:content url="'.$postImage.'" width="170" height="140" medium="image" type="'.$wp_filetype['type'].'" />';
	}
}


//-----------------------------------------------------------------------------------------------------------------------
add_action('wp_dashboard_setup', 'bBox_add_dashboard_widgets' );
	function custom_dashboard_help() {
		echo '<div style="border-bottom:1px solid #ccc; padding-bottom:10px; margin-bottom:20px;">
				<p><a href="http://www.incomejamaica.aweber.com" target="_blank"><img src="'.get_template_directory_uri().'/images/aweber-logo.gif" style="float:right;" /></a><span style="color:#E66F00; font-size:16px;">30 day trial for only <strong>$1</strong></span></br>
Start building your email list and earn money!</br>
Visit the link below then click the green button "Order"</p>
<h3><a href="http://www.incomejamaica.aweber.com" target="_blank">CLICK HERE TODAY</a></h3>
			  </div>';
		echo '<div style="border-bottom:1px solid #ccc; padding-bottom:10px; margin-bottom:20px;">
				<p><span style="color:#E66F00; font-size:16px;">Password Tool</span></p>
				<p><a href="http://www.freepasswordtool.com" target="_blank"><img src="'.get_template_directory_uri().'/images/roboform-logo.gif" style="float:right;" /></a>Never forget another password</br>
(including the password for your website)</br>
Download your FREE password tool today!</p>
<h3><a href="http://www.freepasswordtool.com" target="_blank">CLICK HERE</a></h3>
			</div>';
		echo '<center><a target="_blank" href="http://www.shareasale.com/r.cfm?b=448103&u=653284&m=44747&urllink=&afftrack="><img src="http://www.shareasale.com/image/44747/ginwiz_optimiz-for-mobile_468x60.jpg" alt="468x60" border="0"></a></center>';
		}
	
	
	function bBox_add_dashboard_widgets() {
	wp_add_dashboard_widget('bBox_dashboard_widget', 'Brainbox Themes', 'custom_dashboard_help');
	
	// Globalize the metaboxes array, this holds all the widgets for wp-admin

	global $wp_meta_boxes;
	
	// Get the regular dashboard widgets array 
	// (which has our new widget already but at the end)

	$normal_dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
	
	// Backup and delete our new dashboard widget from the end of the array

	$bBox_widget_backup = array('bBox_dashboard_widget' => $normal_dashboard['bBox_dashboard_widget']);
	unset($normal_dashboard['bBox_dashboard_widget']);

	// Merge the two arrays together so our widget is at the beginning

	$sorted_dashboard = array_merge($bBox_widget_backup, $normal_dashboard);

	// Save the sorted array back into the original metaboxes 

	$wp_meta_boxes['dashboard']['normal']['core'] = $sorted_dashboard;
} 

    
?>