<?php
/**
 * Portfolios_List Widget Class
 */
class Theme_Widget_Portfolios_List extends WP_Widget {

	function Theme_Widget_Portfolios_List() {
		$widget_ops = array('classname' => 'widget_portfolios_list', 'description' => __( "Displays the portfolios on your site", THEME_ADMIN_DOMAIN) );
		$this->WP_Widget('portfolios_list', THEME_SLUG.' - '.__('Portfolio List', THEME_ADMIN_DOMAIN), $widget_ops);
		$this->alt_option_name = 'widget_portfolios_list';

		add_action( 'save_post', array(&$this, 'flush_widget_cache') );
		add_action( 'deleted_post', array(&$this, 'flush_widget_cache') );
		add_action( 'switch_theme', array(&$this, 'flush_widget_cache') );
	}

	function widget($args, $instance) {
		$cache = wp_cache_get('theme_widget_portfolios_list', 'widget');

		if ( !is_array($cache) )
			$cache = array();

		if ( isset($cache[$args['widget_id']]) ) {
			echo $cache[$args['widget_id']];
			return;
		}

		ob_start();
		extract($args);

		$title = apply_filters('widget_title', empty($instance['title']) ? __('Portfolios', THEME_FRONT_DOMAIN) : $instance['title'], $instance, $this->id_base);
		if ( !$number = (int) $instance['number'] )
			$number = 10;
		else if ( $number < 1 )
			$number = 1;
		else if ( $number > 15 )
			$number = 15;
		
		if ( !$desc_length = (int) $instance['desc_length'] )
			$desc_length = 80;
		else if ( $desc_length < 1 )
			$desc_length = 1;
			
		if ( !$title_length = (int) $instance['title_length'] )
			$title_length = '';
		else if ( $title_length < 1 )
			$title_length = '';
		$disable_thumbnail = $instance['disable_thumbnail'] ? '1' : '0';
		$use_lightbox = $instance['use_lightbox'] ? '1' : '0';
		$display_extra_type = $instance['display_extra_type'] ? $instance['display_extra_type'] :'time';
		if($display_extra_type == 'both'){
			$display_extra_type = array('time','description');
		}else{
			$display_extra_type = array($display_extra_type);
		}
		$orderby = $instance['orderby'] ? $instance['orderby'] : 'menu_order';
		$query = array(
			'showposts' => $number, 
			'nopaging' => 0, 
			'orderby'=> $orderby, 
			'post_status' => 'publish', 
			'ignore_sticky_posts' => 1,
			'suppress_filters'=>0,
			'post_type' => 'portfolio'
		);
		if(!empty($instance['cat'])){
			global $wp_version;
			if(version_compare($wp_version, "3.1", '>=')){
				$query['tax_query'] = array(
					array(
						'taxonomy' => 'portfolio_category',
						'field' => 'slug',
						'terms' => $instance['cat']
					)
				);
			}else{
				$query['taxonomy'] = 'portfolio_category';
				$query['term'] = implode(',', $instance['cat']);
			}
		}
		if(!empty($instance['portfolio_type'])){
			
			$query['meta_key'] = '_type';
			$query['meta_value'] = $instance['portfolio_type'];
			$query['meta_compare'] = 'IN';
		}
		$r = new WP_Query($query);
		if ($r->have_posts()) :
?>
		<?php echo $before_widget; ?>
		<?php if ( $title ) echo $before_title . $title . $after_title; ?>
		<ul class="posts_list">
<?php  while ($r->have_posts()) : $r->the_post(); ?>
			<li>
<?php if(!$disable_thumbnail):?>
<?php
			if($use_lightbox){
				$image_title = get_the_title();
				if (has_post_thumbnail()) {
					$image = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_id()), 'full', true);
					$type = get_post_meta(get_the_id(), '_type', true);
					if($type == 'image'){
						$href =  get_post_meta(get_the_id(), '_image', true);
						if(!empty($href)){
							$href = theme_parse_image($href,null,true);
							$href = $href['media'];
						}else
							$href = $image[0];					
						$rel = 'prettyPhoto';
					}elseif($type == 'video'){
						$href =  get_post_meta(get_the_id(), '_video', true);
						$video_width =  get_post_meta(get_the_id(), '_video_width', true);
						$video_height =  get_post_meta(get_the_id(), '_video_height', true);
						$video_size = '';
						if(!empty($video_width) && is_numeric($video_width)){
							$video_size .= 'width='.$video_width;
						}else{
							$video_size .= 'width='.theme_get_option('portfolio','video_width');
						}

						if(!empty($video_height) && is_numeric($video_height)){
							$video_size = '&amp;height='.$video_height;
						}else{
							$video_size .= '&amp;height='.theme_get_option('portfolio','video_height');
						}
						if(empty($href)){
							$href = $image[0];
						}
						$href=$href.'?'.$video_size;
						$rel = 'prettyPhoto';
					}elseif($type == 'doc'){
						global $theme_inline_id;
						$theme_inline_id = md5(uniqid(rand()));
						$href="#inline-".$theme_inline_id;
						$content =  get_post_meta(get_the_id(), '_lightbox_content', true);
						$lightbox_width = get_post_meta(get_the_id(), '_lightbox_doc_width', true);
						$lightbox_height = get_post_meta(get_the_id(), '_lightbox_doc_height', true);
						if(empty($lightbox_width) || !is_numeric($lightbox_width)){
							$lightbox_width =theme_get_option('portfolio','lightbox_width');
						}

						if(empty($lightbox_height) || !is_numeric($lightbox_height)){
							$lightbox_height =theme_get_option('portfolio','lightbox_height');
						}
						$content='<div id="inline-'.$theme_inline_id.'" class="hide" style="width:'.$lightbox_width.'px;height:'.$lightbox_height.'px">'.do_shortcode($content).'</div>';
						$rel = 'prettyPhoto';
					}elseif($type == 'iframe'){
						$href =  get_post_meta(get_the_id(), '_lightbox_href', true);
						$lightbox_width = get_post_meta(get_the_id(), '_lightbox_iframe_width', true);
						$lightbox_height = get_post_meta(get_the_id(), '_lightbox_iframe_height', true);
						$lightbox_size = '';
						if(!empty($lightbox_width) && is_numeric($lightbox_width)){
							$lightbox_size .= 'width='.$lightbox_width;
						}else{
							$lightbox_size .= 'width='.theme_get_option('portfolio','lightbox_width');
						}

						if(!empty($lightbox_height) && is_numeric($lightbox_height)){
							$lightbox_size = '&amp;height='.$lightbox_height;
						}else{
							$lightbox_size .= '&amp;height='.theme_get_option('portfolio','lightbox_height');
						}
						$href=$href.'?iframe=true&'.$lightbox_size;
						$rel = 'prettyPhoto';
					}elseif($type == 'link'){
						$link = get_post_meta(get_the_ID(), '_link', true);
						$href = theme_get_superlink($link);
						$link_target = get_post_meta(get_the_ID(), '_link_target', true);
						$link_target = $link_target?$link_target:'_self';
						$lightbox = '';
						$rel = '';
					}elseif($type == 'gallery'){
						$image_ids_str = get_post_meta(get_the_id(), '_image_ids', true);
						$image_ids = array();
						if(!empty($image_ids_str)){
							$image_ids = explode(',',str_replace('image-','',$image_ids_str));
							$image_src = wp_get_attachment_image_src(array_pop($image_ids),'full');
							$href = $image_src[0];
						}else{
							$href =  get_post_meta(get_the_id(), '_image', true);
							if(empty($href)){
								$href = $image[0];
							}
						}
						$rel = 'prettyPhoto';
						$image_title = get_the_title($image_ids[0]);
					}else{
						$href = get_permalink();
						$rel = 'prettyPhoto';
					}
				}else{
					$type = 'image';
					$image_source = theme_get_option('portfolio','default_portfolio_image');
					$image_source = theme_parse_image($image_source,'post-image-placer.png',true);
					$source_type = $image_source['method'];
					$image_source = $image_source['media'];
					$href = theme_parse_image($image_source,'post-image-placer.png',false);
					$href = $href['media'];
					$rel = 'prettyPhoto';
				}

				
				if($type == 'gallery' && !empty($image_ids)){
					echo '<div style="display:none">';
					foreach($image_ids as $image_id){
						$image_src = wp_get_attachment_image_src($image_id,'full');
						$image_title = get_the_title($image_id);
						echo '<a title="'.$image_title.'" href="'.$image_src[0].'" rel="prettyPhoto'.'['.strtolower(get_the_title()).']'.'">gallery-'.get_the_ID().'</a>';
					}
					echo '</div>';
				}
				echo '<a class="thumbnail" title="'.$image_title.'" href="'.$href.'" '.(isset($link_target)?' target="'.$link_target.'" ':'').' rel="'.$rel.(($type == 'gallery')?'['.strtolower(get_the_title()).']':'').'">';
				if($type =='doc'){
					echo $content;
				}

			}else{
				echo '<a class="thumbnail" href="'.get_permalink().'" title="'.get_the_title().'">';
			}
?>

<?php if (has_post_thumbnail() ): ?>
					<?php the_post_thumbnail(array(65,65),array('title'=>get_the_title(),'alt'=>get_the_title())); ?>	
<?php  elseif(theme_get_option('portfolio','display_default_thumbnail')):
		$default_thumbnail_custom = theme_get_option('portfolio','default_thumbnail_custom');
		$image = theme_parse_image($default_thumbnail_custom,'widget_posts_thumbnail.png',false);
		$resize = theme_resize($image['media'],65,65,$image['method']);
?>
					<img src="<?php echo $resize['url'];?>" width="65" height="65" title="<?php the_title();?>" alt="<?php the_title();?>"/>
<?php endif;//end has_post_thumbnail ?>
				</a>
<?php endif;//disable_thumbnail ?>
				<div class="post_extra_info">
					<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php echo esc_attr(get_the_title() ? get_the_title() : get_the_ID()); ?>"><?php if ( get_the_title() ) { if($title_length && mb_strlen(get_the_title())>$title_length){echo mb_substr(get_the_title(),0,$title_length).'...';}else{the_title();} }else the_ID(); ?></a>
<?php if(in_array('time', $display_extra_type)):?>
					<time datetime="<?php the_time('Y-m-d') ?>"><?php echo get_the_date(); ?></time>
<?php endif;?>
<?php if(in_array('description', $display_extra_type)):?>
	<p><?php 
		$excerpt = wp_html_excerpt(get_the_excerpt(),$desc_length);
		$excerpt = empty($excerpt) ? '':$excerpt.'...';		
		echo $excerpt;		
	?></p>
<?php endif;//end display extra type ?>
				</div>
				<div class="clear"></div>
			</li>
<?php endwhile; ?>
		</ul>
		<?php echo $after_widget; ?>
<?php
		// Reset the global $the_post as this query will have stomped on it
		wp_reset_query();

		endif;

		$cache[$args['widget_id']] = ob_get_flush();
		wp_cache_set('theme_widget_portfolios_list', $cache, 'widget');
	}

	function update( $new_instance, $old_instance ) {
		$instance = $old_instance;
		$instance['title'] = strip_tags($new_instance['title']);
		$instance['number'] = (int) $new_instance['number'];
		$instance['desc_length'] = (int) $new_instance['desc_length'];
		$instance['disable_thumbnail'] = !empty($new_instance['disable_thumbnail']) ? 1 : 0;
		$instance['use_lightbox'] = !empty($new_instance['use_lightbox']) ? 1 : 0;
		$instance['display_extra_type'] = $new_instance['display_extra_type'];
		$instance['cat'] = $new_instance['cat'];
		$instance['portfolio_type'] = $new_instance['portfolio_type'];
		$instance['title_length'] = (int) $new_instance['title_length'];
		$instance['orderby'] = $new_instance['orderby'];
		
		$this->flush_widget_cache();

		$alloptions = wp_cache_get( 'alloptions', 'options' );
		if ( isset($alloptions['theme_widget_portfolios_list']) )
			delete_option('theme_widget_portfolios_list');

		return $instance;
	}

	function flush_widget_cache() {
		wp_cache_delete('theme_widget_portfolios_list', 'widget');
	}

	function form( $instance ) {
		$title = isset($instance['title']) ? esc_attr($instance['title']) : '';
		$disable_thumbnail = isset( $instance['disable_thumbnail'] ) ? (bool) $instance['disable_thumbnail'] : false;
		$use_lightbox = isset( $instance['use_lightbox'] ) ? (bool) $instance['use_lightbox'] : false;
		$display_extra_type = isset( $instance['display_extra_type'] ) ? $instance['display_extra_type'] : 'time';
		$cat = isset($instance['cat']) ? $instance['cat'] : array();
		$portfolio_type = isset($instance['portfolio_type']) ? $instance['portfolio_type'] : array();
		$orderby = isset( $instance['orderby'] ) ? $instance['orderby'] : 'menu_order';
		
		if ( !isset($instance['number']) || !$number = (int) $instance['number'] )
			$number = 5;

		if ( !isset($instance['desc_length']) || !$desc_length = (int) $instance['desc_length'] )
			$desc_length = 80;
		if ( !isset($instance['title_length']) || !$title_length = (int) $instance['title_length'] )
			$title_length = '';
		$categories = get_terms('portfolio_category','orderby=name&hide_empty=0&suppress_filters=0');
		$portfolio_type_array = array(
			"image" => __('Image',THEME_ADMIN_DOMAIN),
			"gallery" => __('Gallery',THEME_ADMIN_DOMAIN),
			"video" => __('Video',THEME_ADMIN_DOMAIN),
			"doc" => __('Document',THEME_ADMIN_DOMAIN),
			"link" => __('Link',THEME_ADMIN_DOMAIN),
			"lightbox" => __('Lightbox',THEME_ADMIN_DOMAIN),
		);
?>
		<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:',THEME_ADMIN_DOMAIN); ?></label>
		<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></p>

		<p><label for="<?php echo $this->get_field_id('number'); ?>"><?php _e('Number of posts to show:', THEME_ADMIN_DOMAIN); ?></label>
		<input id="<?php echo $this->get_field_id('number'); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="text" value="<?php echo $number; ?>" size="3" /></p>

		<p><input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('disable_thumbnail'); ?>" name="<?php echo $this->get_field_name('disable_thumbnail'); ?>"<?php checked( $disable_thumbnail ); ?> />
		<label for="<?php echo $this->get_field_id('disable_thumbnail'); ?>"><?php _e( 'Disable Post Thumbnail?' , THEME_ADMIN_DOMAIN); ?></label></p>

	
		<p><input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('use_lightbox'); ?>" name="<?php echo $this->get_field_name('use_lightbox'); ?>"<?php checked( $use_lightbox ); ?> />
		<label for="<?php echo $this->get_field_id('use_lightbox'); ?>"><?php _e( 'Use Lightbox?', THEME_ADMIN_DOMAIN ); ?></label></p>
		
		<p><label for="<?php echo $this->get_field_id('title_length'); ?>"><?php _e('Length of Title to show:',THEME_ADMIN_DOMAIN); ?></label>
		<input id="<?php echo $this->get_field_id('title_length'); ?>" name="<?php echo $this->get_field_name('title_length'); ?>" type="text" value="<?php echo $title_length; ?>" size="3" /></p>

		
		
		<p>
			<label for="<?php echo $this->get_field_id('display_extra_type'); ?>"><?php _e( 'Display Extra infomation type:', THEME_ADMIN_DOMAIN ); ?></label>
			<select name="<?php echo $this->get_field_name('display_extra_type'); ?>" id="<?php echo $this->get_field_id('display_extra_type'); ?>" class="widefat">
				<option value="time"<?php selected($display_extra_type,'time');?>><?php _e( 'Time', THEME_ADMIN_DOMAIN ); ?></option>
				<option value="description"<?php selected($display_extra_type,'description');?>><?php _e( 'Description', THEME_ADMIN_DOMAIN ); ?></option>
					<option value="both"<?php selected($display_extra_type,'both');?>><?php _e( 'Time and Description', THEME_ADMIN_DOMAIN ); ?></option>
				<option value="none"<?php selected($display_extra_type,'none');?>><?php _e( 'None', THEME_ADMIN_DOMAIN ); ?></option>
			</select>
		</p>
		
		<p><label for="<?php echo $this->get_field_id('desc_length'); ?>"><?php _e('Length of Description to show:', THEME_ADMIN_DOMAIN); ?></label>
		<input id="<?php echo $this->get_field_id('desc_length'); ?>" name="<?php echo $this->get_field_name('desc_length'); ?>" type="text" value="<?php echo $desc_length; ?>" size="3" /></p>

		<p>
			<label for="<?php echo $this->get_field_id('cat'); ?>"><?php _e( 'Categorys:' , THEME_ADMIN_DOMAIN); ?></label>
			<select style="height:5.5em" name="<?php echo $this->get_field_name('cat'); ?>[]" id="<?php echo $this->get_field_id('cat'); ?>" class="widefat" multiple="multiple">
				<?php foreach($categories as $category):?>
				<option value="<?php echo $category->slug;?>"<?php echo in_array($category->slug, $cat)? ' selected="selected"':'';?>><?php echo $category->name;?></option>
				<?php endforeach;?>
			</select>
		</p>
		
		<p>
			<label for="<?php echo $this->get_field_id('portfolio_type'); ?>"><?php _e( 'Portfolio Type:' , THEME_ADMIN_DOMAIN); ?></label>
			<select style="height:5.5em" name="<?php echo $this->get_field_name('portfolio_type'); ?>[]" id="<?php echo $this->get_field_id('portfolio_type'); ?>" class="widefat" multiple="multiple">
				<?php foreach($portfolio_type_array as $key=>$value):?>
				<option value="<?php echo $key;?>"<?php echo in_array($key, $portfolio_type)? ' selected="selected"':'';?>><?php echo $value;?></option>
				<?php endforeach;?>
			</select>
		</p>
		
		<p>
			<label for="<?php echo $this->get_field_id('orderby'); ?>"><?php _e( 'Orderby:', THEME_ADMIN_DOMAIN ); ?></label>
			<select name="<?php echo $this->get_field_name('orderby'); ?>" id="<?php echo $this->get_field_id('orderby'); ?>" class="widefat">
				<option value="none"<?php selected($orderby,'none');?>><?php _e( 'None', THEME_ADMIN_DOMAIN ); ?></option>
				<option value="ID"<?php selected($orderby,'ID');?>><?php _e( ' Order by post id', THEME_ADMIN_DOMAIN ); ?></option>
				<option value="author"<?php selected($orderby,'author');?>><?php _e( ' Order by author', THEME_ADMIN_DOMAIN ); ?></option>
				<option value="title"<?php selected($orderby,'title');?>><?php _e( ' Order by title', THEME_ADMIN_DOMAIN ); ?></option>
				<option value="date"<?php selected($orderby,'date');?>><?php _e( 'Order by date', THEME_ADMIN_DOMAIN ); ?></option>
				<option value="modified"<?php selected($orderby,'modified');?>><?php _e( 'Order by last modified date', THEME_ADMIN_DOMAIN ); ?></option>
				<option value="rand"<?php selected($orderby,'rand');?>><?php _e( 'Random order', THEME_ADMIN_DOMAIN ); ?></option>
				<option value="comment_count"<?php selected($orderby,'comment_count');?>><?php _e( 'Order by number of comments', THEME_ADMIN_DOMAIN ); ?></option>
				<option value="menu_order"<?php selected($orderby,'menu_order');?>><?php _e( 'Order by Page Order', THEME_ADMIN_DOMAIN ); ?></option>
			</select>
		</p>
<?php
	}
}
