$(document).ready(function() {
	function page(position, pager) {
		var sku = $("meta[name=sku]").attr("content");
		$.get($.mapPath('product/pager/' + sku + "/" + position), {}, function(data, textStatus) {
			var list = $("div.search-pager ul");
			var results = $(data).find("li");
			
			if (results.length > 0) {
				list.find("li").remove();
				list.append(results);
			}
			else {
				$(pager).addClass("disabled");
			}
			
			$("div.search-pager ul.product-search li a").click ( function(){
				var position = $(this).attr('rel');
				document.cookie = '_lastSearchPosition=' + position + ';; path=/';
				return true;
				}
			);
		});
	}
	
	
	$("div.product div.section h4").each(function() {
		$(this).append("<a href='#'><!-- click me --></a>");
		$(this).find("a").click(function() {
			$(this).toggleClass("closed");
	
			var section = $(this).parent().parent().find("div.inner");
	
			if (section.hasClass("closed")) {
				section.removeClass("closed");
				section.show();
			}
			else {
				section.addClass("closed");
				section.hide();
			}
	
			return false;
		});
	});
	
	$("div.product a.show").click(function() {
		$(this).toggleClass("shown");
		
		var prefix = "Pattern";
		if ($(this).hasClass("paint")){
			prefix = "Colour";
		}
		
		if ($(this).hasClass("shown")) {
			$(this).find("span").text( prefix +" and info");
			$("div.product div.section").hide();
		}
		else {
			$(this).find("span").text(prefix + " only");
			$("div.product div.section").show();
		}
		return false;
	});
	
	$("div.search-pager a.prev").click(function() {
		var position = parseInt($("ul.product-search li:first a").attr("rel"),10);
	
		if (!$(this).hasClass("disabled") && position > 0) {
			page(position < 6 ? 0 : position - 6, this);				
		}
	
		return false;
	});
	
	$("div.search-pager a.next").click(function() {
		var position = parseInt($("ul.product-search li:last a").attr("rel"),10) - 6;
	
		if (!$(this).hasClass("disabled")) {
			page(position, this);				
		}
	
		return false;
	});
	
	$("div.draggable").draggable({
		start: function() {
			$("h5.flyout").removeClass("open"); 	
			$("div.flyout-container").hide().removeClass("open"); 	
		}
	});

});
