<?php
/*
Plugin Name: Bookshelf Slider
Plugin URI: http://srvalle.com/bookshelf-slider/
Description: Multipurpose Bookshelf Slider is useful for displaying products such as books, magazines, dvd/cd and others. It's a way to showcase products in an attractive manner.
Version: 2.9
Author: Sergio Valle
Author URI: http://srvalle.com
*/

// don't load directly
if (!defined('ABSPATH')) die('');

// Call function when plugin is activated
register_activation_hook(__FILE__,'bs_install');

// Action hook to initialize the plugin
add_action('admin_init', 'bs_init');

// Action hook to register option settings
add_action( 'admin_init', 'bs_register_settings' );

// Action hook to create bookshelf post type and categories taxonomy
add_action('init', 'post_type_bookshelf');
add_action('init', 'create_Bookshelf_cat_tax');

// Action hook to add the menu item
add_action('admin_menu', 'bs_menu');

// Action hook to save the meta box data when the post is saved
add_action('save_post','bs_save_meta_box');

// Action hook to create bookshelf shortcode
add_shortcode('bookshelf', 'bs_shortcode');

// Action hook to create plugin widget
add_action( 'widgets_init', 'bs_register_widgets' );

// Post Order (menu_order) / add ing 08.01.2015
add_action( 'admin_init', 'bookshelf_posts_order' );
function bookshelf_posts_order() {
    add_post_type_support( 'bookshelf', 'page-attributes' );
	add_post_type_support( 'post', 'page-attributes' );
}

// ---------------------------------------
// install
// ---------------------------------------

function bs_install() {
	//setup default option values

	//shortcode
	$bs_options_arr=array("sh_btn_titles"=>"Titles", "sh_btn_icons"=>"Icons", "sh_width"=>545, "sh_height"=>320, "sh_margin_left"=>30, "sh_title_textcolor"=>"#ffffff", "sh_title_bgcolor"=>"#c33b4e",
		"sh_product_margin"=>30, "sh_show_title"=>"true", "sh_show_title_popup"=>"true", "sh_selected_title"=>"true", "sh_show_icons"=>"true", "sh_thumbs_effects"=>"true",
		"sh_buttons_margin"=>15, "sh_buttons_align"=>"center", "sh_slide_duration"=>1000, "sh_slide_easing"=>"easeOutQuart", "sh_arrow_duration"=>800, "sh_arrow_easing"=>"easeOutQuart", 
		"sh_video_width"=>500, "sh_video_height"=>290, "sh_iframe_width"=>600,  "sh_iframe_height"=>430, "sh_categories"=>array(), "sh_exclude_products"=>"", "sh_orderby"=>"date", "sh_order"=>"DESC", 
		"sh_post_type"=>"bookshelf", "sh_shortcode_code"=>"[bookshelf]", "sh_use_which_category"=>"bookshelf_cat", "sh_shelf_space"=>"small","sh_skin"=>"skin01"
	 );

	 //general
	 $bs_general_arr=array("gs_open_bookshelf_script"=>"open_in_footer", "gs_default_post_support"=>"true", "gs_woo_commerce_support"=>"true");

	//save default option values
	update_option('bs_options', $bs_options_arr);
	update_option('bs_general', $bs_general_arr);


	// --------------------------------------------------
	// version 1.7 compatible - init
	// --------------------------------------------------

	$type = 'bookshelf';
	$args=array(
		'post_type' => $type,
		'post_status' => 'publish',
	 	'posts_per_page' => -1
	);
	//'ignore_sticky_posts'=> 1

	$my_query = null;
	$my_query = new WP_Query($args);

	if( $my_query->have_posts() ) {
		while ($my_query->have_posts()) : $my_query->the_post();
			$theID = $my_query->post->ID;
			//echo "<p>" . $theID . " - " . get_the_title() . "</p>";

			if ( get_post_meta($theID,'bs_product_type',true) && !get_post_meta($theID,'_bs_product_type',true) ) {

				update_post_meta($theID,'_bs_product_thumb_url', get_post_meta($theID,'bs_product_thumb_url',true));
				//delete_post_meta($theID,'bs_product_thumb_url', get_post_meta($theID,'bs_product_thumb_url',true));

				update_post_meta($theID,'_bs_product_width', get_post_meta($theID,'bs_product_width',true));
				//delete_post_meta($theID,'bs_product_width', get_post_meta($theID,'bs_product_width',true));

				update_post_meta($theID,'_bs_product_height', get_post_meta($theID,'bs_product_height',true));
				//delete_post_meta($theID,'bs_product_height', get_post_meta($theID,'bs_product_height',true));

				update_post_meta($theID,'_bs_product_type', get_post_meta($theID,'bs_product_type',true));
				//delete_post_meta($theID,'bs_product_type', get_post_meta($theID,'bs_product_type',true));

				update_post_meta($theID,'_bs_product_url', get_post_meta($theID,'bs_product_url',true));
				//delete_post_meta($theID,'bs_product_url', get_post_meta($theID,'bs_product_url',true));

				update_post_meta($theID,'_bs_product_popup', get_post_meta($theID,'bs_product_popup',true));
				//delete_post_meta($theID,'bs_product_popup', get_post_meta($theID,'bs_product_popup',true));

				update_post_meta($theID,'_bs_product_new_window', get_post_meta($theID,'bs_product_new_window',true));
				//delete_post_meta($theID,'bs_product_new_window', get_post_meta($theID,'bs_product_new_window',true));
			}

		endwhile;
	}
	wp_reset_query();

	// --------------------------------------------------
	// version 1.7 compatible - end
	// --------------------------------------------------

}//bs_install


// --------------------------------------------------
// create sub-menu > shortcode and general settings
// --------------------------------------------------

function bs_menu() {
	//shortcode
	add_submenu_page( 'edit.php?post_type=bookshelf', __('Create Shortcode Page','bs-plugin'), __('Create Shortcode','bs-plugin'), 'administrator', 'create-shortcode', 'bs_settings_shorcode' );

	//general settings
	add_submenu_page( 'edit.php?post_type=bookshelf', __('Bookshelf General Settings Page','bs-plugin'), __('BS General Settings','bs-plugin'), 'administrator', 'bs-general-settings', 'bs_general_settings' );
}


// ---------------------------------------
// create post Bookshelf meta box
// ---------------------------------------

function bs_init() {

	// create custom meta box (bookshelf product)
	add_meta_box('bs-meta',__('Bookshelf Product Options','bs-plugin'), 'bs_meta_box','bookshelf','normal','high');	

	$bs_general = get_option('bs_general');

	if ($bs_general['gs_woo_commerce_support'] == 'true') {			
		// create custom meta box (woocommerce product) 
		add_meta_box('bs-meta2',__('Bookshelf Product Options','bs-plugin'), 'bs_meta_box','product','normal','high');
	}

	if ($bs_general['gs_default_post_support'] == 'true') {
		// create custom meta box (default post) 
		add_meta_box('bs-meta3',__('Bookshelf Product Options','bs-plugin'), 'bs_meta_box','post','normal','high');
	}
}


// ---------------------------------------
// create shortcode
// ---------------------------------------

function bs_shortcode($atts, $content = null) {

	global $post;
	$plugin_dir = plugin_dir_url(__FILE__);

	extract(shortcode_atts(array(
		'id' => 1,
		'item_width' => 545,
		'item_height' => 320,
		'products_box_margin_left' => 20, 
		'product_title_textcolor' => '#ffffff', 
		'product_title_bgcolor' => '#c33b4e', 
		'product_margin' => 30,
		'product_show_title' => 'true',
		'show_title_in_popup' => 'true',
		'show_selected_title' => 'true',
		'show_icons' => 'true',
		'buttons_margin' => 10,
		'buttons_align' => 'center',
		'slide_duration' => 1000,
		'slide_easing' => 'easeInOutExpo', 
		'arrow_duration' => 800,
		'arrow_easing' => 'easeInOutExpo', 
		'video_width' => 500,
		'video_height' => 290,
		'iframe_width' => 400,
		'iframe_height' => 300,
		'categories' => '',
		'exclude_products' => '',
		'post_type' => 'bookshelf',
		'btn_titles' => 'Titles',
		'btn_icons' => 'Icons',
		'order' => 'DESC',
		'orderby' => 'date',
		'thumbs_effects' => 'true',
		'shelf_space' => 'small',
		'skin' => 'skin01',
		'forced_centralized' => 'false'
	), $atts));


	if ($exclude_products != '') {
		$exclude_products_arr = explode (',', $exclude_products);
	} else {
		$exclude_products_arr = '';
	}

	$percent_width = strpos($item_width, '%');
	if ($percent_width !== false) { $item_width = "'" . $item_width . "'"; }


	////////////////////////////////////////////////
	// open css file
	$css_file_name = '';

	if ($skin == 'skin01' && $shelf_space == 'small') {
		$css_file_name = $plugin_dir . 'css/skin01.css';
		$css_class = 'sk01';
	} elseif ($skin == 'skin01' && $shelf_space == 'medium') {
		$css_file_name = $plugin_dir . 'css/skin01_medium.css';
		$css_class = 'sk01_md';

	} elseif ($skin == 'skin02' && $shelf_space == 'small') {
		$css_file_name = $plugin_dir . 'css/skin02.css';
		$css_class = 'sk02';
	} elseif ($skin == 'skin02' && $shelf_space == 'medium') {
		$css_file_name = $plugin_dir . 'css/skin02_medium.css';
		$css_class = 'sk02_md';

	} elseif ($skin == 'skin03' && $shelf_space == 'small') {
		$css_file_name = $plugin_dir . 'css/skin03.css';
		$css_class = 'sk03';
	} elseif ($skin == 'skin03' && $shelf_space == 'medium') {
		$css_file_name = $plugin_dir . 'css/skin03_medium.css';
		$css_class = 'sk03_md';
	}


	$output = "<div><script type='text/javascript'>
	/* <![CDATA[ */
		jQuery(window).load(function(){
			var fileref = document.createElement('link');
			fileref.setAttribute('rel', 'stylesheet');
			fileref.setAttribute('type', 'text/css');
			fileref.setAttribute('href', '" . $css_file_name . "');
			if (typeof fileref != 'undefined') {
				document.getElementsByTagName('head')[0].appendChild(fileref);
			}
		});
	/* ]]> */
	</script></div>";
	////////////////////////////////////////////////

	$output .= "<div><script type='text/javascript'>
	/* <![CDATA[ */
		////jQuery(document).ready(function(){
		jQuery(window).load(function(){
			jQuery.bookshelfSlider('#bookshelf_slider_sc_" . $id . "', {
				'item_width': " . $item_width . ",
				'item_height': " . $item_height . ",
				'products_box_margin_left': " . $products_box_margin_left . ", 
				'product_title_textcolor': '" . $product_title_textcolor . "', 
				'product_title_bgcolor': '" . $product_title_bgcolor . "', 
				'product_margin': " . $product_margin . ",
				'product_show_title': " . $product_show_title . ",
				'show_title_in_popup': " . $show_title_in_popup . ",
				'show_selected_title': " . $show_selected_title . ",
				'show_icons': " . $show_icons . ",
				'buttons_margin': " . $buttons_margin . ",
				'buttons_align': '" . $buttons_align . "',
				'slide_duration': " . $slide_duration . ",
				'slide_easing': '" . $slide_easing . "', 
				'arrow_duration': " . $arrow_duration . ",
				'arrow_easing': '" . $arrow_easing . "', 
				'video_width_height': [" . $video_width . "," . $video_height . "],
				'iframe_width_height': [" . $iframe_width . "," . $iframe_height . "],
				'thumbs_effects': " . $thumbs_effects . ",
				'shelf_space': '" . $shelf_space . "',
				'css_class': '" . $css_class . "',
				'forced_centralized': " . $forced_centralized . "
			});
		});
	/* ]]> */
	</script></div>";
?>
<?php
	$output .= "
    <div id='bookshelf_slider_sc_$id' class='bookshelf_slider $css_class'>
        <div class='panel_title $css_class'>";
			if ($show_selected_title) { $output .= "<div class='selected_title_box $css_class'><div class='selected_title $css_class'>Selected Title</div></div>"; }
            $output .= "<div class='bs_menu_top $css_class'>
                <ul>";
					if ($btn_titles != '') { $output .= "<li class='show_hide_titles'><a href='#'>$btn_titles</a></li>"; }
                    if ($btn_icons != '') { $output .= "<li class='show_hide_icons'><a href='#'>$btn_icons</a></li>"; }
				$output .= "
                </ul>
            </div>
        </div>";
?>
<?php
		$output .= "
        <div class='panel_slider $css_class'>
            <div class='panel_items $css_class'>";
?>
<?php
                //09.08.2014 - new resize script
                require_once( "php/aq_resizer.php" );

				////wp_localize_script()
                $output .= "<div class='plugin_dir' style='display:none;'>$plugin_dir</div>";

				if ($categories != '') {
					$catsSelected = explode(',', $categories);
				} else {

					///////////////////
					if ($post_type == 'post') {
						$tax = 'category';
					} elseif ($post_type == 'bookshelf') {
						$tax = 'bookshelf_category';
					} elseif ($post_type == 'product') {
						$tax = 'product_cat';
					}

					$args = array('type' => $post_type, 'taxonomy' => $tax);
					$categoriesTmp = get_categories( $args );

					$catTmpArr = array();
					foreach ($categoriesTmp as $catTmp) {
						array_push($catTmpArr, $catTmp->slug);
					}

					$catsSelected = $catTmpArr;
				}

				$len_cats = count($catsSelected);


				if ($len_cats > 0) {
					for ($i=1; $i <= $len_cats; $i++) {

						$output .= "<div class='slide_animate $css_class'>";
							$output .= "<div class='products_box $css_class' id='products_box_$i'>";

								$j = $i-1;
								$ct_wp_query = new WP_Query();
						
								//////////////// \\\\\\\\\\\\\\\\
								//add 'suppress_filters' => true >>>> para multilanguages

								//post type
								if ($post_type == 'post') {
									// post - default post type
									$ct_wp_query->query( array('post__not_in' => $exclude_products_arr, 'post_type' => 'post', 'category_name' => $catsSelected[$j], 
									'post_status' => 'publish', 'posts_per_page' => -1, 'nopaging' => true, 'orderby' => $orderby, 'order' => $order, 'suppress_filters' => 0) );

								} elseif ($post_type == 'bookshelf' || $post_type == '' || $post_type == NULL) {
									// bookshelf - custom post type
									$ct_wp_query->query( array('post__not_in' => $exclude_products_arr, 'post_type' => 'bookshelf', 'bookshelf_category' => $catsSelected[$j], 'post_status' => 'publish', 'posts_per_page' => -1, 'nopaging' => true, 'orderby' => $orderby, 'order' => $order, 'suppress_filters' => 0 ) );

								} else {

									// othes custom post type and taxonomy 

									if ($post_type == 'product') {	
										//woo commerce
										$ct_wp_query->query( array('post__not_in' => $exclude_products_arr, 'post_type' => $post_type, 'product_cat' => $catsSelected[$j], 'post_status' => 'publish', 'posts_per_page' => -1, 'nopaging' => true, 'orderby' => $orderby, 'order' => $order, 'suppress_filters' => 0) );
									} else {
										// other
										$ct_wp_query->query( array('post__not_in' => $exclude_products_arr, 'post_type' => $post_type, 'category_name' => $catsSelected[$j], 'post_status' => 'publish', 'posts_per_page' => -1, 'nopaging' => true, 'orderby' => $orderby, 'order' => $order, 'suppress_filters' => 0) );	
									}

								}

								if ( $ct_wp_query->have_posts() ) : while ( $ct_wp_query->have_posts() ) : $ct_wp_query->the_post();
						
									//////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
									////echo the_title() . ' / ' . get_the_ID() . '<br>';

									$bs_p_type = get_post_meta($post->ID,'_bs_product_type',true);
									$bs_p_url = trim(get_post_meta($post->ID,'_bs_product_url',true));
                                    ////////////////////////
                                    //automatic link if empty field
									if ($bs_p_url == '') { $bs_p_url = get_permalink( $post->ID ); }

									$bs_p_popup = get_post_meta($post->ID,'_bs_product_popup',true);
									$bs_p_new_window = get_post_meta($post->ID,'_bs_product_new_window',true);

                                    $bs_p_width = trim(get_post_meta($post->ID,'_bs_product_width',true));
									if ($bs_p_width == '') {
										if ($shelf_space == 'small') {
											$bs_p_width = '80';
										} else {
											$bs_p_width = '126';
										}
									}

									$bs_p_height = trim(get_post_meta($post->ID,'_bs_product_height',true));
									if ($bs_p_height == '') {
										if ($shelf_space == 'small') {
											$bs_p_height = '107';
										} else {
											$bs_p_height = '168';
										}
									}

                                    $use_default_image = false;
                                    $bs_p_thumb_url = trim(get_post_meta($post->ID,'_bs_product_thumb_url',true));

                                    if ( $bs_p_thumb_url == '' && !has_post_thumbnail($post->ID) ) {
                                        $use_default_image = true;
										if ($shelf_space == 'small') {
											$bs_p_thumb_url = $plugin_dir . 'images/default_image.jpg';
										} else {
											$bs_p_thumb_url = $plugin_dir . 'images/default_image_medium.jpg';
										}
									}

									$the_id = get_the_ID();
									$the_title = get_the_title();
									//enable shortcode
									//$the_content = apply_filters('the_content', get_the_content());


									if ($use_default_image) {
										$output .= "<div class='bs_product $css_class' data-id='$the_id' data-post-type='$post_type' data-type='$bs_p_type' data-popup='$bs_p_popup' data-newwindow='$bs_p_new_window' data-url='$bs_p_url' title='$the_title'><img src='$bs_p_thumb_url' alt='' width='$bs_p_width' height='$bs_p_height'/></div>";

                                    } elseif ($bs_p_thumb_url != '') {

                                        //aq_resize( $url, $width, $height, $crop, $single, $upscale );
                                        //$image = aq_resize( $bs_p_thumb_url, $bs_p_width, $bs_p_height, true, true, true );

                                        //$output .= "<div class='bs_product $css_class' data-id='$the_id' data-post-type='$post_type' data-type='$bs_p_type' data-popup='$bs_p_popup' data-newwindow='$bs_p_new_window' data-url='$bs_p_url' title='$the_title'><img src='$image' alt='' width='$bs_p_width' height='$bs_p_height'/></div>";

                                        //no crop
                                        $output .= "<div class='bs_product $css_class' data-id='$the_id' data-post-type='$post_type' data-type='$bs_p_type' data-popup='$bs_p_popup' data-newwindow='$bs_p_new_window' data-url='$bs_p_url' title='$the_title'><img src='$bs_p_thumb_url' alt='' width='$bs_p_width' height='$bs_p_height'/></div>";

									} elseif (has_post_thumbnail($post->ID)) {

                                        $thumb = get_post_thumbnail_id();
                                        $img_url = wp_get_attachment_url( $thumb,'full'); //get img URL

                                        //aq_resize( $url, $width, $height, $crop, $single, $upscale );
                                        $image = aq_resize( $img_url, $bs_p_width, $bs_p_height, true, true, true );

                                        $output .= "<div class='bs_product $css_class' data-id='$the_id' data-post-type='$post_type' data-type='$bs_p_type' data-popup='$bs_p_popup' data-newwindow='$bs_p_new_window' data-url='$bs_p_url' title='$the_title'><img src='$image' alt='' width='$bs_p_width' height='$bs_p_height'/></div>";
									}

								endwhile; else:
								endif;
								wp_reset_postdata();

							$output .= "</div>";
						$output .= "</div>";
					}//for
				}//if
			$output .="
            </div>
        </div>";
?>
<?php
		$output .= "<div class='panel_bar $css_class'>
						<div class='buttons_container $css_class'>
            				<div id='arrow_box'><div id='arrow_menu'></div></div>
            					<div class='button_items $css_class'>";
?>
<?php 
                for ($i=0; $i < $len_cats; $i++) {
                    $num = $i+1;

					if ($post_type == 'post') {
						//post - default post type
						$getTermBy = get_category_by_slug( $catsSelected[$i] );
					} elseif ($post_type == 'bookshelf' || $post_type == '' || $post_type == NULL) {
						//bookshelf - custom post type
						$getTermBy = get_term_by('slug', $catsSelected[$i], 'bookshelf_category');
					} else {
						//other custom post type and taxonomy
						if ($post_type == 'product') {
							//woo commerce
							$getTermBy = get_term_by('slug', $catsSelected[$i], 'product_cat');
						} else {
							//other
							$getTermBy = get_category_by_slug( $catsSelected[$i] );
						}
					}

                    $output .= "<div id='btn$num' class='button_bar $css_class'><a href='#'>" . $getTermBy->name . "</a></div>";
                }
?>
<?php
            $output .= "</div>
        				</div>
						</div>
	</div>";
	//#bookshelf_slider
	return $output;
?>
<?php
}//bs_shortcode


// ---------------------------------------
// build bookshelf product meta box
// ---------------------------------------

function bs_meta_box($post,$box) {

	// retrieve custom meta box values
	$bs_product_type = get_post_meta($post->ID,'_bs_product_type',true);
	$bs_product_url = get_post_meta($post->ID,'_bs_product_url',true);
	$bs_product_popup = get_post_meta($post->ID,'_bs_product_popup',true);
	$bs_product_new_window = get_post_meta($post->ID,'_bs_product_new_window',true);
	$bs_product_width = get_post_meta($post->ID,'_bs_product_width',true);
	$bs_product_height = get_post_meta($post->ID,'_bs_product_height',true);
	$bs_product_thumb_url = get_post_meta($post->ID,'_bs_product_thumb_url',true);


	// display meta box form
	echo '<br><br>';
	echo '<table>';

	echo '</tr><tr>';
	echo '<td>' .__('Thumbnail Image URL', 'bs-plugin'). ':</td><td><input type="text" name="_bs_product_thumb_url" value="'.esc_attr($bs_product_thumb_url).'" size="60"></td><td>&nbsp;<div class="bs_info_btn"><div class="bs_info">Paste here the url of the image with exact size. Or use "Set featured image" (leaving this field empty) and the image is automatically cropped to fit the width and height defined below (Thumbnail Width and Thumbnail Height).</div></div></td>';
	echo '</tr><tr>';

	echo '<tr><td colspan="3"><hr noshade="noshade" color="#dddddd"></td></tr>';

	echo '</tr><tr>';
	echo '<td>' . __('Thumbnail Width', 'bs-plugin') . ':</td><td><input type="text" name="_bs_product_width" value="'.esc_attr($bs_product_width).'" size="5">&nbsp;<small>' . __('Required (enter number only)', 'bs-plugin') . '</small></td><td>&nbsp;<div class="bs_info_btn"><div class="bs_info">(Required). Default DVD Width: 77 pixels - Default CD Width: 80 pixels</div></div></td>';
	echo '</tr><tr>';

	echo '<tr><td colspan="3"><hr noshade="noshade" color="#dddddd"></td></tr>';

	echo '</tr><tr>';
	echo '<td>' . __('Thumbnail Height', 'bs-plugin') . ':</td><td><input type="text" name="_bs_product_height" value="'.esc_attr($bs_product_height).'" size="5">&nbsp;<small>' . __('Required (enter number only)', 'bs-plugin') . '</small></td><td>&nbsp;<div class="bs_info_btn"><div class="bs_info">(Required). Default DVD Height: 107 pixels - Default CD Height: 80 pixels</div></div></td>';
	echo '</tr><tr>';

	echo '<tr><td colspan="3"><hr noshade="noshade" color="#dddddd"></td></tr>';

	echo '<tr>';
	echo '<td>' . __('Product Type', 'bs-plugin') . ':</td><td><select name="_bs_product_type" id="_bs_product_type" style="width:100px;">
			<option value="book" ' . (is_null($bs_product_type) || $bs_product_type == "book" ? 'selected="selected" ' : '').'>' .__('Book', 'bs-plugin'). '</option>
			<option value="magazine" ' . ($bs_product_type == "magazine" ? 'selected="selected" ' : '') . '>' . __('Magazine', 'bs-plugin') . '</option>
			
			<option value="dvd" ' . ($bs_product_type == "dvd" ? 'selected="selected" ' : '').'>' .__('Dvd', 'bs-plugin'). '</option>
			<option value="cd" ' . ($bs_product_type == "cd" ? 'selected="selected" ' : '').'>' .__('Cd', 'bs-plugin'). '</option>
			<option value="none" ' . ($bs_product_type == "none" ? 'selected="selected" ' : '').'>' .__('None', 'bs-plugin'). '</option>
		</select></td><td>&nbsp;<div class="bs_info_btn"><div class="bs_info">Defines only the effect that is placed over the image (Thumbnail). Choose "none" if you do not want to add effect.</div></div></td>';
	echo '</tr>';

	echo '<tr><td colspan="3"><hr noshade="noshade" color="#dddddd"></td></tr>';

	echo '<td>' . __('Open in Popup (Lightbox)', 'bs-plugin') . ':</td><td><select name="_bs_product_popup" id="_bs_product_popup" style="width:100px;">
            <option value="false" ' . ($bs_product_popup == "false" ? 'selected="selected" ' : '').'>False</option>
			<option value="true" ' . ($bs_product_popup == "true" ? 'selected="selected" ' : '').'>True</option>
		</select></td><td>&nbsp;<div class="bs_info_btn"><div class="bs_info">Select "False" if the target is another page, either internal or external.</div></div></td>';
	echo '</tr>';
	echo '</tr><tr>';

	echo '<tr><td colspan="3"><hr noshade="noshade" color="#dddddd"></td></tr>';

	echo '<td>' . __('Open in New Window', 'bs-plugin') . ':</td><td><select name="_bs_product_new_window" id="_bs_product_new_window" style="width:100px;">
            <option value="false" ' . ($bs_product_new_window == "false" ? 'selected="selected" ' : '').'>False</option>
			<option value="true" ' . ($bs_product_new_window == "true" ? 'selected="selected" ' : '').'>True</option>
		</select></td><td>&nbsp;<div class="bs_info_btn"><div class="bs_info">If you choose "True" the link will open in a new window. Only if the previous option - Open in Popup (Lightbox) - is marked as "False".</div></div></td>';
	echo '</tr>';
	echo '</tr><tr>';

	echo '<tr><td colspan="3"><hr noshade="noshade" color="#dddddd"></td></tr>';

	echo '</tr><tr>';
	echo '<td>' .__('Product Target URL', 'bs-plugin'). ':</td><td><input type="text" name="_bs_product_url" value="'.esc_attr($bs_product_url).'" size="60"></td><td>&nbsp;<div class="bs_info_btn"><div class="bs_info">Large Image, Video (Youtube or Vimeo) or Page Content (html, php etc). Use [#description#] to display the html content (above) this page. <br>Use ?size=900x300&p=[#description#] to customize the size of the popup</div></div></td>';
	echo '</tr><tr>';

	echo '<tr><td colspan="3"><hr noshade="noshade" color="#dddddd"></td></tr>';

	echo '</table>';
	echo '<br><br>';
}//bs_meta_box


// ---------------------------------------
// save meta box data
// ---------------------------------------

function bs_save_meta_box($post_id) {
	global $post;

	// if post is a revision skip saving meta box data
	//if($post->post_type == 'revision') { return; }

	// process form data if $_POST is set
	if(isset($_POST['_bs_product_type']) && $_POST['_bs_product_type'] != '') {

		// save the meta box data as post meta using the post ID as a unique prefix
		update_post_meta($post_id,'_bs_product_thumb_url', esc_attr($_POST['_bs_product_thumb_url']));
		update_post_meta($post_id,'_bs_product_width', esc_attr($_POST['_bs_product_width']));
		update_post_meta($post_id,'_bs_product_height', esc_attr($_POST['_bs_product_height']));
		update_post_meta($post_id,'_bs_product_type', esc_attr($_POST['_bs_product_type']));
		update_post_meta($post_id,'_bs_product_url', esc_attr($_POST['_bs_product_url']));
		update_post_meta($post_id,'_bs_product_popup', esc_attr($_POST['_bs_product_popup']));
		update_post_meta($post_id,'_bs_product_new_window', esc_attr($_POST['_bs_product_new_window']));
	}
}

//register widget
function bs_register_widgets() {
	register_widget( 'bs_widget' );

	// Using Shortcodes inside 'Text' widgets
	add_filter('widget_text', 'do_shortcode');
}


// ---------------------------------------
// bs_widget class
// ---------------------------------------

//include_once( "bs_widget.php" );

class bs_widget extends WP_Widget {

	//process new widget
	function bs_widget() {
		$widget_ops = array('classname' => 'bs_widget', 'description' => __('Display Bookshelf Slider Products','bs-plugin') );
		////$this->WP_Widget('bs_widget', __('Bookshelf Widget','bs-plugin'), $widget_ops);
		$this->__construct('bs_widget', __('Bookshelf Widget','bs-plugin'), $widget_ops);
		$id_count = 1;
	}

 	//build widget settings form
	function form($instance) {
		$defaults = array( 'title' => __('Bookshelf','bs-plugin'), 'bs_button_titles' => 'Titles', 'bs_button_icons' => 'Icons', 'bs_width' => 280, 'bs_height' => 320, 'bs_margin_left' => 30, 'bs_prod_title_color' => '#ffffff', 'bs_prod_bg_color' => '#c33b4e', 'bs_prod_margin' => 30, 'bs_show_title' => 'yes', 'bs_show_title_popup' => 'true', 'bs_show_sel_title' => 'true', 'bs_show_icons' => 'true', 'bs_buttons_margin' => 15, 'bs_buttons_align' => 'center', 'bs_slide_duration' => 1000, 'bs_slide_easing' => 'easeOutQuart', 'bs_arrow_duration' => 800, 'bs_arrow_easing' => 'easeOutQuart', 'bs_video_width' => 500, 'bs_video_height' => 290, 'bs_iframe_width' => 500, 'bs_iframe_height' => 330, 'bs_categories' => array(), 'bs_input_order' => array(), 'bs_exclude_products' => '' );
		$instance = wp_parse_args( (array) $instance, $defaults );

		$title = strip_tags($instance['title']);
		$bs_width = strip_tags($instance['bs_width']);
		$bs_button_titles = strip_tags($instance['bs_button_titles']);
		$bs_button_icons = strip_tags($instance['bs_button_icons']);
		$bs_height = strip_tags($instance['bs_height']);
		$bs_margin_left = strip_tags($instance['bs_margin_left']);
		$bs_prod_title_color = strip_tags($instance['bs_prod_title_color']);
		$bs_prod_bg_color = strip_tags($instance['bs_prod_bg_color']);
		$bs_prod_margin = strip_tags($instance['bs_prod_margin']);
		$bs_show_title = strip_tags($instance['bs_show_title']);
		$bs_show_title_popup = strip_tags($instance['bs_show_title_popup']);
		$bs_show_sel_title = strip_tags($instance['bs_show_sel_title']);
		$bs_show_icons = strip_tags($instance['bs_show_icons']);
		$bs_buttons_margin = strip_tags($instance['bs_buttons_margin']);
		$bs_buttons_align = strip_tags($instance['bs_buttons_align']);
		$bs_slide_duration = strip_tags($instance['bs_slide_duration']);
		$bs_slide_easing = strip_tags($instance['bs_slide_easing']);
		$bs_arrow_duration = strip_tags($instance['bs_arrow_duration']);
		$bs_arrow_easing = strip_tags($instance['bs_arrow_easing']);
		$bs_video_width = strip_tags($instance['bs_video_width']);
		$bs_video_height = strip_tags($instance['bs_video_height']);
		$bs_iframe_width = strip_tags($instance['bs_iframe_width']);
		$bs_iframe_height = strip_tags($instance['bs_iframe_height']);
		$bs_categories = $instance['bs_categories'];
		$bs_input_order = $instance['bs_input_order'];
		$bs_exclude_products = strip_tags($instance['bs_exclude_products']);

		$easingOptions = array('jswing', 'easeInQuad', 'easeOutQuad', 'easeInOutQuad', 'easeInCubic', 'easeOutCubic', 'easeInOutCubic', 'easeInQuart', 'easeOutQuart', 'easeInOutQuart', 'easeInQuint', 'easeOutQuint', 'easeInOutQuint', 'easeInSine', 'easeOutSine', 'easeInOutSine', 'easeInExpo', 'easeOutExpo', 'easeInOutExpo', 'easeInCirc', 'easeOutCirc', 'easeInOutCirc', 'easeInElastic', 'easeOutElastic', 'easeInOutElastic', 'easeInBack', 'easeOutBack', 'easeInOutBack', 'easeInBounce', 'easeOutBounce', 'easeInOutBounce');

		$easingLen = count($easingOptions);
		?>

        <p><?php _e('Title', 'bs-plugin') ?>: <input class="widefat" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></p>
        <p><?php _e('Button Titles (Text)', 'bs-plugin') ?>: <input class="widefat" name="<?php echo $this->get_field_name('bs_button_titles'); ?>" type="text" value="<?php echo esc_attr($bs_button_titles); ?>" /></p>
        <p><?php _e('Button Icons (Text)', 'bs-plugin') ?>: <input class="widefat" name="<?php echo $this->get_field_name('bs_button_icons'); ?>" type="text" value="<?php echo esc_attr($bs_button_icons); ?>" /></p>
        <p><?php _e('Bookshelf Width', 'bs-plugin') ?>: <input name="<?php echo $this->get_field_name('bs_width'); ?>" type="text" value="<?php echo esc_attr($bs_width); ?>" size="4" maxlength="4" /><br><small><?php _e('Allowed percentage value. e.g. 100%', 'bs-plugin') ?></small></p>
        <p><?php _e('Bookshelf Height', 'bs-plugin') ?>: <input name="<?php echo $this->get_field_name('bs_height'); ?>" type="text" value="<?php echo esc_attr($bs_height); ?>" size="4" maxlength="4" /></p>
        <p><?php _e('Margin Left', 'bs-plugin') ?>: <input name="<?php echo $this->get_field_name('bs_margin_left'); ?>" type="text" value="<?php echo esc_attr($bs_margin_left); ?>" size="4" maxlength="3" /></p>
        <p><?php _e('Product Title Text Color', 'bs-plugin') ?>: <input name="<?php echo $this->get_field_name('bs_prod_title_color'); ?>" type="text" value="<?php echo esc_attr($bs_prod_title_color); ?>" size="6" maxlength="7" /></p>
        <p><?php _e('Product Title BG Color', 'bs-plugin') ?>: <input name="<?php echo $this->get_field_name('bs_prod_bg_color'); ?>" type="text" value="<?php echo esc_attr($bs_prod_bg_color); ?>" size="6" maxlength="7" /></p>
        <p><?php _e('Product Margin', 'bs-plugin') ?>: <input name="<?php echo $this->get_field_name('bs_prod_margin'); ?>" type="text" value="<?php echo esc_attr($bs_prod_margin); ?>" size="6" maxlength="7" /></p>
        <p><?php _e('Buttons Margin', 'bs-plugin') ?>: <input name="<?php echo $this->get_field_name('bs_buttons_margin'); ?>" type="text" value="<?php echo esc_attr($bs_buttons_margin); ?>" size="6" maxlength="7" /></p>

        <p><?php _e('Buttons Align', 'bs-plugin') ?>:
        <select style="width:80px;" class="widefat" id="<?php echo $this->get_field_id('bs_buttons_align'); ?>" name="<?php echo $this->get_field_name('bs_buttons_align'); ?>">
            <option value="left" <?php if($bs_buttons_align == "left") { echo "selected='selected'"; } else { echo ""; } ?>>Left</option>
            <option value="center" <?php if($bs_buttons_align == "center") { echo "selected='selected'"; } else { echo ""; }?>>Center</option>
            <option value="right" <?php if($bs_buttons_align == "right") { echo "selected='selected'"; } else { echo ""; }?>>Right</option>
        </select></p>

        <p><?php _e('Slide Duration', 'bs-plugin') ?>: <input name="<?php echo $this->get_field_name('bs_slide_duration'); ?>" type="text" value="<?php echo esc_attr($bs_slide_duration); ?>" size="6" maxlength="4" />&nbsp;<small><?php _e('Milliseconds', 'bs-plugin') ?></small></p>

        <p><?php _e('Slide Easing', 'bs-plugin') ?>:
        <select style="width:140px;" class="widefat" name="<?php echo $this->get_field_name('bs_slide_easing'); ?>">
        	<?php
				for ($i=0; $i < $easingLen; $i++) {
					if ($bs_slide_easing == $easingOptions[$i]) {
						echo "<option value='$easingOptions[$i]' selected='selected'>$easingOptions[$i]</option>";
					}
					echo "<option value='$easingOptions[$i]'>$easingOptions[$i]</option>";
				}
			?>
        </select></p>

        <p><?php _e('Arrow Duration', 'bs-plugin') ?>: <input name="<?php echo $this->get_field_name('bs_arrow_duration'); ?>" type="text" value="<?php echo esc_attr($bs_arrow_duration); ?>" size="6" maxlength="4" />&nbsp;<small><?php _e('Milliseconds', 'bs-plugin') ?></small></p>

        <p><?php _e('Arrow Easing', 'bs-plugin') ?>:
        <select style="width:140px;" class="widefat" name="<?php echo $this->get_field_name('bs_arrow_easing'); ?>">
        	<?php
				for ($i=0; $i < $easingLen; $i++) {
					if ($bs_arrow_easing == $easingOptions[$i]) {
						echo "<option value='$easingOptions[$i]' selected='selected'>$easingOptions[$i]</option>";
					}
					echo "<option value='$easingOptions[$i]'>$easingOptions[$i]</option>";
				}
			?>
        </select></p>

        <p>
		<?php _e('Video Width / Height', 'bs-plugin') ?>: <br />
        <input name="<?php echo $this->get_field_name('bs_video_width'); ?>" type="text" value="<?php echo esc_attr($bs_video_width); ?>" size="6" maxlength="4" /> x <input name="<?php echo $this->get_field_name('bs_video_height'); ?>" type="text" value="<?php echo esc_attr($bs_video_height); ?>" size="6" maxlength="4" />
        </p>

        <p>
		<?php _e('Iframe Width / Height', 'bs-plugin') ?>: <br />
        <input name="<?php echo $this->get_field_name('bs_iframe_width'); ?>" type="text" value="<?php echo esc_attr($bs_iframe_width); ?>" size="6" maxlength="4" /> x <input name="<?php echo $this->get_field_name('bs_iframe_height'); ?>" type="text" value="<?php echo esc_attr($bs_iframe_height); ?>" size="6" maxlength="4" />
        </p>

        <p><?php _e('Show Product Title', 'bs-plugin') ?>:
        <select style="width:60px;" class="widefat" id="<?php echo $this->get_field_id('bs_show_title'); ?>" name="<?php echo $this->get_field_name('bs_show_title'); ?>">
            <option value="true" <?php if($bs_show_title == "true") { echo "selected='selected'"; } else { echo ""; } ?>>True</option>
            <option value="false" <?php if($bs_show_title == "false") { echo "selected='selected'"; } else { echo ""; }?>>False</option>
        </select></p>

        <p><?php _e('Show Title in Popup', 'bs-plugin') ?>:
        <select style="width:60px;" class="widefat" id="<?php echo $this->get_field_id('bs_show_title_popup'); ?>" name="<?php echo $this->get_field_name('bs_show_title_popup'); ?>">
            <option value="true" <?php if($bs_show_title_popup == "true") { echo "selected='selected'"; } else { echo ""; } ?>>True</option>
            <option value="false" <?php if($bs_show_title_popup == "false") { echo "selected='selected'"; } else { echo ""; }?>>False</option>
        </select></p>

        <p><?php _e('Show Selected Title', 'bs-plugin') ?>:
        <select style="width:60px;" class="widefat" id="<?php echo $this->get_field_id('bs_show_sel_title'); ?>" name="<?php echo $this->get_field_name('bs_show_sel_title'); ?>">
            <option value="true" <?php if($bs_show_sel_title == "true") { echo "selected='selected'"; } else { echo ""; } ?>>True</option>
            <option value="false" <?php if($bs_show_sel_title == "false") { echo "selected='selected'"; } else { echo ""; }?>>False</option>
        </select></p>

        <p><?php _e('Show Icons', 'bs-plugin') ?>:
        <select style="width:60px;" class="widefat" id="<?php echo $this->get_field_id('bs_show_icons'); ?>" name="<?php echo $this->get_field_name('bs_show_icons'); ?>">
            <option value="true" <?php if($bs_show_icons == "true") { echo "selected='selected'"; } else { echo ""; } ?>>True</option>
            <option value="false" <?php if($bs_show_icons == "false") { echo "selected='selected'"; } else { echo ""; }?>>False</option>
        </select></p>


		<p><?php _e('Choose the Categories and Order', 'bs-plugin') ?>:</p>
		<?php
		$categories = get_terms("bookshelf_category"); 
		$count = count($categories); 
		$i=0;

		if ( $count > 0 ) {
			foreach ($categories as $cat) {

				$option = '<input type="checkbox" id="'. $this->get_field_id( 'bs_categories' ) .'[]" name="'. $this->get_field_name( 'bs_categories' ) .'[]"';
				if (is_array($instance['bs_categories'])) {
					foreach ($instance['bs_categories'] as $cats) {
						if($cats == $cat->slug) { //$cat->term_id
							$option = $option.' checked="checked"';
						}
					}
				}
				$option .= ' value="' . $cat->slug . '" />';
				$option .= '&nbsp;' . $cat->name;


				//get bs_input_order array
				//$order_request = $_REQUEST['bs_input_order'];
				$order_instance = $instance['bs_input_order'];

				if ( $order_instance[$i] != '' && is_numeric($order_instance[$i]) ) {
					$option .= '&nbsp;<input name="'. $this->get_field_name( 'bs_input_order' ) . '[]" type="text" value="' . $order_instance[$i] . '" size="2" maxlength="2" /><br>';
				} else {
					$option .= '&nbsp;<input name="'. $this->get_field_name( 'bs_input_order' ) . '[]" type="text" value="" size="2" maxlength="2" /><br>';
				}

				echo $option;
				$i++;
			}//foreach
		}//if
		?>

        <br>
        <p><?php _e('Exclude Products', 'bs-plugin') ?>: <input class="widefat" name="<?php echo $this->get_field_name('bs_exclude_products'); ?>" type="text" value="<?php echo esc_attr($bs_exclude_products); ?>" /><small><?php _e('Product ID comma-separated', 'bs-plugin') ?></small></p>
        <br><hr color="#dddddd" noshade="noshade" />
	<?php
	}//form

  	//save widget settings
	function update($new_instance, $old_instance) {
		$instance = $old_instance;
		$instance['title'] = strip_tags(esc_attr($new_instance['title']));
		$instance['bs_button_titles'] = strip_tags(esc_attr($new_instance['bs_button_titles']));
		$instance['bs_button_icons'] = strip_tags(esc_attr($new_instance['bs_button_icons']));
		$instance['bs_width'] = strip_tags(esc_attr($new_instance['bs_width']));
		$instance['bs_height'] = intval($new_instance['bs_height']);
		$instance['bs_margin_left'] = intval($new_instance['bs_margin_left']);
		$instance['bs_prod_title_color'] = strip_tags(esc_attr($new_instance['bs_prod_title_color']));
		$instance['bs_prod_bg_color'] = strip_tags(esc_attr($new_instance['bs_prod_bg_color']));
		$instance['bs_prod_margin'] = intval($new_instance['bs_prod_margin']);
		$instance['bs_show_title'] = strip_tags(esc_attr($new_instance['bs_show_title']));
		$instance['bs_show_title_popup'] = strip_tags(esc_attr($new_instance['bs_show_title_popup']));
		$instance['bs_show_sel_title'] = strip_tags(esc_attr($new_instance['bs_show_sel_title']));
		$instance['bs_show_icons'] = strip_tags(esc_attr($new_instance['bs_show_icons']));
		$instance['bs_buttons_margin'] = intval($new_instance['bs_buttons_margin']);
		$instance['bs_buttons_align'] = strip_tags(esc_attr($new_instance['bs_buttons_align']));
		$instance['bs_slide_duration'] = intval($new_instance['bs_slide_duration']);
		$instance['bs_slide_easing'] = strip_tags(esc_attr($new_instance['bs_slide_easing']));
		$instance['bs_arrow_duration'] = intval($new_instance['bs_arrow_duration']);
		$instance['bs_arrow_easing'] = strip_tags(esc_attr($new_instance['bs_arrow_easing']));
		$instance['bs_video_width'] = intval($new_instance['bs_video_width']);
		$instance['bs_video_height'] = intval($new_instance['bs_video_height']);
		$instance['bs_iframe_width'] = intval($new_instance['bs_iframe_width']);
		$instance['bs_iframe_height'] = intval($new_instance['bs_iframe_height']);
		$instance['bs_categories'] = $new_instance['bs_categories'];	
		$instance['bs_input_order'] = $new_instance['bs_input_order'];
		$instance['bs_exclude_products'] = strip_tags(esc_attr($new_instance['bs_exclude_products']));

		return $instance;
	}

 	//display widget
	function widget($args, $instance) {
		global $post;
		extract($args);

		$bs_general = get_option('bs_general');

		// include thumb resize scripts
        require_once( "php/aq_resizer.php" );

		echo $before_widget;
		$title = apply_filters('widget_title', $instance['title'] );
		$bs_button_titles = $instance['bs_button_titles'];
		$bs_button_icons = $instance['bs_button_icons'];
		$bs_width = $instance['bs_width'];
		$bs_height = $instance['bs_height'];
		$bs_margin_left = $instance['bs_margin_left'];
		$bs_prod_title_color = $instance['bs_prod_title_color'];
		$bs_prod_bg_color = $instance['bs_prod_bg_color'];
		$bs_prod_margin = $instance['bs_prod_margin'];
		$bs_show_title = $instance['bs_show_title'];
		$bs_show_title_popup = $instance['bs_show_title_popup'];
		$bs_show_sel_title = $instance['bs_show_sel_title'];
		$bs_show_icons = $instance['bs_show_icons'];
		$bs_buttons_margin = $instance['bs_buttons_margin'];
		$bs_buttons_align = $instance['bs_buttons_align'];
		$bs_slide_duration = $instance['bs_slide_duration'];
		$bs_slide_easing = $instance['bs_slide_easing'];
		$bs_arrow_duration = $instance['bs_arrow_duration'];
		$bs_arrow_easing = $instance['bs_arrow_easing'];
		$bs_video_width = $instance['bs_video_width'];
		$bs_video_height = $instance['bs_video_height'];
		$bs_iframe_width = $instance['bs_iframe_width'];
		$bs_iframe_height = $instance['bs_iframe_height'];
		$bs_categories = $instance['bs_categories'];
		$bs_input_order = $instance['bs_input_order'];
		$bs_exclude_products = $instance['bs_exclude_products'];

		if ( !empty( $title ) ) { echo $before_title . $title . $after_title; };

		global $id_count;
		$id_count++;

		$percent_width = strpos($bs_width, '%');
		if ($percent_width !== false) { $bs_width = "'" . $bs_width . "'"; }
        
        ////////////////////////////////////////////////
        // open css file
        $plugin_dir = plugin_dir_url(__FILE__);
        $css_file_name = $plugin_dir . 'css/skin01.css';
        $css_class = 'sk01';

        echo "<div><script type='text/javascript'>
        /* <![CDATA[ */
            jQuery(window).load(function(){
                var fileref = document.createElement('link');
                fileref.setAttribute('rel', 'stylesheet');
                fileref.setAttribute('type', 'text/css');
                fileref.setAttribute('href', '" . $css_file_name . "');
                if (typeof fileref != 'undefined') {
                    document.getElementsByTagName('head')[0].appendChild(fileref);
                }
            });
        /* ]]> */
        </script></div>";
        ////////////////////////////////////////////////

		echo "<script type='text/javascript'>
		/* <![CDATA[ */
			////jQuery(document).ready(function(){
			jQuery(window).load(function(){
				jQuery.bookshelfSlider('#bookshelf_slider_" . $id_count . "', {
					'item_width': " . $bs_width . ",
					'item_height': " . $bs_height . ",
					'products_box_margin_left': " . $bs_margin_left . ", 
					'product_title_textcolor': '" . $bs_prod_title_color . "', 
					'product_title_bgcolor': '" . $bs_prod_bg_color . "', 
					'product_margin': " . $bs_prod_margin . ",
					'product_show_title': " . $bs_show_title . ",
					'show_title_in_popup': " . $bs_show_title_popup . ",
					'show_selected_title': " . $bs_show_sel_title . ",
					'show_icons': " . $bs_show_icons . ",
					'buttons_margin': " . $bs_buttons_margin . ",
					'buttons_align': '" . $bs_buttons_align . "',
					'slide_duration': " . $bs_slide_duration . ",
					'slide_easing': '" . $bs_slide_easing . "', 
					'arrow_duration': " . $bs_arrow_duration . ",
					'arrow_easing': '" . $bs_arrow_easing . "', 
					'video_width_height': [" . $bs_video_width . "," . $bs_video_height . "],
					'iframe_width_height': [" . $bs_iframe_width . "," . $bs_iframe_height . "],
                    'shelf_space': 'small',
		            'css_class': 'skin01'
				});
			});
		/* ]]> */
		</script>";
		?>

        <div id="bookshelf_slider_<?php echo $id_count; ?>" class="bookshelf_slider <?php echo $css_class; ?>">

        	<!-- PANEL TITLE -->

            <div class="panel_title <?php echo $css_class; ?>">
                <div class="selected_title_box <?php echo $css_class; ?>"><div class="selected_title <?php echo $css_class; ?>">Selected Title</div></div>
                <div class="bs_menu_top <?php echo $css_class; ?>">
                    <ul>
                    	<?php if($bs_button_titles != '') { ?>
                        <li class="show_hide_titles <?php echo $css_class; ?>"><a href="#"><?php echo $bs_button_titles; ?></a></li>
                        <?php } ?>

                        <?php if($bs_button_icons != '') { ?>
                        <li class="show_hide_icons <?php echo $css_class; ?>"><a href="#"><?php echo $bs_button_icons; ?></a></li>
                        <?php } ?>
                    </ul>
                </div>
			</div>

            <!-- PANEL SLIDER -->

            <div class="panel_slider <?php echo $css_class; ?>">
                <div class="panel_items <?php echo $css_class; ?>">
                    <?php
					echo "<div class='plugin_dir' style='display:none;'>$plugin_dir</div>";

					$bs_general = get_option('bs_general');

					$new_bs_input_order = array();
					if (is_array($bs_input_order)) {
						foreach ($bs_input_order as $value) {
					  		if ( $value != '' ) array_push($new_bs_input_order, $value); 
						}
					}

					$arrTmp = array();
					$catsSelected = array();
					$x = 0;
					if (count($bs_categories) > 0) {
						foreach ($bs_categories as $v) {
                            $orderTmp = ( !isset($new_bs_input_order[$x]) ) ? $x : $new_bs_input_order[$x]; 
							$arrTmp[$v] = $orderTmp;
							$x++;
						}

						asort($arrTmp);

						foreach ($arrTmp as $key => $val) {
							array_push($catsSelected, $key);
						}

						$len_cats = count($catsSelected);
                        
                        if ($len_cats > 0) {
                            for ($i=1; $i <= $len_cats; $i++) {

                                echo "<div class='slide_animate $css_class'>";
                                    echo "<div class='products_box $css_class' id='products_box_$i'>";

                                        if ($bs_exclude_products != '') {
                                            $bs_exclude_products_arr = explode (',', $bs_exclude_products);
                                        } else {
                                            $bs_exclude_products_arr = '';
                                        }

                                        $j = $i-1;
                                        $ct_wp_query = new WP_Query();
                                        $ct_wp_query->query( array('post__not_in'=>$bs_exclude_products_arr, 'post_type' => 'bookshelf', 'bookshelf_category' => $catsSelected[$j], 'post_status' => 'publish', 'posts_per_page' => -1, 'nopaging' => true, 'suppress_filters' => 0) );

                                        if ( $ct_wp_query->have_posts() ) : while ( $ct_wp_query->have_posts() ) : $ct_wp_query->the_post();

                                            $bs_p_type = get_post_meta($post->ID,'_bs_product_type',true);
                                            $bs_p_url = get_post_meta($post->ID,'_bs_product_url',true);										
                                            $bs_p_popup = get_post_meta($post->ID,'_bs_product_popup',true);
                                            $bs_p_new_window = get_post_meta($post->ID,'_bs_product_new_window',true);
                                            $bs_p_width = get_post_meta($post->ID,'_bs_product_width',true); 
                                            if ($bs_p_width == '') $bs_p_width = '80';
                                            $bs_p_height = get_post_meta($post->ID,'_bs_product_height',true); 
                                            if ($bs_p_height == '') $bs_p_height = '107';
                                            $bs_p_thumb_url = trim(get_post_meta($post->ID,'_bs_product_thumb_url',true));

                                            $post_type = 'bookshelf';
                                            $the_id = get_the_ID();
                                            $the_title = get_the_title();
                                            //enable shortcode
                                            //$the_content = apply_filters('the_content', get_the_content());


                                            //////////////////////////
                                            $use_default_image = false;

                                            if ( $bs_p_thumb_url == '' && !has_post_thumbnail($post->ID) ) {
                                                $use_default_image = true;
                                                $bs_p_thumb_url = $plugin_dir . 'images/default_image.jpg';
                                            }

                                            if ($use_default_image) {
                                                echo "<div class='bs_product $css_class' data-id='$the_id' data-post-type='$post_type' data-type='$bs_p_type' data-popup='$bs_p_popup' data-newwindow='$bs_p_new_window' data-url='$bs_p_url' title='$the_title'><img src='$bs_p_thumb_url' alt='' width='$bs_p_width' height='$bs_p_height'/></div>";

                                            } elseif ($bs_p_thumb_url != '') {

                                                //$image = aq_resize( $bs_p_thumb_url, $bs_p_width, $bs_p_height, true ); //resize & crop img

                                                //echo "<div class='bs_product $css_class' data-id='$the_id' data-post-type='$post_type' data-type='$bs_p_type' data-popup='$bs_p_popup' data-newwindow='$bs_p_new_window' data-url='$bs_p_url' title='$the_title'><img src='$image' alt='' width='$bs_p_width' height='$bs_p_height'/></div>";

                                                //no crop
                                                echo "<div class='bs_product $css_class' data-id='$the_id' data-post-type='$post_type' data-type='$bs_p_type' data-popup='$bs_p_popup' data-newwindow='$bs_p_new_window' data-url='$bs_p_url' title='$the_title'><img src='$bs_p_thumb_url' alt='' width='$bs_p_width' height='$bs_p_height'/></div>";

                                            } elseif (has_post_thumbnail($post->ID)) {

                                                $thumb = get_post_thumbnail_id();
                                                $img_url = wp_get_attachment_url( $thumb,'full'); //get img URL
                                                $image = aq_resize( $img_url, $bs_p_width, $bs_p_height, true ); //resize & crop img

                                                echo "<div class='bs_product $css_class' data-id='$the_id' data-post-type='$post_type' data-type='$bs_p_type' data-popup='$bs_p_popup' data-newwindow='$bs_p_new_window' data-url='$bs_p_url' title='$the_title'><img src='$image' alt='' width='$bs_p_width' height='$bs_p_height'/></div>";
                                            }

                                        endwhile; else:
                                        endif;
                                        // Reset Post Data
                                        wp_reset_postdata();

                                    echo "</div>";
                                echo "</div>";
                            }//for
                        }//if len_cats
					}//if
					?>
				</div><!-- panel_items -->
			</div><!-- panel_slider -->

            <!-- PANEL BAR -->

            <div class="panel_bar <?php echo $css_class; ?>">
            	<div class='buttons_container <?php echo $css_class; ?>'>
                <div id="arrow_box"><div id="arrow_menu"></div></div>
                <div class="button_items <?php echo $css_class; ?>">
                    <?php
                    if ($len_cats > 0) {
                        for ($i=0; $i < $len_cats; $i++) {
                            $num = $i+1;
                            $getTermBy = get_term_by('slug', $catsSelected[$i], 'bookshelf_category');
                            echo "<div id='btn$num' class='button_bar $css_class'><a href='#'>" . $getTermBy->name . "</a></div>";
                        }
                    }
					?>
                </div>
                </div>
            </div>

		</div><!-- #bookshelf_slider -->
		<?php
		echo $after_widget;
	}
}

function bs_register_settings() {
	//register Array of settings
	register_setting( 'bs-settings-group', 'bs_options' ); //shortcodes
	register_setting( 'bs-general-settings', 'bs_general' ); //general settings
}


// ---------------------------------------
// general settings
// ---------------------------------------

function bs_general_settings() {
	include_once( "php/admin/general_settings.php" );
}


// ---------------------------------------
// shortcode settings
// ---------------------------------------

function bs_settings_shorcode() {
	include_once( "php/admin/shortcode_settings.php" );
}//bs_settings_shorcode


// ---------------------------------------
// add bookshelf post type
// ---------------------------------------

function post_type_bookshelf() {

	$labels = array(
		'name' => __( 'Bookshelf','bs-plugin' ),
		'singular_name' => __( 'Bookshelf','bs-plugin' ), 
		'add_new' => __( 'Add Product','bs-plugin' ), //_x( 'Add New','Bookshelf','bs-plugin' ),
		'add_new_item' => __( 'Add Bookshelf Product','bs-plugin' ),
		'edit' => __( 'Edit Bookshelf Products','bs-plugin' ),
		'edit_item' => __( 'Edit Bookshelf Product','bs-plugin' ), 
		'new_item' => __( 'New Bookshelf Product','bs-plugin' ),
		'view_item' => __( 'View Bookshelf Product','bs-plugin' ),
		'search_items' => __( 'Search Bookshelf','bs-plugin' ), 
		'not_found' =>  __( 'No Bookshelf product found','bs-plugin' ), 
		'not_found_in_trash' => __( 'No Bookshelf product found in Trash','bs-plugin' ), 
		'parent_item_colon' => '',
		'menu_name' => 'Bookshelf Slider'
	);

	$iconPath = plugin_dir_url(__FILE__) . "images/bs_icon.png";
	$args = array(
		'exclude_from_search' => true,
		'labels' => $labels,
		'public' => true, 
		'show_ui' => true, 
		'show_in_menu' => true, 
		'query_var' => true,
		'rewrite' => true,
		//'rewrite' => array( 'slug' => __('bookshelf', 'bs-plugin') ),
		'capability_type' => 'post',
		'menu_position' => 5.5, 
		'menu_icon'=> $iconPath, 
		//'register_meta_box_cb' => 'Bookshelf_meta_boxes',
		'supports' => array('title', 'editor', 'thumbnail', 'custom-fields')
	 );

	 //register Bookshelf post type
	 register_post_type('bookshelf', $args);

	//register category for Bookshelf
	register_taxonomy_for_object_type('bookshelf_category', 'bookshelf');
}


// ---------------------------------------
// add bookshelf category taxonomy
// ---------------------------------------

function create_Bookshelf_cat_tax() {

	$labels = array(
		'name' => __( 'Bookshelf Categories','bs-plugin' ),
		'singular_name' => __( 'Bookshelf Category','bs-plugin' ), 
		'search_items' => __( 'Search Bookshelf Category','bs-plugin' ),
		'parent_item' => __( 'Parent Bookshelf Category','bs-plugin' ),
		'parent_item_colon' => __( 'Parent Bookshelf Category','bs-plugin' ),
		'edit_item' => __( 'Edit Bookshelf Category','bs-plugin' ), 
		'update_item' => __( 'Update Bookshelf Category','bs-plugin' ), 
		'add_new_item' => __( 'Add New Bookshelf Category','bs-plugin' ),
		'new_item_name' => __( 'New Bookshelf Category Name','bs-plugin' ),
		'new_item' => __( 'New Bookshelf Category Item','bs-plugin' ),
		'view_item' => __( 'View Bookshelf Category Item','bs-plugin' )
	);

	$args = array(
		'labels' => $labels,
		'hierarchical' => true
	);

	register_taxonomy('bookshelf_category', 'bookshelf', $args);
}


// ---------------------------------------
// enable thumbnails for bookshelf
// ---------------------------------------

if ( !function_exists('fb_AddThumbColumn') && !function_exists('bookshelf_taxonomy_custom_column') && function_exists('add_theme_support') ) {

	// thumb for bookshelf
	add_theme_support('post-thumbnails', array( 'bookshelf' ) );

	function fb_AddThumbColumn($cols) { 
		$cols['thumbnail'] = __('Thumbnail');
		return $cols;
	}

	function fb_AddBookshelfCategoryColumn($cols) { 
		$cols['bookshelf_categories'] = __('Bookshelf Categories','bs-plugin');
		return $cols;
	}

	function fb_AddThumbValue($column_name, $post_id) {

		// avoids duplicate thumbnails
		global $typenow;
		//if ($typenow != 'bookshelf') return;

		if ($typenow == 'bookshelf') {

			$width = (int) 60;
			$height = (int) 60;
 
 
			if ( 'thumbnail' == $column_name ) {
				// thumbnail of WP 2.9
				$thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true );
				// image from gallery
				$attachments = get_children( array('post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image') );
				if ($thumbnail_id) {
					$thumb = wp_get_attachment_image( $thumbnail_id, array($width, $height), true );
				} elseif (get_post_meta( $post_id, '_bs_product_thumb_url', true)) {
					$thumb = '<img width="60" height="60" src="' . get_post_meta( $post_id, '_bs_product_thumb_url', true) . '"/>';
				} elseif ($attachments) {
					foreach ( $attachments as $attachment_id => $attachment ) {
						$thumb = wp_get_attachment_image( $attachment_id, array($width, $height), true );
					}
				}
					if ( isset($thumb) && $thumb ) {
						echo $thumb;
					} else {
						echo __('None','bs-plugin');
					}
			}
		}
	}

	// print the bookshelf taxonomy terms, linked to filter the posts to this taxonomy term only
	function bookshelf_taxonomy_custom_column($column_name) {
		global $post;
		if ('bookshelf_categories' == $column_name) {
			$cats = get_the_terms($post->ID, 'bookshelf_category');
			if (!empty($cats)) {
				$theCats = array();
				foreach ($cats as $cat) {					
					$theCats[] = "<a href='edit.php?post_type=bookshelf&bookshelf_category=$cat->slug'>" . esc_html(sanitize_term_field('name', $cat->name, $cat->term_id, 'bookshelf_category', 'display')) . "</a>";
				}
				echo implode(', ', $theCats);
			}
		}
	}

	//actions and filters	
	add_filter( 'manage_bookshelf_posts_columns', 'fb_AddThumbColumn' );
	add_action( 'manage_posts_custom_column', 'fb_AddThumbValue', 10, 2 );
	add_filter( "manage_edit-bookshelf_columns", "bookshelf_edit_columns" ); //order columns

	add_filter( 'manage_bookshelf_posts_columns', 'fb_AddBookshelfCategoryColumn' );
	add_action( 'manage_bookshelf_posts_custom_column', 'bookshelf_taxonomy_custom_column', 10, 2 ); //bookshelf Categories column

}

//edit custom columns display for backend
function bookshelf_edit_columns($columns) {
	$columns = array(
		"cb" => "<input type=\"checkbox\" />",
		"title" => __('Title', 'bs-plugin'), 
		"thumbnail" => __('Thumbnail', 'bs-plugin'), 
		"bookshelf_categories" => __('Bookshelf Categories', 'bs-plugin'), 
		//"description" => __('Description', 'bs-plugin'),
		"date" => __('Date', 'bs-plugin')
	);
	return $columns;
}


// ---------------------------------------------------
// Show Categories Filter on Custom Post Type List
// ---------------------------------------------------

function bs_my_restrict_manage_posts() {
	global $typenow; //bookshelf
	$taxonomy = $typenow.'_category'; //bookshelf_category
	if( $typenow != "page" && $typenow != "post" && $typenow == "bookshelf"){
		$filters = array($taxonomy);
		foreach ($filters as $tax_slug) {
			$tax_obj = get_taxonomy($tax_slug);
			$tax_name = $tax_obj->labels->name;
			$terms = get_terms($tax_slug);
			echo "<select name='$tax_slug' id='$tax_slug' class='postform'>";
			echo "<option value=''>Show All $tax_name</option>";
			foreach ($terms as $term) { 
				echo '<option value='. $term->slug, ( isset($_GET[$tax_slug]) && $_GET[$tax_slug] == $term->slug ) ? ' selected="selected"' : '','>' . $term->name .' (' . $term->count .')</option>'; 
			}
			echo "</select>";
		}
	}
}
add_action( 'restrict_manage_posts', 'bs_my_restrict_manage_posts' );

// ---------------------------------------------------
// add style/script
// ---------------------------------------------------

function bs_add_script_style() {
	$plugin_dir = plugin_dir_url(__FILE__);

	wp_enqueue_style("bookshelf-style", $plugin_dir . "css/bookshelf_slider.css", false, "1.0", "all");
	wp_enqueue_style("bookshelf-skin01", $plugin_dir . "css/skin01.css", false, "1.0", "all");
	wp_enqueue_style("bookshelf-skin01_medium", $plugin_dir . "css/skin01_medium.css", false, "1.0", "all");

	$bs_general = get_option('bs_general');
	$bs_gs_open_bookshelf_script = $bs_general['gs_open_bookshelf_script'];

	if ($bs_gs_open_bookshelf_script == 'open_in_header') {
		wp_enqueue_script("bookshelf_script", $plugin_dir . "js/jquery.bookshelfslider.min.js", array('jquery'), "2.13", false);
	} else {
		wp_enqueue_script("bookshelf_script", $plugin_dir . "js/jquery.bookshelfslider.min.js", array('jquery'), "2.13", true); //footer
	}

	//add mediaelement
	wp_enqueue_style( 'wp-mediaelement' );
	wp_enqueue_script( 'wp-mediaelement' );

	//ajax
	// Get current page protocol
    $protocol = isset( $_SERVER["HTTPS"]) ? 'https://' : 'http://';
    // Output admin-ajax.php URL with same protocol as current page
    $params = array( 'ajaxurl' => admin_url( 'admin-ajax.php', $protocol ) );
    wp_localize_script( 'bookshelf_script', 'bookshelf_script', $params );
}
add_action('init', 'bs_add_script_style');


function bs_add_script_style_adm() {
	$plugin_dir = plugin_dir_url(__FILE__);
	wp_enqueue_style("bookshelf-util", $plugin_dir . "css/bookshelf_util.css", false, "1.0", "all");
	wp_enqueue_script("bookshelf-util", $plugin_dir . "js/bookshelf_util.js", array('jquery'), "1.0", false);
}
add_action('admin_init', 'bs_add_script_style_adm');


// ---------------------------------------
// Ajax handler
// ---------------------------------------

add_action('wp_ajax_nopriv_bs_query_ajax', 'bs_query_ajax');
add_action('wp_ajax_bs_query_ajax', 'bs_query_ajax');
function bs_query_ajax() {
	
	//pegando o post sem precisar do loop - mais simples
	$post_id = $_REQUEST['post_id'];
	$post_object = get_post( $post_id );
	//echo $post_object->post_content;

	///////
	$the_content = apply_filters('the_content', $post_object->post_content);
	echo $the_content;
	///////

	die();

	/*
	//setup Query OPTION 1 - usando WP_Query()
	$bs_wp_query = new WP_Query();
	$bs_wp_query->query( array('p' => $_REQUEST['post_id'], 'post_type' => $_REQUEST['post_posttype']) );

	if ( $bs_wp_query->have_posts() ) : while ( $bs_wp_query->have_posts() ) : $bs_wp_query->the_post();
		$the_content = apply_filters('the_content', get_the_content());
		echo $the_content;
	endwhile; else:
			echo "post not found.";
	endif;
	// reset Query
	wp_reset_query(); die();
	*/

	/*
	// setup Query OPTION 2 - ORIGINAL
	query_posts('p=' . absint( $_REQUEST['post_id'] ) . '&post_type=' . $_REQUEST['post_posttype']);

    if ( have_posts() ) : while ( have_posts() ) : the_post();
		//echo get_the_content();
		$the_content = apply_filters('the_content', get_the_content());
		echo $the_content;
    endwhile; else:
        echo "post not found.";
    endif;

    // reset Query
    wp_reset_query(); die();
	*/
}


// ---------------------------------------------------
// languages
// ---------------------------------------------------

function languages_init() {
	load_plugin_textdomain( 'bs-plugin', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
add_action('plugins_loaded', 'languages_init');


// ---------------------------------------------------
// multisite
// ---------------------------------------------------

add_shortcode( 'bookshelf_multisite', 'bs_multisite_network_posts' );

function bs_multisite_network_posts( $attr ) {
	extract( shortcode_atts( array(
			"blogid" => '1',
			"postid" => '1',
			"posttype" => 'page'
			), $attr ) );

	if ( is_multisite() ) {

		$return_post = '';

		//switch to site set in the shortcode
		switch_to_blog( absint( $blogid ) );

		if ($posttype == 'page') {
			$page_data = get_page( $postid );
			$return_post = apply_filters('the_content', $page_data->post_content);
		} else {
			$post_data = get_post( $postid );
			$return_post = apply_filters('the_content', $post_data->post_content);
		}

		//restore the current site
		restore_current_blog();

		//return the results to display
		return $return_post;
	}
}
?>