$(document).ready(function() {
	
	//hide all items not on sale: 
	var hide_non_sale_items = function() {
		//console.log("hide non-sale items");
		var items = $('.product-list li');
		items.not('.sale-item').fadeOut(400, function () {
			if (0 == items.not(':hidden').length) {
				$('ul.product-list').after('<p id="no-items">There are no sale items.</p>');
			}
		});
		
	};
	
	//show all hidden items: 
	var show_all_items = function () {
		//console.log("view all");
		$('.product-list li:hidden').fadeIn();
		$('#no-items').remove();
	};
	
	//get the price of an element in the product list:
	var get_price = function ($elm) {
		var $price = $elm.find('.price'),
			$sale_price = $elm.find('.sale-price'),
			price = $price.html(),
			sale_price = $sale_price.html();
			
		return ($sale_price.length > 0) ? sale_price.substr(1, price.indexOf(' ')) : price.substr(1, price.indexOf(' '));
	};
	
	//sort products on the page by price:
	var sort_by_price = function(order) {
		var $list = $('.product-list'),
			products = $list.children('li').get(); 
		
		products.sort(function (a, b) {
			//this might be a little inefficient:
			var $a = $(a),
				$b = $(b),
				price_a = get_price($a),
				price_b = get_price($b);
				//console.log(order, price_a, price_b, price_a - price_b);	
			return 'asc' == order ? price_a - price_b : price_b - price_a;
		});
		
		$.each(products, function (index, item) { $list.append(item); });
	};
	
	
	//honor any hash (for link sharing):
	var request = document.location.toString();
	if (request.match('#')) { 
		//in case we add stuff other than sale later: 
		var anchor = request.split('#')[1];
		if ('sale' == anchor) {
			$('#sale-filter').attr('href', '#').html('view all');
			hide_non_sale_items();
		} else if ('by-price' == anchor) {
			sort_by_price('asc');
			$('#price-sort').attr('href', '#by-price-desc').html('sort by price (descending)');
		} else if ('by-price-desc' == anchor) {
			sort_by_price('desc');
		}
	}
	
	//sale-filter button
	$('#sale-filter').click(function(){
		if ('#sale' == $(this).attr('href')) {
			hide_non_sale_items();
			//hack to  change URL immediately *after* click, should just make this a callback...
			var btn = $(this);
			setTimeout(function() { btn.attr('href', '#').html('view all');	}, 100);
			
		} else {
			show_all_items();
			var btn = $(this);
			setTimeout(function() { btn.attr('href', '#sale').html('shop sale');	}, 100);	
		}
	});
	
	
	$('#price-sort').click(function () {
		
		var $btn = $(this);
		
		if ('#by-price' == $btn.attr('href')) {
			sort_by_price('asc');
			setTimeout(function() { $btn.attr('href', '#by-price-desc').html('sort by price (descending)'); }, 100);
		} else {
			sort_by_price('desc');
			setTimeout(function() { $btn.attr('href', '#by-price').html('sort by price'); }, 100);
		}
		
		
		
	});
	
});
