$(document).ready(function(){
	
	// Helper stuff
	$.extend($.expr[':'], {
	  'containsi': function(elem, i, match, array)
	  {
		return (elem.textContent || elem.innerText || '').toLowerCase()
		.indexOf((match[3] || "").toLowerCase()) >= 0;
	  }
	});	
	function sortNumber(a,b) // Sorting numerical ascending
	{
	return a - b;
	}
	
	
	function determineDivState()
	{
		 // Remove a link list div if there's 0 products in it		
		 $("div.link_list_wrapper").each(function(){
			var hD = 0;
			var vD = 0;
			var hideThisDiv = false;      
			$(this).find(".gridBlock").each(function(){
				if ($(this).css("display") != "none") {                                        
					vD++;                                           
				} else { hD++ }                                                                              
			});
			if (vD == 0) { hideThisDiv = true; }
			// Only remove a wrapper when there's more then one on the page
			if ($("div.link_list_wrapper").size() > 1)
			{
				if (hideThisDiv){ 
					$(this).hide(300);
				} else {
					if ($(this).css("display") == "none" && vD > 0){
						$(this).show(300);                     
					}
				}
			}
			// set correct number of products in header of div
			var subcategory = $(this).find("h1.subgroup_title").attr("title");
			if (vD > 1)
			{
				$(this).find("h1.subgroup_title").html(subcategory + " ("+vD+" customizable products)");
			} else {
				$(this).find("h1.subgroup_title").html(subcategory + " ("+vD+" customizable product)");
			}														
		 });
		 checkForScrollBar();
	}
	
	/*** SLIDER SETUP ***/
	
	// First get all the prices on the page to determine min and max values
	var all_prices = new Array();
	$("span.price").each(function(){
		var this_price = $(this).html();
		this_price = this_price.substr(1)
		if (this_price != "Variable")
		{
			all_prices.push(parseInt(this_price));
		}
	});
	all_prices.sort(sortNumber);  
	
	// Set up slider 
	$( "#slider-range" ).slider({
				range: true,
				min: all_prices[0],
				max: all_prices[all_prices.length - 1],
				values: [all_prices[0], all_prices[all_prices.length - 1]],
				
				slide: function( event, ui ) {
					 update_product_counts(ui);                          
				},
				
				stop: function(event, ui) {
					 var min_price = ui.values[0];
					 var max_price = ui.values[1];
					 var productsShown = 0;
					 var hideElems = $();
					 var showElems = $();
					 var box_has_value = false;
					 if($.trim($("input#tags").val()).length)
					 {
						box_has_value = true;
 				 	 	var box_value = $("input#tags").val();
					 }
					 
					 if (!box_has_value)
					 {
						 $("span.price").each(function(){
							var this_price = $(this).html();
							this_price = this_price.substr(1);                                
							var parentDisplayState = $(this).parent().css("display");
							 if (parentDisplayState != "none")
							{
								if (this_price < min_price) {
									hideElems = hideElems.add($(this).parent()); 
								} else if (this_price > max_price) {
									hideElems = hideElems.add($(this).parent());  
								} else {
									productsShown++;
								}
							 } else {
								if (this_price >= min_price && this_price <= max_price) {
									showElems = showElems.add($(this).parent());                                          
									productsShown++;
								}
							}
						  });
					 } else {
						$("a.description:containsi('"+box_value+"')").each(function(){
							var thisPrice = $(this).parent().find("span.price").html();
							thisPrice = thisPrice.substr(1);
							if ($(this).parent().is(":hidden"))
							{ 							
								//alert(thisPrice);
								if (thisPrice >= min_price && thisPrice <= max_price)
								{                          	  
									showElems = showElems.add($(this).parent());                                          
									productsShown++;
								}
							} else { // shown right now
								if (thisPrice < min_price) {
									 //alert("smaller");
									hideElems = hideElems.add($(this).parent()); 
								} else if (thisPrice > max_price) {									
									hideElems = hideElems.add($(this).parent());  
								} else {
									productsShown++;
								}	
							}
						});
				     }
					$( "#amount" ).html( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ]+" ("+productsShown+" products shown)");    

					var i = 0;
					var hideCount = $(hideElems).length;
					$(hideElems).each(function()
					{
						 $(this).delay(i * 10).fadeOut(200, function(){
							if(!--hideCount) determineDivState();                             
						 });
						 i++;
					});                            
					var i = 0;
					var showCount = $(showElems).length;
					$(showElems).each(function()
					{
						
						 $(this).delay(i * 10).fadeIn(200, function(){
							if(!--showCount) determineDivState();                             
						 });
						 i++;                           
					});												
				} // end stop-method of slider					
	}); // end slider setup
	
	function update_product_counts(ui)
	{
		 var productsShown = 0;
		 //alert(typeof(ui));
		 if (typeof(ui) != 'undefined')
		 {
		 	var min_price = ui.values[0];
		 	var max_price = ui.values[1];
		 } else {
			var min_price = $("#slider-range").slider("values", 0);
		 	var max_price = $("#slider-range").slider("values", 1); 
		 }
		 var box_has_value = false;
		 if($.trim($("input#tags").val()).length)
		 {
			box_has_value = true;
			var box_value = $("input#tags").val();
		 }
		 $("span.price").each(function(){
			var this_price = $(this).html();
			if (box_has_value){ var this_description = $(this).parent().find("a.description").html();}
			this_price = this_price.substr(1);
			if (this_price >= min_price && this_price <= max_price)
			{
				if (box_has_value)
				{
					if (this_description.toLowerCase().indexOf(box_value) != -1)
					{
						productsShown++;
					}
				} else {
					productsShown++;
				}
			}
		  });
		if (typeof(ui) != 'undefined')
		{
			$("#amount").html("$"+ui.values[0]+" - $"+ui.values[1]+" ("+productsShown+" products remain)");
		} else {
			$("#amount").html("$"+$("#slider-range").slider("values",0)+" - $"+$("#slider-range").slider("values",1)+"("+productsShown+" products remain)");
		}
	}
	
	var productsShown = $("span.price").size();
	$( "#amount" ).html( "$" + $( "#slider-range" ).slider( "values", 0 ) +
		" - $" + $( "#slider-range" ).slider( "values", 1 ) +" ("+productsShown+" products shown)");
			
	// Search field setup (doesn't take the slider into consideration yet) 
	$("input#tags").keyup(function(){
	    update_product_counts();
		if($.trim($(this).val()).length)
		{
			var box_value = $(this).val();
			
			$("a.description:containsi('"+box_value+"')").each(function(){				
				if ($(this).parent().is(":hidden"))
				{
					var minPrice = $("#slider-range").slider("values", 0);
					var maxPrice = $("#slider-range").slider("values", 1);
					var thisPrice = $(this).parent().find("span.price").html();
					thisPrice = thisPrice.substr(1);
					//alert(thisPrice);
					if (thisPrice >= minPrice && thisPrice <= maxPrice)
					{                          	  
						$(this).parent().show();
					}
			  }	
			});
			$("a.description:not(:containsi('"+box_value+"'))").each(function()
			{   
			   if ($(this).parent().is(":visible"))
			   {
					$(this).parent().hide();
			   }	
			});
			determineDivState();
			
		}
		else {
			 $("a.description").each(function(){
				if ($(this).parent().is(":hidden"))
				{
					var minPrice = $("#slider-range").slider("values", 0);
					var maxPrice = $("#slider-range").slider("values", 1);
					var thisPrice = $(this).parent().find("span.price").html();
					thisPrice = thisPrice.substr(1);
					//alert(thisPrice);
					if (thisPrice >= minPrice && thisPrice <= maxPrice || thisPrice == "Variable")
					{                          	  
						$(this).parent().show();
					}
				}	
			 });
		}
		
		//alert($(this).val());
	});        
   

});
