<?php
// **********************************************************************// 
// ! Product brand label
// **********************************************************************//

add_action( 'admin_enqueue_scripts', 'et_brand_admin_scripts' );
if(!function_exists('et_brand_admin_scripts')) {
    function et_brand_admin_scripts() {
        $screen = get_current_screen();
        if ( in_array( $screen->id, array('edit-brand') ) )
		  wp_enqueue_media();
    }
}
if(!function_exists('et_product_brand_image')) {
	function et_product_brand_image() {
		global $post, $wpdb, $product;
        $terms = wp_get_post_terms( $post->ID, 'brand' );

        if(count($terms)>0) {
        	?>
			<div class="product-brands">
	        	<?php
			        foreach($terms as $brand) {
			            $image 			= '';
			        	$thumbnail_id 	= absint( get_woocommerce_term_meta( $brand->term_id, 'thumbnail_id', true ) );
			        	if ($thumbnail_id) :
			        		$image = etheme_get_image( $thumbnail_id );
			                ?>
			                    <img src="<?php echo $image; ?>" title="<?php echo $brand->name; ?>" alt="<?php echo $brand->name; ?>" class="brand-image" />
			                <?php
			        	endif;
			        }
	        	?>
			</div>
        	<?php
        }
        

        
	}
}

add_action( 'init', 'et_create_brand_taxonomies', 0 );
if(!function_exists('et_create_brand_taxonomies')) {
	function et_create_brand_taxonomies() {
		$labels = array(
			'name'              => _x( 'Brands', WFT_DOMAIN ),
			'singular_name'     => _x( 'Brand', WFT_DOMAIN ),
			'search_items'      => __( 'Search Brands', WFT_DOMAIN ),
			'all_items'         => __( 'All Brands', WFT_DOMAIN ),
			'parent_item'       => __( 'Parent Brand', WFT_DOMAIN ),
			'parent_item_colon' => __( 'Parent Brand:', WFT_DOMAIN ),
			'edit_item'         => __( 'Edit Brand', WFT_DOMAIN ),
			'update_item'       => __( 'Update Brand', WFT_DOMAIN ),
			'add_new_item'      => __( 'Add New Brand', WFT_DOMAIN ),
			'new_item_name'     => __( 'New Brand Name', WFT_DOMAIN ),
			'menu_name'         => __( 'Brands', WFT_DOMAIN ),
		);

		$args = array(
			'hierarchical'      => true,
			'labels'            => $labels,
			'show_ui'           => true,
			'show_admin_column' => true,
			'query_var'         => true,
            'capabilities'			=> array(
            	'manage_terms' 		=> 'manage_product_terms',
				'edit_terms' 		=> 'edit_product_terms',
				'delete_terms' 		=> 'delete_product_terms',
				'assign_terms' 		=> 'assign_product_terms',
            ),
			'rewrite'           => array( 'slug' => 'brand' ),
		);

		register_taxonomy( 'brand', array( 'product' ), $args );
	}
}

add_action( 'brand_add_form_fields', 'et_brand_fields' );
if(!function_exists('et_brand_fields')) {
	function et_brand_fields() {
		global $woocommerce;
		?>
		<div class="form-field">
			<label><?php _e( 'Thumbnail', 'woocommerce' ); ?></label>
			<div id="brand_thumbnail" style="float:left;margin-right:10px;"><img src="<?php echo woocommerce_placeholder_img_src(); ?>" width="60px" height="60px" /></div>
			<div style="line-height:60px;">
				<input type="hidden" id="brand_thumbnail_id" name="brand_thumbnail_id" />
				<button type="submit" class="upload_image_button button"><?php _e( 'Upload/Add image', 'woocommerce' ); ?></button>
				<button type="submit" class="remove_image_button button"><?php _e( 'Remove image', 'woocommerce' ); ?></button>
			</div>
			<script type="text/javascript">

				 // Only show the "remove image" button when needed
				 if ( ! jQuery('#brand_thumbnail_id').val() )
					 jQuery('.remove_image_button').hide();

				// Uploading files
				var file_frame;

				jQuery(document).on( 'click', '.upload_image_button', function( event ){

					event.preventDefault();

					// If the media frame already exists, reopen it.
					if ( file_frame ) {
						file_frame.open();
						return;
					}

					// Create the media frame.
					file_frame = wp.media.frames.downloadable_file = wp.media({
						title: '<?php _e( 'Choose an image', 'woocommerce' ); ?>',
						button: {
							text: '<?php _e( 'Use image', 'woocommerce' ); ?>',
						},
						multiple: false
					});

					// When an image is selected, run a callback.
					file_frame.on( 'select', function() {
						attachment = file_frame.state().get('selection').first().toJSON();

						jQuery('#brand_thumbnail_id').val( attachment.id );
						jQuery('#brand_thumbnail img').attr('src', attachment.url );
						jQuery('.remove_image_button').show();
					});

					// Finally, open the modal.
					file_frame.open();
				});

				jQuery(document).on( 'click', '.remove_image_button', function( event ){
					jQuery('#brand_thumbnail img').attr('src', '<?php echo woocommerce_placeholder_img_src(); ?>');
					jQuery('#brand_thumbnail_id').val('');
					jQuery('.remove_image_button').hide();
					return false;
				});

			</script>
			<div class="clear"></div>
		</div>
		<?php
	}
}


add_action( 'brand_edit_form_fields', 'et_edit_brand_fields', 10,2 );
if(!function_exists('et_edit_brand_fields')) {
    function et_edit_brand_fields( $term, $taxonomy ) {
    	global $woocommerce;
    
    	$image 			= '';
    	$thumbnail_id 	= absint( get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true ) );
    	if ($thumbnail_id) :
    		$image = wp_get_attachment_thumb_url( $thumbnail_id );
    	else :
    		$image = woocommerce_placeholder_img_src();
    	endif;
    	?>
    	<tr class="form-field">
    		<th scope="row" valign="top"><label><?php _e( 'Thumbnail', 'woocommerce' ); ?></label></th>
    		<td>
    			<div id="brand_thumbnail" style="float:left;margin-right:10px;"><img src="<?php echo $image; ?>" width="60px" height="60px" /></div>
    			<div style="line-height:60px;">
    				<input type="hidden" id="brand_thumbnail_id" name="brand_thumbnail_id" value="<?php echo $thumbnail_id; ?>" />
    				<button type="submit" class="upload_image_button button"><?php _e( 'Upload/Add image', 'woocommerce' ); ?></button>
    				<button type="submit" class="remove_image_button button"><?php _e( 'Remove image', 'woocommerce' ); ?></button>
    			</div>
    			<script type="text/javascript">
    
    				// Uploading files
    				var file_frame;
    
    				jQuery(document).on( 'click', '.upload_image_button', function( event ){
    
    					event.preventDefault();
    
    					// If the media frame already exists, reopen it.
    					if ( file_frame ) {
    						file_frame.open();
    						return;
    					}
    
    					// Create the media frame.
    					file_frame = wp.media.frames.downloadable_file = wp.media({
    						title: '<?php _e( 'Choose an image', 'woocommerce' ); ?>',
    						button: {
    							text: '<?php _e( 'Use image', 'woocommerce' ); ?>',
    						},
    						multiple: false
    					});
    
    					// When an image is selected, run a callback.
    					file_frame.on( 'select', function() {
    						attachment = file_frame.state().get('selection').first().toJSON();
    
    						jQuery('#brand_thumbnail_id').val( attachment.id );
    						jQuery('#brand_thumbnail img').attr('src', attachment.url );
    						jQuery('.remove_image_button').show();
    					});
    
    					// Finally, open the modal.
    					file_frame.open();
    				});
    
    				jQuery(document).on( 'click', '.remove_image_button', function( event ){
    					jQuery('#brand_thumbnail img').attr('src', '<?php echo woocommerce_placeholder_img_src(); ?>');
    					jQuery('#brand_thumbnail_id').val('');
    					jQuery('.remove_image_button').hide();
    					return false;
    				});
    
    			</script>
    			<div class="clear"></div>
    		</td>
    	</tr>
    	<?php
    }
}

if(!function_exists('et_brands_fields_save')) {
    function et_brands_fields_save( $term_id, $tt_id, $taxonomy ) {
        
    	if ( isset( $_POST['brand_thumbnail_id'] ) )
    		update_woocommerce_term_meta( $term_id, 'thumbnail_id', absint( $_POST['brand_thumbnail_id'] ) );
    
    	delete_transient( 'wc_term_counts' );
    }
}

add_action( 'created_term', 'et_brands_fields_save', 10,3 );
add_action( 'edit_term', 'et_brands_fields_save', 10,3 );

// **********************************************************************// 
// ! AJAX Quick View
// **********************************************************************//

add_action('wp_ajax_et_product_quick_view', 'et_product_quick_view');
add_action('wp_ajax_nopriv_et_product_quick_view', 'et_product_quick_view');
if(!function_exists('et_product_quick_view')) {
	function et_product_quick_view() {
		if(empty($_GET['prodid'])) {
			echo 'Error: Absent product id';
			die();
		}

		$args = array(
			'p'=>$_GET['prodid'],
			'post_type' => 'product'
		);

		$the_query = new WP_Query( $args );
		if ( $the_query->have_posts() ) {
			while ( $the_query->have_posts() ) : $the_query->the_post();
				woocommerce_get_template('product-quick-view.php');
			endwhile;
			wp_reset_query();
			wp_reset_postdata();
		} else {
			echo 'No posts were found!';
		}
		die();
	}
}

// **********************************************************************// 
// ! Product Labels
// **********************************************************************// 

if(!function_exists('etheme_wc_product_labels')) {
	function etheme_wc_product_labels( $product_id = '' ) { 
	    echo etheme_wc_get_product_labels($product_id);
	}
}


if(!function_exists('etheme_wc_get_product_labels')) {
	function etheme_wc_get_product_labels( $product_id = '' ) {
		global $post, $wpdb,$product;
		$count_labels = 0;
		$output = '';

		if ( etheme_get_option('discount_label') ) {
			if ( $product->is_on_sale() && $product->regular_price > $product->price ) {
				$discount = 100 - $product->price * 100 / $product->regular_price;
				$output .= '<div class="sale_discount img-rounded">-'. (int) $discount . '%</div>';
			}
		}

		if ( etheme_get_option('sale_icon') ) {
			if ($product->is_on_sale()) {
				$count_labels++;
				$output .= '<div class="label_sale_top_right">'.__( 'Sale!', WFT_DOMAIN ).'</div>';
			}
		}

		$videos = get_post_meta($product->id, 'video');
		if ( !empty($videos) ) {
			$output .= '<div class="label_video_bot_right">'.__( 'Video', WFT_DOMAIN ).'</div>';
		}

		if ( etheme_get_option('new_icon') ) {
			$count_labels++;
			if(etheme_product_is_new($product_id)) {
				//$second_label = ($count_labels > 1) ? 'second_label' : '';
				$output .= '<div class="label_new_top_left">'.__( 'New!', WFT_DOMAIN ).'</div>';
			}
		}
		return $output;
	}
}

// **********************************************************************// 
// ! Get list of all product images
// **********************************************************************// 

if(!function_exists('get_images_list')) {
	function get_images_list($width, $height, $crop) {
		global $post, $product, $woocommerce;
		$images_string = '';
		$attachment_ids = $product->get_gallery_attachment_ids();
		$_i = 0;
		$images_string .= etheme_get_image(false, $width, $height, $crop);
		if(count($attachment_ids) > 0) {
			$images_string .= ',';
			foreach ($attachment_ids as $value) {
				$_i++;
				$images_string .= etheme_get_image($value, $width, $height, $crop);
				if($_i != count($attachment_ids)) 
					$images_string .= ',';
			}
		}

		return $images_string;
	}
}

// **********************************************************************// 
// ! Is product New
// **********************************************************************// 

if(!function_exists('etheme_product_is_new')) {
	function etheme_product_is_new( $product_id = '' ) {
		global $post, $wpdb;
	    $key = 'product_new';
		if(!$product_id) $product_id = $post->ID;
		if(!$product_id) return false;
	    $_etheme_new_label = get_post_meta($product_id, $key);
	    if(isset($_etheme_new_label[0]) && $_etheme_new_label[0] == 'enable') {
	        return true;
	    }
	    return false;	
	}
}

// **********************************************************************// 
// ! Grid/List switcher
// **********************************************************************//

if ( !function_exists('etheme_grid_list_switcher') ) {

	function etheme_grid_list_switcher() {

		$view_mode = etheme_get_option('view_mode', 'grid_list');

		?>


		<label> <span class="hidden-tablet">View as:</span></label>
		<a class="icon-th 777" href="#"></a>
		<a class="icon-th-list" href="#"></a>


		<?php

	}	
}

// **********************************************************************// 
// ! Catalog Mode
// **********************************************************************// 
$just_catalog = etheme_get_option('just_catalog');

function etheme_remove_loop_button(){
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
	remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
	remove_action( 'woocommerce_simple_add_to_cart', 'woocommerce_simple_add_to_cart', 30 );
	remove_action( 'woocommerce_grouped_add_to_cart', 'woocommerce_grouped_add_to_cart', 30 );
	remove_action( 'woocommerce_variable_add_to_cart', 'woocommerce_variable_add_to_cart', 30 );
	remove_action( 'woocommerce_external_add_to_cart', 'woocommerce_external_add_to_cart', 30 );
}

if($just_catalog) {
    add_action('init','etheme_remove_loop_button');
}


// **********************************************************************// 
// ! Template hooks
// **********************************************************************// 

//add_action( 'woocommerce_before_main_content', 'et_back_to_page', 40 ); // add pagination above the products

add_action( 'woocommerce_before_main_content', 'woocommerce_before_main_content_wrapper', 15 );
add_action( 'woocommerce_before_main_content', 'woocommerce_before_main_content_wrapper_end', 100 );

remove_action('woocommerce_before_shop_loop', 'woocommerce_result_count', 20);
remove_action('woocommerce_before_shop_loop', 'woocommerce_catalog_ordering', 30);
add_action('woocommerce_before_shop_loop', 'wft_listing_header_row1', 1);
add_action('woocommerce_before_shop_loop', 'wft_div_line1', 2);
add_action('woocommerce_before_shop_loop', 'wft_listing_header_row2', 3);

remove_action( 'woocommerce_after_shop_loop', 'woocommerce_pagination', 10 );
add_action( 'woocommerce_after_shop_loop', 'wft_listing_header_row1', 1 );
add_action( 'woocommerce_after_shop_loop', 'wft_div_line1', 2 );
add_action( 'woocommerce_after_shop_loop', 'wft_listing_header_row2', 3 );

remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_rating', 5 ); // remove stars from loop
// **********************************************************************// 
// ! Set number of products per page
// **********************************************************************// 
$products_per_page = etheme_get_option('products_per_page');
add_filter( 'loop_shop_per_page', create_function( '$cols', 'return '.$products_per_page.';' ), 20 );

// **********************************************************************// 
// ! Category thumbnail
// **********************************************************************// 
if(!function_exists('etheme_category_header')){
	function etheme_category_header() {
		if(function_exists('get_term_meta')){
			global $wp_query;
			$cat = $wp_query->get_queried_object();
			if(!property_exists($cat, "term_id") && !is_search()){
			    echo do_shortcode(etheme_get_option('product_bage_banner'));
			}else{
			    $image = etheme_get_option('product_bage_banner');
				$queried_object = get_queried_object(); 
				
				if (isset($queried_object->term_id)){
			
					$term_id = $queried_object->term_id;  
					$content = get_term_meta($term_id, 'cat_meta');
			
					if(isset($content[0]['cat_header'])){
						echo do_shortcode($content[0]['cat_header']);
					}
				}
			}
		}
	}
}
        
// **********************************************************************// 
// ! Review form
// **********************************************************************//   
//add_action('after_page_wrapper', 'etheme_review_form');
if(!function_exists('etheme_review_form')) {
	function etheme_review_form( $product_id = '' ) {
		global $woocommerce, $product,$post;
		$title_reply = '';
	
		if ( have_comments() ) :
			$title_reply = __( 'Add a review', WFT_DOMAIN );
	
		else :
	
			$title_reply = __( 'Be the first to review', WFT_DOMAIN ).' &ldquo;'.$post->post_title.'&rdquo;';
		endif;
	
		$commenter = wp_get_current_commenter();
	
		echo '<div id="review_form">';
		
		echo '<h4>'.__('Add your review', WFT_DOMAIN).'</h4>';
	
		$comment_form = array(
			'title_reply' => '',
			'comment_notes_before' => '',
			'comment_notes_after' => '',
			'fields' => array(
				'author' => '<p class="comment-form-author">' . '<label for="author">' . __( 'Name', WFT_DOMAIN ) . '</label> ' . '<span class="required">*</span>' .
				            '<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30" aria-required="true" /></p>',
				'email'  => '<p class="comment-form-email"><label for="email">' . __( 'Email', WFT_DOMAIN ) . '</label> ' . '<span class="required">*</span>' .
				            '<input id="email" name="email" type="text" value="' . esc_attr(  $commenter['comment_author_email'] ) . '" size="30" aria-required="true" /></p>',
			),
			'label_submit' => __( 'Submit Review', WFT_DOMAIN ),
			'logged_in_as' => '',
			'comment_field' => ''
		);
	
		if ( get_option('woocommerce_enable_review_rating') == 'yes' ) {
	
			$comment_form['comment_field'] = '<p class="comment-form-rating"><label for="rating">' . __( 'Rating', WFT_DOMAIN ) .'</label><select name="rating" id="rating">
				<option value="">'.__( 'Rate&hellip;', WFT_DOMAIN ).'</option>
				<option value="5">'.__( 'Perfect', WFT_DOMAIN ).'</option>
				<option value="4">'.__( 'Good', WFT_DOMAIN ).'</option>
				<option value="3">'.__( 'Average', WFT_DOMAIN ).'</option>
				<option value="2">'.__( 'Not that bad', WFT_DOMAIN ).'</option>
				<option value="1">'.__( 'Very Poor', WFT_DOMAIN ).'</option>
			</select></p>';
	
		}
	
		$comment_form['comment_field'] .= '<p class="comment-form-comment"><label for="comment">' . __( 'Your Review', WFT_DOMAIN ) . '</label><textarea id="comment" name="comment" cols="25" rows="8" aria-required="true"></textarea></p>' . $woocommerce->nonce_field('comment_rating', true, false);
		
		
			comment_form( apply_filters( 'woocommerce_product_review_comment_form_args', $comment_form ) );
			
		
	
		echo '</div>';
	}
}  

// **********************************************************************// 
// ! User area in account page sidebar
// **********************************************************************//   
add_action('etheme_before_account_sidebar', 'etheme_user_info',10);
if(!function_exists('etheme_user_info')) {
	function etheme_user_info() {
		global $current_user;
		get_currentuserinfo();
		if(is_user_logged_in()) {
			?>
				<div class="user-sidearea">
					<?php echo get_avatar( $current_user->id, 50 ); ?>
					<?php echo '<strong>' . $current_user->user_login . "</strong>\n"; ?>
					<br>
					<a href="<?php echo wp_logout_url(home_url()); ?>"><?php _e('Logout', WFT_DOMAIN) ?></a>
				</div>
			<?php
		}
	}
}

// **********************************************************************// 
// ! Get account sidebar position
// **********************************************************************// 

if(!function_exists('etheme_account_sidebar')) {
    function etheme_account_sidebar() {

        $result = array(
            'responsive' => '',
            'span' => 9,
            'sidebar' => etheme_get_option('account_sidebar')
        );
        
        $result['responsive'] = etheme_get_option('blog_sidebar_responsive');   

        if(!$result['sidebar']) {
            $result['span'] = 12;
        }
        
        return $result;
    }
}

// **********************************************************************// 
// ! Search form popup
// **********************************************************************//  

add_action('after_page_wrapper', 'etheme_search_form_modal');
if(!function_exists('etheme_search_form_modal')) {
	function etheme_search_form_modal() {
		?>
			<div id="searchModal" class="modal hide fade" tabindex="-1" role="dialog" aria-hidden="true">
				<div>
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
						<h3 class="title"><span><?php _e('Search', WFT_DOMAIN); ?></span></h3>
					</div>
					<div class="modal-body">
						<p class="a-center"><?php _e('Use the search box to find the product you are looking for.', WFT_DOMAIN) ?></p>
						<?php get_template_part('woosearchform'); ?>
					</div>
				</div>
			</div>
		<?php
	}
}
// **********************************************************************// 
// ! Login form popup
// **********************************************************************//  

add_action('after_page_wrapper', 'etheme_login_form_modal');
if(!function_exists('etheme_login_form_modal')) {
	function etheme_login_form_modal() {
		global $woocommerce;
		?>
			<div id="loginModal" class="modal hide fade" tabindex="-1" role="dialog" aria-hidden="true">
				<div>
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
						<h3 class="title"><span><?php _e('Login', WFT_DOMAIN); ?></span></h3>
					</div>
					<div class="modal-body">
						<?php do_action('etheme_before_login'); ?>
						<form method="post" class="login">
							<p class="form-row form-row-<?php if (get_option('woocommerce_enable_myaccount_registration')=='yes') : ?>wide<?php else: ?>first<?php endif; ?>">
								<label for="username"><?php _e( 'Username or email', WFT_DOMAIN ); ?> <span class="required">*</span></label>
								<input type="text" class="input-text" name="username" id="username" />
							</p>
							<p class="form-row form-row-<?php if (get_option('woocommerce_enable_myaccount_registration')=='yes') : ?>wide<?php else: ?>last<?php endif; ?>">
								<label for="password"><?php _e( 'Password', WFT_DOMAIN ); ?> <span class="required">*</span></label>
								<input class="input-text" type="password" name="password" id="password" />
							</p>
							<div class="clear"></div>

							<p class="form-row">
								<?php $woocommerce->nonce_field('login', 'login') ?>
								<input type="submit" class="button filled active" name="login" value="<?php _e( 'Login', WFT_DOMAIN ); ?>" />
								<a class="lost_password" href="<?php

								$lost_password_page_id = woocommerce_get_page_id( 'lost_password' );

								if ( $lost_password_page_id )
									echo esc_url( get_permalink( $lost_password_page_id ) );
								else
									echo esc_url( wp_lostpassword_url( home_url() ) );

								?>"><?php _e( 'Lost Password?', WFT_DOMAIN ); ?></a>
								<a href="<?php echo get_permalink( get_option('woocommerce_myaccount_page_id') ); ?>" class="right"><?php _e('Create Account', WFT_DOMAIN) ?></a>
							</p>
						</form>
					</div>
				</div>
			</div>
		<?php
	}
}

// **********************************************************************// 
// ! Shopping cart modal
// **********************************************************************//   

add_action('after_page_wrapper', 'etheme_cart_modal');
if(!function_exists('etheme_cart_modal')) {
	function etheme_cart_modal( $product_id = '' ) {
		global $woocommerce, $product,$post;
	
		echo '<div id="cartModal" class="modal hide fade" tabindex="-1" role="dialog" aria-hidden="true"><div id="shopping-cart-modal">';
		
		?>
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
				<h3 class="title"><span><?php _e('Cart', WFT_DOMAIN); ?></span></h3>
			</div>
		<?php
		
		echo '<div class="modal-body">';
		?>
			<div class="shopping-cart-modal a-right" >
			    <div class="cart-popup-container">
				    <div class="cart-popup">
				        <?php
				        	etheme_cart_items(150);
				        ?>
				    </div>
			    </div> 
			</div>

	    <?php
			
		echo '</div>';
		
	
		echo '</div></div>';
	}
}  
// **********************************************************************// 
// ! Top Cart Widget
// **********************************************************************// 

if(!function_exists('etheme_top_cart')) {
	function etheme_top_cart() {
        global $woocommerce;
		?>

			<div class="shopping-cart-widget a-right" <?php if(etheme_get_option('favicon_badge')) echo 'data-fav-badge="enable"' ?>>
				<div class="cart-summ" data-items-count="<?php echo $woocommerce->cart->cart_contents_count; ?>">
					<a href="<?php echo $woocommerce->cart->get_cart_url(); ?>"><?php _e('Cart', WFT_DOMAIN) ?> <span class="items"><?php echo $woocommerce->cart->cart_contents_count; ?> <?php _e('items', WFT_DOMAIN);?></span> <span class="for-label"><?php _e('for', WFT_DOMAIN) ?></span> <span class="price-summ"><?php echo $woocommerce->cart->get_cart_subtotal(); ?></span></a>
				</div>
			    <div class="cart-popup-container">
				    <div class="cart-popup">
				        <?php
				        	etheme_cart_items(3);
				        ?>
				    </div>
			    </div> 
			</div>

    <?php
	}
}

if(!function_exists('etheme_cart_items')) {
	function etheme_cart_items ($limit = 3) {
        global $woocommerce;
        if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
          ?>
            <div class="products-small">
          <?php
            $counter = 0;
            foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {
                $counter++;
                if($counter > $limit) continue;
                $_product = $cart_item['data'];

                if ( ! apply_filters('woocommerce_widget_cart_item_visible', true, $cart_item, $cart_item_key ) ) 
                    continue;
                
                if ( $_product->exists() && $cart_item['quantity'] > 0 ) {
            
                    $product_price = get_option( 'woocommerce_display_cart_prices_excluding_tax' ) == 'yes' || $woocommerce->customer->is_vat_exempt() ? $_product->get_price_excluding_tax() : $_product->get_price();
                            
                    $product_price = apply_filters( 'woocommerce_cart_item_price_html', woocommerce_price( $product_price ), $cart_item, $cart_item_key );  
                                
                ?>
                    <div class="product-item">       
                        <a href="<?php echo get_permalink( $cart_item['product_id'] ); ?>" class="product-image">
                            <img src="<?php echo etheme_get_image(get_post_thumbnail_id($cart_item['product_id']), 100, 200, false); ?>">
                        </a>
                        <?php 
                            echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf('<a href="%s" class="delete-btn" title="%s"><i class="icon-remove"></i></a>', esc_url( $woocommerce->cart->get_remove_url( $cart_item_key ) ), __('Remove this item', WFT_DOMAIN) ), $cart_item_key );
                        ?>
                        <h5><a href="<?php echo get_permalink( $cart_item['product_id'] ); ?>"><?php echo apply_filters('woocommerce_widget_cart_product_title', $_product->get_title(), $_product ) ?></a></h5>
                        
                        <div class="qty">
                            <span class="price"><span class="pricedisplay"><?php echo $product_price; ?></span></span>
                            <span class="quanity-label"><?php echo __('Qty', WFT_DOMAIN); ?>:</span> <span><?php echo $cart_item['quantity']; ?></span>
                        	<?php echo $woocommerce->cart->get_item_data( $cart_item ); ?>
                        </div>
                        
                        <div class="clear"></div>
                    </div> 
                <?php
                }
            }
        ?>
        </div>

        <?php   
        } else {
            echo '<p class="empty a-center">' . __('No products in the cart.', WFT_DOMAIN) . '</p>';
        }
        

        if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
          ?>
            <div class="totals">
            	<span class="items left"><?php echo $woocommerce->cart->cart_contents_count; ?> <?php _e('items', WFT_DOMAIN);?></span>
                <?php echo __('Total:', WFT_DOMAIN); ?> &nbsp;<span class="price"><span class="pricedisplay"><?php echo $woocommerce->cart->get_cart_subtotal(); ?></span></span>
            </div>
          <?php

            do_action( 'woocommerce_widget_shopping_cart_before_buttons' );
            ?>
                
                <a href="<?php echo $woocommerce->cart->get_cart_url(); ?>" class="button left"><span><?php echo __('View Cart', WFT_DOMAIN); ?></span></a>
                <a href="<?php echo $woocommerce->cart->get_checkout_url(); ?>" class="button filled active right "><span><?php echo __('Checkout', WFT_DOMAIN); ?></span></a>

                <div class="clear"></div>
            
            <?php

        }
	}
}


// **********************************************************************// 
// ! New AJAX add to cart action
// **********************************************************************// 
add_action('wp_ajax_wft_woocommerce_add_to_cart', 'wft_woocommerce_add_to_cart');
add_action('wp_ajax_nopriv_wft_woocommerce_add_to_cart', 'wft_woocommerce_add_to_cart');

if(!function_exists('wft_woocommerce_add_to_cart')) {
	function wft_woocommerce_add_to_cart() {

		global $woocommerce;

		$product_id        = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_POST['product_id'] ) );
		$quantity          = empty( $_POST['quantity'] ) ? 1 : apply_filters( 'woocommerce_stock_amount', $_POST['quantity'] );
		$passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity );

		if ( $passed_validation && $woocommerce->cart->add_to_cart( $product_id, $quantity ) ) {

			do_action( 'woocommerce_ajax_added_to_cart', $product_id );

			if ( get_option( 'woocommerce_cart_redirect_after_add' ) == 'yes' ) {
				woocommerce_add_to_cart_message( $product_id );
				$woocommerce->set_messages();
			}

			// Return fragments
			wft_woocommerce_get_refreshed_fragments();


		} else {

			header( 'Content-Type: application/json; charset=utf-8' );

			// If there was an error adding to the cart, redirect to the product page to show any errors
			$data = array(
				'error' => true,
				'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id )
			);

			$woocommerce->set_messages();

			echo json_encode( $data );
		}

		die();
	}	
}

if ( !function_exists('wft_woocommerce_get_refreshed_fragments') ) {
	/**
	 * woocommerce_get_refreshed_fragments function.
	 *
	 * @access public
	 * @return void
	 */
	function wft_woocommerce_get_refreshed_fragments() {

		header( 'Content-Type: application/json; charset=utf-8' );

		// Get mini cart
		ob_start();
		woocommerce_mini_cart();
		$mini_cart = ob_get_clean();

		// Fragments and mini cart are returned
		$woo_cart = WC()->cart->get_cart();
		$data = array(
			'fragments' => apply_filters( 'add_to_cart_fragments', array(
					'div.widget_shopping_cart_content' => '<div class="shopping_cart_mini hidden-phone hidden-tablet widget_shopping_cart_content" style="display: none;">' . $mini_cart . '</div>'
				)
			),
			'cart_hash' => $woo_cart ? md5( json_encode( $woo_cart ) ) : '',
			'cart_count' => $woo_cart ? count($woo_cart) : 0,
		);

		echo json_encode( $data );

		die();
	}
}

function wft_filter_add_to_cart_fragments($arr) {

	if ( isset($arr['div.widget_shopping_cart_content']) ) {
		$arr['div.widget_shopping_cart_content'] = str_replace('widget_shopping_cart_content', 'shopping_cart_mini hidden-phone hidden-tablet widget_shopping_cart_content', $arr['div.widget_shopping_cart_content']);
	}

	return $arr;
}
add_filter('add_to_cart_fragments', 'wft_filter_add_to_cart_fragments', 10);

if ( !function_exists('wft_woocommerce_get_products_listing') ) {

	function wft_woocommerce_get_products_listing() {

		global $woocommerce, $product_slide_size, $wp_query;

		$product_slide_size = 3;

		$order = $_GET['order'] ? $_GET['order'] : 'ASC';

		$meta_query = array();
		$meta_query[] = $woocommerce->query->visibility_meta_query();
		$meta_query[] = $woocommerce->query->stock_status_meta_query();
		$meta_query   = array_filter( $meta_query );

		$args = array(
			'post_type' => 'product',
			'posts_per_page' => etheme_get_option('products_per_page'),
			'product_cat' => ( $_GET['product_cat'] ? woocommerce_clean($_GET['product_cat']) : '' ),
			'orderby' => ( $_GET['orderby'] ? woocommerce_clean($_GET['orderby']) : 'menu_order' ),
			'paged' => ( $_GET['paged'] ? (int) $_GET['paged'] : 1 ),
			'meta_query' => $meta_query,
			'post__in' => WC()->query->price_filter(array())
		);

		if ( isset($_GET['product_cat']) ) {
			$args['product_cat'] = woocommerce_clean($_GET['product_cat']);
		}

		if ( isset($_GET['product_tag']) ) {
			$args['product_tag'] = woocommerce_clean($_GET['product_tag']);
		}

		if ( isset($_GET['brand']) ) {
			$args['brand'] = woocommerce_clean($_GET['brand']);
		}

		if ( $_GET['s'] ) {
			$args['s'] = woocommerce_clean($_GET['s']);
		}

		if ( $_GET['min_price'] ) {
			$args['min_price'] = (int) $_GET['min_price'];
		}

		if ( $_GET['max_price'] ) {
			$args['max_price'] = (int) $_GET['max_price'];
		}

		switch ($args['orderby']) {
			case 'menu_order' :
				$args['orderby']  = 'menu_order title';
				$args['order']    = $order == 'DESC' ? 'DESC' : 'ASC';
				break;
			case 'date' :
				$args['orderby']  = 'date';
				$args['order']    = $order == 'ASC' ? 'ASC' : 'DESC';
				break;
			case 'price' :
				$args['orderby']  = 'meta_value_num';
				$args['order']    = $order == 'DESC' ? 'DESC' : 'ASC';
				$args['meta_key'] = '_price';
				break;
			case 'price_desc' :
				$args['orderby']  = 'meta_value_num';
				$args['order']    = 'DESC';
				$args['meta_key'] = '_price';
				break;
			case 'popularity' :
				$args['meta_key'] = 'total_sales';

				// Sorting handled later though a hook
				add_filter( 'posts_clauses', array( $woocommerce->query, 'order_by_popularity_post_clauses' ) );
				break;
			case 'rating' :
				// Sorting handled later though a hook
				add_filter( 'posts_clauses', array( $woocommerce->query, 'order_by_rating_post_clauses' ) );
				break;
			case 'title' :
				$args['orderby']  = 'title';
				$args['order']    = $order == 'DESC' ? 'DESC' : 'ASC';
				break;
		}
		//$posts = get_posts($args);
		$wp_query = new WP_Query($args);


		ob_start();


		while ( $wp_query->have_posts() ) {

			$wp_query->the_post();

			woocommerce_get_template_part( 'content', 'product' );

		}

		$data['products'] = ob_get_clean();

		ob_start();
		woocommerce_pagination();
		$data['pagination'] = ob_get_clean();

		ob_start();
		woocommerce_result_count();
		$data['result_count'] = ob_get_clean();

		//wp_reset_postdata();

		echo json_encode($data);
		die();

	}

}
add_action( 'wp_ajax_woocommerce_get_products_listing', 'wft_woocommerce_get_products_listing' );
add_action( 'wp_ajax_nopriv_woocommerce_get_products_listing', 'wft_woocommerce_get_products_listing' );

if ( !function_exists('wft_listing_header_row1') ) {
	function wft_listing_header_row1() {
		?>

		<div class="listing_header_row1">
			<div class="pull-left">
				<?php woocommerce_catalog_ordering(); ?>
			</div>

		</div>
	<?php
	}
}

if ( !function_exists('wft_div_line1') ) {
	function wft_div_line1() {
		echo '<div class="line1"></div>';
	}
}

if ( !function_exists('wft_listing_header_row2') ) {
	function wft_listing_header_row2() {

		if ( get_option( 'woocommerce_shop_page_display' ) != 'subcategories' ) {
			?>
			<div class="listing_header_row2">
				<div class="pull-left">
					<?php woocommerce_result_count(); ?>
				</div>
				<div class="pull-right wft_pagination">
					<?php woocommerce_pagination(); ?>
				</div>
			</div>
			<div class="clearfix"></div>
			<?php
		}

	}
}

add_action( 'wp_ajax_woocommerce_get_product_quick', 'wft_woocommerce_get_product_quick' );
add_action( 'wp_ajax_nopriv_woocommerce_get_product_quick', 'wft_woocommerce_get_product_quick' );

if ( !function_exists('wft_woocommerce_get_product_quick') ) {
	function wft_woocommerce_get_product_quick() {

		$q = '';
		query_posts($q);
		woocommerce_get_template_part( 'content', 'single-product' );

		exit;

	}
}


add_action( 'wp_ajax_woocommerce_cart_remove', 'wft_woocommerce_cart_remove' );
add_action( 'wp_ajax_nopriv_woocommerce_cart_remove', 'wft_woocommerce_cart_remove' );

if ( !function_exists('wft_woocommerce_cart_remove') ) {
	/**
	 * Remove from cart/update.
	 *
	 * @access public
	 * @return void
	 */
	function wft_woocommerce_cart_remove() {

		$data = array();

		// Remove from cart
		if ( isset($_GET['ajax_remove_item']) && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( $_GET['_wpnonce'], 'woocommerce-cart' ) ) {
			WC()->cart->set_quantity( $_GET['ajax_remove_item'], 0 );
			$data['result'] = true;
			$data['item_count'] = count(WC()->cart->get_cart());
			$data['message'] = __( 'Cart updated.', 'woocommerce' );
		} else {
			$data['result'] = false;
			$data['message'] = __( 'Nothing to remove.', 'woocommerce' );
		}

		echo json_encode($data);
		exit;
	}
}

if ( !function_exists('get_ajax_remove_url') ) {
	/**
	 * Gets the url to remove an item from the cart.
	 *
	 * @return string url to page
	 */
	function get_ajax_remove_url( $cart_item_key ) {

		global $woocommerce;

		$cart_page_id = woocommerce_get_page_id('cart');

		if ( $cart_page_id ) {
			$url = get_permalink($cart_page_id);
			return apply_filters( 'woocommerce_get_remove_url', $woocommerce->nonce_url('cart', add_query_arg(array('remove_item'=>$cart_item_key, 'action' => 'woocommerce_cart_remove'), $url) ) );
		}
	}
}

/**
 * WFT_Product_Cat_List_Walker class.
 *
 * @extends 	Walker
 * @class 		WFT_Product_Cat_List_Walker
 * @version		1.0.0
 * @package		WooCommerce/Classes/Walkers
 * @author 		Web Flash Templates
 */

class WFT_Product_Cat_List_Walker extends Walker {

	var $tree_type = 'product_cat';
	var $db_fields = array ( 'parent' => 'parent', 'id' => 'term_id', 'slug' => 'slug' );

	/**
	 * @see Walker::start_lvl()
	 * @since 2.1.0
	 *
	 * @param string $output Passed by reference. Used to append additional content.
	 * @param int $depth Depth of category. Used for tab indentation.
	 * @param array $args Will only append content if style argument value is 'list'.
	 */
	function start_lvl( &$output, $depth = 0, $args = array() ) {
		if ( 'list' != $args['style'] )
			return;

		$level = $depth + 1;

		$indent = str_repeat("\t", $depth);

		$output .= "$indent". '<ul class="level'.$level.' children" style="display: none;">'."\n";
	}

	/**
	 * @see Walker::end_lvl()
	 * @since 2.1.0
	 *
	 * @param string $output Passed by reference. Used to append additional content.
	 * @param int $depth Depth of category. Used for tab indentation.
	 * @param array $args Will only append content if style argument value is 'list'.
	 */
	function end_lvl( &$output, $depth = 0, $args = array() ) {
		if ( 'list' != $args['style'] )
			return;

		$indent = str_repeat("\t", $depth);

		$output .= "$indent</ul>\n";
	}

	/**
	 * @see Walker::start_el()
	 * @since 2.1.0
	 *
	 * @param string $output Passed by reference. Used to append additional content.
	 * @param object $object Category data object.
	 * @param int $depth Depth of category in reference to parents.
	 * @param array $args
	 * @param int $current_object_id
	 */
	function start_el( &$output, $object, $depth = 0, $args = array(), $current_object_id = 0 ) {

		$level = $depth + 1;

		$output .= '<li class="level'. $level .' cat-item cat-item-' . $object->term_id;

		if ( $args['current_category'] == $object->term_id )
			$output .= ' current-cat';

		if ( $args['current_category_ancestors'] && $args['current_category'] && in_array( $object->term_id, $args['current_category_ancestors'] ) )
			$output .= ' current-cat-parent';

		$output .=  '"><a href="' . get_term_link( (int) $object->term_id, 'product_cat' ) . '">' . __( $object->name, 'woocommerce' ) . '</a>';

		if ( $args['show_count'] )
			$output .= ' <span class="count">(' . $object->count . ')</span>';

		if ( $args['has_children'] ) {
			$output .= '<span class="collapse_button">+</span>';
		}

	}

	/**
	 * @see Walker::end_el()
	 * @since 2.1.0
	 *
	 * @param string $output Passed by reference. Used to append additional content.
	 * @param object $object Not used.
	 * @param int $depth Depth of category. Not used.
	 * @param array $args Only uses 'list' for whether should append to output.
	 */
	function end_el( &$output, $object, $depth = 0, $args = array() ) {

		$output .= "</li>\n";

	}

	/**
	 * Traverse elements to create list from elements.
	 *
	 * Display one element if the element doesn't have any children otherwise,
	 * display the element and its children. Will only traverse up to the max
	 * depth and no ignore elements under that depth. It is possible to set the
	 * max depth to include all depths, see walk() method.
	 *
	 * This method shouldn't be called directly, use the walk() method instead.
	 *
	 * @since 2.5.0
	 *
	 * @param object $element Data object
	 * @param array $children_elements List of elements to continue traversing.
	 * @param int $max_depth Max depth to traverse.
	 * @param int $depth Depth of current element.
	 * @param array $args
	 * @param string $output Passed by reference. Used to append additional content.
	 * @return null Null on failure with no changes to parameters.
	 */
	function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) {

		if ( !$element )
			return;

		if ( ! $args[0]['show_children_only'] || ( $args[0]['show_children_only'] && ( $element->parent == 0 || $args[0]['current_category'] == $element->parent || in_array( $element->parent, $args[0]['current_category_ancestors'] ) ) ) ) {

			$id_field = $this->db_fields['id'];

			//display this element
			if ( is_array( $args[0] ) )
				$args[0]['has_children'] = ! empty( $children_elements[$element->$id_field] );
			$cb_args = array_merge( array(&$output, $element, $depth), $args);
			call_user_func_array(array(&$this, 'start_el'), $cb_args);

			$id = $element->$id_field;

			// descend only when the depth is right and there are children for this element
			if ( ($max_depth == 0 || $max_depth > $depth+1 ) && isset( $children_elements[$id]) ) {

				foreach( $children_elements[ $id ] as $child ){

					if ( !isset($newlevel) ) {
						$newlevel = true;
						//start the child delimiter
						$cb_args = array_merge( array(&$output, $depth), $args);
						call_user_func_array(array(&$this, 'start_lvl'), $cb_args);
					}
					$this->display_element( $child, $children_elements, $max_depth, $depth + 1, $args, $output );
				}
				unset( $children_elements[ $id ] );
			}

			if ( isset($newlevel) && $newlevel ){
				//end the child delimiter
				$cb_args = array_merge( array(&$output, $depth), $args);
				call_user_func_array(array(&$this, 'end_lvl'), $cb_args);
			}

			//end this element
			$cb_args = array_merge( array(&$output, $element, $depth), $args);
			call_user_func_array(array(&$this, 'end_el'), $cb_args);

		}
	}

}

/**
 * WFT_Product_Brands_List_Walker class.
 *
 * @extends 	Walker
 * @class 		WFT_Product_Brands_List_Walker
 * @version		1.0.0
 * @package		WooCommerce/Classes/Walkers
 * @author 		Web Flash Templates
 */

class WFT_Product_Brands_List_Walker extends Walker {

	var $tree_type = 'brand';
	var $db_fields = array ( 'parent' => 'parent', 'id' => 'term_id', 'slug' => 'slug' );

	/**
	 * @see Walker::start_lvl()
	 * @since 2.1.0
	 *
	 * @param string $output Passed by reference. Used to append additional content.
	 * @param int $depth Depth of brand. Used for tab indentation.
	 * @param array $args Will only append content if style argument value is 'list'.
	 */
	function start_lvl( &$output, $depth = 0, $args = array() ) {
		if ( 'list' != $args['style'] )
			return;

		$level = $depth + 1;

		$indent = str_repeat("\t", $depth);

		$output .= "$indent". '<ul class="level'.$level.' children">'."\n";
	}

	/**
	 * @see Walker::end_lvl()
	 * @since 2.1.0
	 *
	 * @param string $output Passed by reference. Used to append additional content.
	 * @param int $depth Depth of brand. Used for tab indentation.
	 * @param array $args Will only append content if style argument value is 'list'.
	 */
	function end_lvl( &$output, $depth = 0, $args = array() ) {
		if ( 'list' != $args['style'] )
			return;

		$indent = str_repeat("\t", $depth);

		$output .= "$indent</ul>\n";
	}

	/**
	 * @see Walker::start_el()
	 * @since 2.1.0
	 *
	 * @param string $output Passed by reference. Used to append additional content.
	 * @param object $object Brand data object.
	 * @param int $depth Depth of brand in reference to parents.
	 * @param array $args
	 * @param int $current_object_id
	 */
	function start_el( &$output, $object, $depth = 0, $args = array(), $current_object_id = 0 ) {

		$level = $depth + 1;

		$output .= '<li class="level'. $level .' brand-item brand-item-' . $object->term_id;

		if ( $args['current_brand'] == $object->term_id )
			$output .= ' current-brand';

		if ( $args['current_brand_ancestors'] && $args['current_brand'] && in_array( $object->term_id, $args['current_brand_ancestors'] ) )
			$output .= ' current-brand-parent';

		$output .=  '"><a href="' . get_term_link( (int) $object->term_id, 'brand' ) . '">' . __( $object->name, 'woocommerce' ) . '</a>';

		if ( $args['show_count'] )
			$output .= ' <span class="count">(' . $object->count . ')</span>';

	}

	/**
	 * @see Walker::end_el()
	 * @since 2.1.0
	 *
	 * @param string $output Passed by reference. Used to append additional content.
	 * @param object $object Not used.
	 * @param int $depth Depth of category. Not used.
	 * @param array $args Only uses 'list' for whether should append to output.
	 */
	function end_el( &$output, $object, $depth = 0, $args = array() ) {

		$output .= "</li>\n";

	}

	/**
	 * Traverse elements to create list from elements.
	 *
	 * Display one element if the element doesn't have any children otherwise,
	 * display the element and its children. Will only traverse up to the max
	 * depth and no ignore elements under that depth. It is possible to set the
	 * max depth to include all depths, see walk() method.
	 *
	 * This method shouldn't be called directly, use the walk() method instead.
	 *
	 * @since 2.5.0
	 *
	 * @param object $element Data object
	 * @param array $children_elements List of elements to continue traversing.
	 * @param int $max_depth Max depth to traverse.
	 * @param int $depth Depth of current element.
	 * @param array $args
	 * @param string $output Passed by reference. Used to append additional content.
	 * @return null Null on failure with no changes to parameters.
	 */
	function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) {

		if ( !$element )
			return;

		if ( ! $args[0]['show_children_only'] || ( $args[0]['show_children_only'] && ( $element->parent == 0 || $args[0]['current_brand'] == $element->parent || in_array( $element->parent, $args[0]['current_brand_ancestors'] ) ) ) ) {

			$id_field = $this->db_fields['id'];

			//display this element
			if ( is_array( $args[0] ) )
				$args[0]['has_children'] = ! empty( $children_elements[$element->$id_field] );
			$cb_args = array_merge( array(&$output, $element, $depth), $args);
			call_user_func_array(array(&$this, 'start_el'), $cb_args);

			$id = $element->$id_field;

			// descend only when the depth is right and there are children for this element
			if ( ($max_depth == 0 || $max_depth > $depth+1 ) && isset( $children_elements[$id]) ) {

				foreach( $children_elements[ $id ] as $child ){

					if ( !isset($newlevel) ) {
						$newlevel = true;
						//start the child delimiter
						$cb_args = array_merge( array(&$output, $depth), $args);
						call_user_func_array(array(&$this, 'start_lvl'), $cb_args);
					}
					$this->display_element( $child, $children_elements, $max_depth, $depth + 1, $args, $output );
				}
				unset( $children_elements[ $id ] );
			}

			if ( isset($newlevel) && $newlevel ){
				//end the child delimiter
				$cb_args = array_merge( array(&$output, $depth), $args);
				call_user_func_array(array(&$this, 'end_lvl'), $cb_args);
			}

			//end this element
			$cb_args = array_merge( array(&$output, $element, $depth), $args);
			call_user_func_array(array(&$this, 'end_el'), $cb_args);

		}
	}

}

if ( !function_exists('get_product_brands') ) {
	function get_product_brands($args = '') {

		$defaults = array( 'taxonomy' => 'brand' );
		$args = wp_parse_args( $args, $defaults );

		$taxonomy = $args['taxonomy'];
		/**
		 * Filter the taxonomy used to retrieve terms when calling get_categories().
		 *
		 * @since 2.7.0
		 *
		 * @param string $taxonomy Taxonomy to retrieve terms from.
		 * @param array  $args     An array of arguments. @see get_terms()
		 */
		$taxonomy = apply_filters( 'get_brands_taxonomy', $taxonomy, $args );

		// Back compat
		if ( isset($args['type']) && 'link' == $args['type'] ) {
			_deprecated_argument( __FUNCTION__, '3.0', '' );
			$taxonomy = $args['taxonomy'] = 'link_brand';
		}

		$brands = (array) get_terms( $taxonomy, $args );

		foreach ( array_keys( $brands ) as $k )
			_make_cat_compat( $brands[$k] );

		return $brands;

	}
}

if ( !function_exists('wft_list_brands') ) {
	/**
	 * Display or retrieve the HTML list of brands.
	 *
	 * The list of arguments is below:
	 *     'show_option_all' (string) - Text to display for showing all brands.
	 *     'orderby' (string) default is 'ID' - What column to use for ordering the
	 * brands.
	 *     'order' (string) default is 'ASC' - What direction to order brands.
	 *     'show_count' (bool|int) default is 0 - Whether to show how many posts are
	 * in the brand.
	 *     'hide_empty' (bool|int) default is 1 - Whether to hide brands that
	 * don't have any posts attached to them.
	 *     'use_desc_for_title' (bool|int) default is 1 - Whether to use the
	 * description instead of the brand title.
	 *     'feed' - See {@link get_product_brands()}.
	 *     'feed_type' - See {@link get_product_brands()}.
	 *     'feed_image' - See {@link get_product_brands()}.
	 *     'child_of' (int) default is 0 - See {@link get_product_brands()}.
	 *     'exclude' (string) - See {@link get_product_brands()}.
	 *     'exclude_tree' (string) - See {@link get_product_brands()}.
	 *     'echo' (bool|int) default is 1 - Whether to display or retrieve content.
	 *     'current_category' (int) - See {@link get_product_brands()}.
	 *     'hierarchical' (bool) - See {@link get_product_brands()}.
	 *     'title_li' (string) - See {@link get_product_brands()}.
	 *     'depth' (int) - The max depth.
	 *
	 * @since 2.1.0
	 *
	 * @param string|array $args Optional. Override default arguments.
	 * @return string HTML content only if 'echo' argument is 0.
	 */
	function wft_list_brands($args = '') {
		$defaults = array(
			'show_option_all' => '',
			'show_option_none' => __('No brands', WFT_DOMAIN),
			'orderby' => 'name',
			'order' => 'ASC',
			'style' => 'list',
			'show_count' => 0,
			'hide_empty' => 1,
			'use_desc_for_title' => 1,
			'child_of' => 0,
			'feed' => '',
			'feed_type' => '',
			'feed_image' => '',
			'exclude' => '',
			'exclude_tree' => '',
			'current_brand' => 0,
			'hierarchical' => true,
			'title_li' => __( 'Brands', WFT_DOMAIN ),
			'echo' => 0,
			'depth' => 0,
			'taxonomy' => 'brand',
			'walker' => new WFT_Product_Brands_List_Walker
		);

		$r = wp_parse_args( $args, $defaults );

		if ( !isset( $r['pad_counts'] ) && $r['show_count'] && $r['hierarchical'] )
			$r['pad_counts'] = true;

		if ( true == $r['hierarchical'] ) {
			$r['exclude_tree'] = $r['exclude'];
			$r['exclude'] = '';
		}

		if ( !isset( $r['class'] ) )
			$r['class'] = ( 'category' == $r['taxonomy'] ) ? 'categories' : $r['taxonomy'];

		extract( $r );

		if ( !taxonomy_exists($taxonomy) )
			return false;

		$brands = get_product_brands( $r );

		$output = '';
		if ( $title_li && 'list' == $style )
			$output = '<li class="' . esc_attr( $class ) . '">' . $title_li . '<ul>';

		if ( empty( $brands ) ) {
			if ( ! empty( $show_option_none ) ) {
				if ( 'list' == $style )
					$output .= '<li>' . $show_option_none . '</li>';
				else
					$output .= $show_option_none;
			}
		} else {
			if ( ! empty( $show_option_all ) ) {
				$posts_page = ( 'page' == get_option( 'show_on_front' ) && get_option( 'page_for_posts' ) ) ? get_permalink( get_option( 'page_for_posts' ) ) : home_url( '/' );
				$posts_page = esc_url( $posts_page );
				if ( 'list' == $style )
					$output .= "<li><a href='$posts_page'>$show_option_all</a></li>";
				else
					$output .= "<a href='$posts_page'>$show_option_all</a>";
			}

			if ( empty( $r['current_brand'] ) && ( is_category() || is_tax() || is_tag() ) ) {
				$current_term_object = get_queried_object();
				if ( $current_term_object && $r['taxonomy'] === $current_term_object->taxonomy )
					$r['current_brand'] = get_queried_object_id();
			}

			if ( $hierarchical )
				$depth = $r['depth'];
			else
				$depth = -1; // Flat.

			$output .= walk_category_tree( $brands, $depth, $r );
		}

		if ( $title_li && 'list' == $style )
			$output .= '</ul></li>';

		$output = apply_filters( 'wft_list_brands', $output, $args );

		if ( $echo )
			echo $output;
		else
			return $output;
	}
}

if ( !function_exists('get_shop_by_brand') ) {
	function get_shop_by_brand($args = array()) {

		global $wp_query, $post, $woocommerce;

		extract( $args );

		$count = $count ? '1' : '0';
		$hierarchical = $hierarchical ? true : false;
		$show_children_only = (isset($show_children_only) && $show_children_only) ? '1' : '0';
		$orderby = isset($orderby) ? $orderby : 'order';
		$taxonomy = $taxonomy ? $taxonomy : 'brand';

		$brand_args = array( 'show_count' => $count, 'hierarchical' => $hierarchical, 'taxonomy' => $taxonomy );

		$brand_args['menu_order'] = false;

		if ( $orderby == 'order' ) {

			$brand_args['menu_order'] = 'asc';

		} else {

			$brand_args['orderby'] = 'title';

		}

		$current_brand = false;
		$brand_ancestors = array();

		if ( is_tax($taxonomy) ) {

			$current_brand = $wp_query->queried_object;
			$brand_ancestors = get_ancestors( $current_brand->term_id, $taxonomy );

		} elseif ( is_singular('product') ) {

			$product_brand = wc_get_product_terms( $post->ID, $taxonomy, array( 'orderby' => 'parent' ) );

			if ( $product_brand ) {
				$current_brand   = end( $product_brand );
				$brand_ancestors = get_ancestors( $current_brand->term_id, $taxonomy );
			}

		}

		include_once( $woocommerce->plugin_path() . '/classes/walkers/class-product-cat-list-walker.php' );

		$brand_args['title_li'] 			= '';
		$brand_args['show_children_only']	= $show_children_only;
		$brand_args['pad_counts'] 		= 1;
		$brand_args['show_option_none'] 	= __('No product categories exist.', 'woocommerce' );
		$brand_args['current_brand']	= ( $current_brand ) ? $current_brand->term_id : '';
		$brand_args['current_brand_ancestors']	= $brand_ancestors;
		$brand_args['echo'] = false;

		$html = '<li class="level0 nav-2 level-top first parent">
					<a class="level-top"><span>' . _('Shop by Brand') . '</span></a>
					<ul class="level0">
						<li>
							<ul class="shadow">
								<li class="list_column">
									<ul class="list_in_column">';

		$html .= wft_list_brands( apply_filters( 'woocommerce_product_brands_widget_args', $brand_args ) );

		$html .= '</ul></li></ul></li></ul></li>';

		return $html;
	}
}

if ( !function_exists('get_shop_by_category') ) {
	function get_shop_by_category($args = array()) {

		global $wp_query, $post, $woocommerce;

		extract( $args );

		$count = $count ? '1' : '0';
		$hierarchical = $hierarchical ? true : false;
		$show_children_only = (isset($show_children_only) && $show_children_only) ? '1' : '0';
		$orderby = isset($orderby) ? $orderby : 'order';
		$taxonomy = $taxonomy ? $taxonomy : 'product_cat';

		$cat_args = array( 'show_count' => $count, 'hierarchical' => $hierarchical, 'taxonomy' => $taxonomy );

		$cat_args['menu_order'] = false;

		if ( $orderby == 'order' ) {

			$cat_args['menu_order'] = 'asc';

		} else {

			$cat_args['orderby'] = 'title';

		}

		$current_cat = false;
		$cat_ancestors = array();

		if ( is_tax($taxonomy) ) {

			$current_cat = $wp_query->queried_object;
			$cat_ancestors = get_ancestors( $current_cat->term_id, $taxonomy );

		} elseif ( is_singular('product') ) {

			$product_category = wc_get_product_terms( $post->ID, $taxonomy, array( 'orderby' => 'parent' ) );

			if ( $product_category ) {
				$current_cat   = end( $product_category );
				$cat_ancestors = get_ancestors( $current_cat->term_id, $taxonomy );
			}

		}

		include_once( $woocommerce->plugin_path() . '/classes/walkers/class-product-cat-list-walker.php' );

		$cat_args['walker'] 			= new WFT_Product_Cat_List_Walker;
		$cat_args['title_li'] 			= '';
		$cat_args['show_children_only']	= $show_children_only;
		$cat_args['pad_counts'] 		= 1;
		$cat_args['show_option_none'] 	= __('No product categories exist.', 'woocommerce' );
		$cat_args['current_category']	= ( $current_cat ) ? $current_cat->term_id : '';
		$cat_args['current_category_ancestors']	= $cat_ancestors;
		$cat_args['echo'] = false;

		$html = '<li class="level0 nav-1 level-top first parent">
					<a class="level-top"><span>' . _('Shop by Category') . '</span></a>
					<ul class="level0">
						<li>
							<ul class="shadow">
								<li class="list_column">
									<ul class="list_in_column">';

		$html .= wp_list_categories( apply_filters( 'woocommerce_product_categories_widget_args', $cat_args ) );

		$html .= '</ul></li></ul></li></ul></li>';

		return $html;
	}
}

function wft_filter_woocommerce_product_tag_cloud_widget_args($args) {
	$args['post_type'] = 'product';
	return $args;
}
add_filter('woocommerce_product_tag_cloud_widget_args', 'wft_filter_woocommerce_product_tag_cloud_widget_args', 10);


function wft_product_filter() {

	global $woocommerce_loop, $product_slide_size;

	$product_slide_size = 3;
	$type = ( isset($_GET['type']) ? woocommerce_clean($_GET['type']) : 'new_product' );
	$per_page = ( isset($_GET['per_page']) ? (int) $_GET['per_page'] : 12 );

	ob_start();

	//$products = new WP_Query( $args );
	switch ($type) {
		case '*':
			$products = get_recent_products($per_page);
			break;
		case '.featured':
			$products = get_featured_products($per_page);
			break;
		case '.sale':
			$products = get_sale_products($per_page);
			break;
		case '.new_product':
			$products = get_recent_products($per_page);
			break;
		default:
			$products = get_recent_products($per_page);
			break;
	}

	if ( $products && $products->have_posts() ) {

		while ( $products->have_posts() ) {

			$products->the_post();

			woocommerce_get_template_part( 'content', 'product' );

		} // end of the loop.

	}

	wp_reset_postdata();

	$data = ob_get_clean();

	echo json_encode($data);
	die();
}
add_action( 'wp_ajax_woocommerce_get_products_filtered', 'wft_product_filter' );
add_action( 'wp_ajax_nopriv_woocommerce_get_products_filtered', 'wft_product_filter' );