$(function()
{

	var items_being_shown = new Array();
	
	var product_box_tpl = $("div.product_box").clone();
	$("div.product_box").remove();

	// Build a cache of boxes
	var current_count = 1;
	var shown_sliders = false;

	var current_hovered_product = null;
	var expanded_product = null;

	function load_next_box()
	{

		var count = 1;

		for(var id in products)
		{

			if(count == current_count)
			{

				var new_tpl = product_box_tpl.clone();

				// new_tpl.find("span.product_price").html("&pound;" + products[id]['price']); 
				products[id]['box'] = new_tpl;
				new_tpl.find("img").attr("src", products[id]['thumbnail']);
				$("div.product_box_container").append(products[id]['box']);
				products[id]['box'].hide();

				products[id]['box'].hoverIntent({
					interval: 200,
					over: function(){
						var yep = $("div.product_box_hover");
						yep.find("span.product_name").html(products[id]['name']);
						yep.find("img").attr("src", products[id]['thumbnail']);
						yep.fadeIn("fast");
						$(this).prepend(yep);
						current_hovered_product = id;
					},
					timeout: 100,
					out: function()
					{
						$("div.product_box_hover").fadeOut("fast");
						current_hovered_product = null;
					}
				});
				
				current_count++;

				if(current_count <= product_count)
					setTimeout(load_next_box, 10);

				break;

			}

			count++;

		}

		if(current_count == product_count && shown_sliders == false)
		{

			load_sliders();

			$("div.product_box_hover").hide();

			$("div.product_box_hover").click(function(e){
				if(current_hovered_product == null)

					return;

				expanded_product = current_hovered_product;

				var info_box = $("div.expanded_product_info");

				if(products[expanded_product]['product_code_blue'] == null)
					$("a#blue").hide();
				else
					$("a#blue").show().unbind("click").click(function(){
						window.open('http://ergomonkey.easyorder.eu/easyorder.b2c/index?b2c=erg&prdcod='+products[expanded_product]['product_code_blue']);
						return false;
					});

				if(products[expanded_product]['product_code_black'] == null)
					$("a#black").hide();
				else
					$("a#black").show().unbind("click").click(function(){
						window.open('http://ergomonkey.easyorder.eu/easyorder.b2c/index?b2c=erg&prdcod='+products[expanded_product]['product_code_black']);
						return false;
					});

				info_box.fadeIn(function()
				{
					/*
					$(this).bind("mouseleave", function(){
						$(this).fadeOut();
					});
					*/
				});

/*
					 $.ajax({
						type: "GET",
						url: "test.php",
						data : "product_code="+products[expanded_product]['product_code'],
						dataType: "xml",
						success: function(xml)
						{

							 alert($(xml).find('subtotalAmount').html());
							return false;
						}

					});
*/

				$("div.expanded_product_info a.close").click(function(){
					info_box.fadeOut();
					return false;
				});

				info_box.find("h2").html(products[current_hovered_product]['name']);
				info_box.find("img.product_image").attr("src", products[current_hovered_product]['product_image']);
				info_box.find("p.desc span").html(products[current_hovered_product]['desc']);
				info_box.find("ul.product_info li.price span").html(products[current_hovered_product]['price']);
				info_box.find("ul.product_info li.weight span").html(products[current_hovered_product]['weight']);
				info_box.find("ul.product_info li.usage_rate span").html(products[current_hovered_product]['usage']);
				info_box.find("ul.product_info li.user_weight span").html(
					products[current_hovered_product]['user_weight_from'] + "Kg - " +
					products[current_hovered_product]['user_weight_to'] + "Kg"
				);
				info_box.find("ul.product_info li.seat_width span").html(
					products[current_hovered_product]['seat_width_from'] + "mm - " +
					products[current_hovered_product]['seat_width_to'] + "mm"
				);
				info_box.find("ul.product_info li.seat_depth span").html(
					products[current_hovered_product]['seat_depth_from'] + "mm - " +
					products[current_hovered_product]['seat_depth_to'] + "mm"
				);

				// deal with the image, we want it to disappear, load, then come in
				info_box.find("div.product_image_wrap").fadeOut("fast", function(){
	
					// When the image has finished fading out we start loading the new one
					var image = new Image(); 
					image.onload = function(){
	
						// when the new one has finished loading, we fade it in again
						var findme = info_box.find("div.product_image_wrap");
	
						findme.html(image);
						findme.fadeIn("fast");
					
					}
	
					image.src = products[expanded_product]['product_image']; 
				 		
				});

/*
				(products[id]['lumbar_support'] == lumbar_support) &&
				(products[id]['chair_arms'] == chair_arms) &&
				(products[id]['chair_adjust'] == chair_adjust) &&
				(products[id]['neck_rest'] == neck_rest) &&
				(products[id]['metal_base'] == metal_base) &&

				(products[id]['test_standards'] >= test_standards || products[id]['test_standards'] == -1) &&
*/

				// set position to centre of item clicked on
				/*
				var pos = $(this).position();
				$("div.expanded_product_info").css({
					top : (pos.top - ($(this).height()/2)) - 40,
					left : (pos.left - ($(this).width()/2)) - 80,
					zIndex : 200
				});
				*/

				// set position to centre of main box
				var box = $("div.product_box_wrap");
				var pos = box.position();
				$("div.expanded_product_info").css({
					top : (pos.top + (box.height()/4)) - 40,
					left : (pos.left + (box.width()/4)) - 80,
					zIndex : 200
				});

				return false;

			});

		}

	}

	
	var top_price = 1500;
	var from_price = 0; var to_price = top_price;
	var price_enable = true;

	var top_usage = 16;
	var from_usage = 3; var to_usage = top_usage;
	var usage_enable = true;

	var top_weight = 25;
	var from_weight = 5; var to_weight = top_weight;
	var weight_enable = true;

	var top_user_weight = 200;
	var from_user_weight = 40; var to_user_weight = top_weight;
	var user_weight_enable = true;

	var top_seat_width = 600;
	var from_seat_width = 0; var to_seat_width = top_seat_width;
	var seat_width_enable = true;

	var top_seat_depth = 600;
	var from_seat_depth = 0; var to_seat_depth = top_seat_depth;
	var seat_depth_enable = true;

	var test_standards = -1;
	var test_enable = true;

	var lumbar_support = "";
	var lumbar_support_enable = true;

	var chair_arms = "";
	var chair_arms_enable = true;

	var chair_adjust = "";
	var chair_adjust_enable = true;

	var neck_rest = "";
	var neck_rest_enable = true;

	var metal_base = "";
	var metal_base_enable = true;

	function load_sliders()
	{
		shown_sliders = true;

		/**
		 * PRICE
		 */
		$("#price-slider").slider({
			min : 100,
			max : top_price,
			range : true,
			slide : move_price,
			handles: [
				{start: 100, min: 100, max: (top_price-50)},
				{start: top_price, min: 150, max: top_price}
			]
		});


		function move_price(ev, ui)
		{

			from_price = $("#price-slider").slider("value", 0);
			to_price = $("#price-slider").slider("value", 1);

			if(isNaN(from_price))
				from_price = 0;

			$("span.price_display").html("&pound;"+from_price+" - &pound;"+to_price+"");

			reshow_products();

		}

		$("#sidebar div.box div.searchtype span.title a#price_filter").click(function(){

			if(!price_enable)
				$(this).parent().parent().find("span.price_display").
				fadeIn("fast").parent().find("div.option").
				slideDown("fast", function(){ $(this).parent().css("min-height", "40px"); });
			else
				$(this).parent().parent().css("min-height", "0px").find("span.price_display").
				fadeOut("fast").parent().find("div.option").
				slideUp("fast");

			price_enable = !price_enable;

			$("#price-slider").slider("moveTo", 100, 0);
			$("#price-slider").slider("moveTo", top_price, 1);

			return false;

		});


		/**
		 * USAGE RATE
		 */
		$("#usage-slider").slider({
			min : 3,
			max : top_usage,
			range : true,
			slide : move_usage,
			handles: [
				{start: 3, min: 3, max: (top_usage-1)},
				{start: top_usage, min: 4, max: top_usage}
			]
		});

		function move_usage(ev, ui)
		{

			from_usage = $("#usage-slider").slider("value", 0);
			to_usage = $("#usage-slider").slider("value", 1);

			$("span.usage_display").html(from_usage+"hrs - "+to_usage+(to_usage == top_usage ? "+" : "")+"hrs");

			reshow_products();

		}

		$("#sidebar div.box div.searchtype span.title a#usage_filter").click(function(){

			if(!usage_enable)
				$(this).parent().parent().find("span.usage_display").
				fadeIn("fast").parent().find("div.option").
				slideDown("fast", function(){ $(this).parent().css("min-height", "40px"); });
			else
				$(this).parent().parent().css("min-height", "0px").find("span.usage_display").
				fadeOut("fast").parent().find("div.option").
				slideUp("fast");

			usage_enable = !usage_enable;

			$("#usage-slider").slider("moveTo", 3, 0);
			$("#usage-slider").slider("moveTo", top_usage, 1);

			reshow_products();

			return false;

		});


		/**
		 * WEIGHT
		 */
		$("#weight-slider").slider({
			min: 5,
			max: top_weight,
			range : true,
			slide : move_weight,
			handles: [
				{start: 5, min: 5, max: (top_weight-2)},
				{start: top_weight, min: 7, max: top_weight}
			]
		});

		function move_weight(ev, ui)
		{

			from_weight = $("#weight-slider").slider("value", 0);
			to_weight = $("#weight-slider").slider("value", 1);

			$("span.weight_display").html(from_weight+"Kg - "+to_weight+"Kg");

			reshow_products();

		}

		$("#sidebar div.box div.searchtype span.title a#weight_filter").click(function(){

			if(!weight_enable)
				$(this).parent().parent().find("span.weight_display").
				fadeIn("fast").parent().find("div.option").
				slideDown("fast", function(){ $(this).parent().css("min-height", "40px"); });
			else
				$(this).parent().parent().css("min-height", "0px").find("span.weight_display").
				fadeOut("fast").parent().find("div.option").
				slideUp("fast");

			weight_enable = !weight_enable;

			$("#weight-slider").slider("moveTo", 5, 0);
			$("#weight-slider").slider("moveTo", top_weight, 1);

			return false;

		});


		/**
		 * USER WEIGHT
		 */
		$("#user_weight-slider").slider({
			min: 40,
			max: top_user_weight,
			range : true,
			slide : move_user_weight,
			handles: [
				{start: 40, min: 40, max: (top_user_weight-20)},
				{start: top_user_weight, min: 60, max: top_user_weight}
			]
		});

		function move_user_weight(ev, ui)
		{

			from_user_weight = $("#user_weight-slider").slider("value", 0);
			to_user_weight = $("#user_weight-slider").slider("value", 1);

			$("span.user_weight_display").html(from_user_weight+"Kg - "+to_user_weight+"Kg");

			reshow_products();

		}

		$("#sidebar div.box div.searchtype span.title a#user_weight_filter").click(function(){

			if(!user_weight_enable)
				$(this).parent().parent().find("span.user_weight_display").
				fadeIn("fast").parent().find("div.option").
				slideDown("fast", function(){ $(this).parent().css("min-height", "40px"); });
			else
				$(this).parent().parent().css("min-height", "0px").find("span.user_weight_display").
				fadeOut("fast").parent().find("div.option").
				slideUp("fast");

			user_weight_enable = !user_weight_enable;

			$("#user_weight-slider").slider("moveTo", 40, 0);
			$("#user_weight-slider").slider("moveTo", top_user_weight, 1);

			return false;

		});


		/**
		 * SEAT WIDTH
		 */
		$("#seat_width-slider").slider({
			min: 400,
			max: top_seat_width,
			range : true,
			slide : move_seat_width,
			handles: [
				{start: 400, min: 400, max: (top_seat_width-30)},
				{start: top_seat_width, min: 430, max: top_seat_width}
			]
		});

		function move_seat_width(ev, ui)
		{
		
			from_seat_width = $("#seat_width-slider").slider("value", 0);
			to_seat_width = $("#seat_width-slider").slider("value", 1);

			$("span.seat_width_display").html(from_seat_width+"mm - "+to_seat_width+"mm");

			reshow_products();

		}


		$("#sidebar div.box div.searchtype span.title a#seat_width_filter").click(function(){

			if(!seat_width_enable)
				$(this).parent().parent().find("span.seat_width_display").
				fadeIn("fast").parent().find("div.option").
				slideDown("fast", function(){ $(this).parent().css("min-height", "40px"); });
			else
				$(this).parent().parent().css("min-height", "0px").find("span.seat_width_display").
				fadeOut("fast").parent().find("div.option").
				slideUp("fast");

			seat_width_enable = !seat_width_enable;

			$("#seat_width-slider").slider("moveTo", 60, 0);
			$("#seat_width-slider").slider("moveTo", top_seat_width, 1);

			return false;

		});


		/**
		 * SEAT DEPTH
		 */
		$("#seat_depth-slider").slider({
			min: 400,
			max: top_seat_depth,
			range : true,
			slide : move_seat_depth,
			handles: [
				{start: 400, min: 400, max: (top_seat_depth-30)},
				{start: top_seat_depth, min: 430, max: top_seat_depth}
			]
		});

		function move_seat_depth(ev, ui)
		{

			from_seat_depth = $("#seat_depth-slider").slider("value", 0);
			to_seat_depth = $("#seat_depth-slider").slider("value", 1);

			$("span.seat_depth_display").html(from_seat_depth+"mm - "+to_seat_depth+"mm");

			reshow_products();

		}

		$("#sidebar div.box div.searchtype span.title a#seat_depth_filter").click(function(){

			if(!seat_depth_enable)
				$(this).parent().parent().find("span.seat_depth_display").
				fadeIn("fast").parent().find("div.option").
				slideDown("fast", function(){ $(this).parent().css("min-height", "40px"); });
			else
				$(this).parent().parent().css("min-height", "0px").find("span.seat_depth_display").
				fadeOut("fast").parent().find("div.option").
				slideUp("fast");

			seat_depth_enable = !seat_depth_enable;

			$("#seat_depth-slider").slider("moveTo", 60, 0);
			$("#seat_depth-slider").slider("moveTo", top_seat_depth, 1);

			return false;

		});


		/**
		 * STAR RATING
		 */
		$('.standards-star').rating({
//			required : true,
			callback : function(value, link)
			{
				if(!value)
					test_standards = -1;
				else
					test_standards = parseInt(value);

				wait = 2;
				reshow_products();
			}
		});

		$("#sidebar div.box div.searchtype span.title a#standards_filter").click(function(){

			if(!test_enable)
				$(this).parent().parent().find("div.option").slideDown("fast", function(){ $(this).parent().css("min-height", "40px"); });
			else
				$(this).parent().parent().find("div.option").slideUp("fast");

			test_enable = !test_enable;

			return false;

		});



		/**
		 * LUMBAR SUPPORT
		 */
		$('input[name=lumbar_support]').change(function(){
			wait = 2;
			lumbar_support = $(this).val();
			reshow_products();
		});
		lumbar_support = $('input[name=lumbar_support]:checked').val();


		/**
		 * CHAIR ARMS
		 */
		$('input[name=chair_arms]').change(function(){
			wait = 2;
			chair_arms = $(this).val();
			reshow_products();
		});
		chair_arms = $('input[name=chair_arms]:checked').val();


		/**
		 * CHAIR ADJUST
		 */
		$('input[name=chair_adjust]').change(function(){
			wait = 2;
			chair_adjust = $(this).val();
			reshow_products();
		});
		chair_adjust = $('input[name=chair_adjust]:checked').val();


		/**
		 * NECK REST
		 */
		$('input[name=neck_rest]').change(function(){
			wait = 2;
			neck_rest = $(this).val();
			reshow_products();
		});
		neck_rest = $('input[name=neck_rest]:checked').val();


		/**
		 * METAL BASE
		 */
		$('input[name=metal_base]').change(function(){
			wait = 2;
			metal_base = $(this).val();
			reshow_products();
		});
		metal_base = $('input[name=metal_base]:checked').val();


		//$("div.searchtype div.option").hide();
		//$("div.searchtype span.value").hide();

		//$("div.searchtype").addClass("disabled");
		//$("#sidebar div.box div.searchtype").css("min-height", "0");

		$("#search_loader").fadeOut("slow",
			function()
			{

				$("#sidebar").fadeIn("slow");

				$("#price-slider").slider("moveTo", 100, 0);
				$("#price-slider").slider("moveTo", top_price, 1);

				$("#usage-slider").slider("moveTo", 3, 0);
				$("#usage-slider").slider("moveTo", top_usage, 1);

				$("#weight-slider").slider("moveTo", 5, 0);
				$("#weight-slider").slider("moveTo", top_weight, 1);

				$("#user_weight-slider").slider("moveTo", 60, 0);
				$("#user_weight-slider").slider("moveTo", top_user_weight, 1);

				$("#seat_width-slider").slider("moveTo", 450, 0);
				$("#seat_width-slider").slider("moveTo", top_seat_width, 1);

				$("#seat_depth-slider").slider("moveTo", 430, 0);
				$("#seat_depth-slider").slider("moveTo", top_seat_depth, 1);

				all_ready = true;
				reshow_products();

				$("div#content div.product_box_container").show();

			}
		);

	
	}


	/**
	 * Product showing mechianism
	 */
	var wait = 2;
	var all_ready = false;

	function reshow_products()
	{

		if(all_ready == false)
			return;
/*
		if(wait == 2)
		{
			wait = 0;
		}
		else
		{
			wait++;
			return;
		}
*/
		var items_to_del = new Array();
		var items_to_add = new Array();

		// Go through all the products and work out which ones we should be showing at this point
		var id = 0;

		for(id in products)
		{

			var remove = false;


			if((lumbar_support != "-1") && (products[id]['lumbar_support'] != lumbar_support))
			   remove = true;

			if((chair_arms != "-1") && (products[id]['chair_arms'] != chair_arms))
			   remove = true;

			if((chair_adjust != "-1") && (products[id]['chair_adjust'] != chair_adjust))
			   remove = true;

			if((neck_rest != "-1") && (products[id]['neck_rest'] != neck_rest))
			   remove = true;

			if((metal_base != "-1") && (products[id]['metal_base'] != metal_base))
			   remove = true;

			if((test_standards != "-1") && (products[id]['test_standards'] < test_standards))
			   remove = true;

			if(price_enable && (products[id]['price'] < from_price || products[id]['price'] > to_price))
			   remove = true;

			if(weight_enable && (products[id]['weight'] < from_weight || products[id]['weight'] > to_weight))
			   remove = true;

			if(usage_enable && (products[id]['usage'] < from_usage || (to_usage < top_usage && products[id]['usage'] > to_usage)))
				remove = true;

			if(user_weight_enable && (to_user_weight < products[id]['user_weight_from'] || from_user_weight > products[id]['user_weight_to']))
				remove = true;

			if(seat_width_enable && (to_seat_width < products[id]['seat_width_from'] || from_seat_width > products[id]['seat_width_to']))
			   remove = true;

			if(seat_depth_enable && (to_seat_depth < products[id]['seat_depth_from'] || from_seat_depth > products[id]['seat_depth_to']))
			   remove = true;

			if(remove)
				products[id]['box'].addClass("fadeout").removeClass("fadein");
			else
				products[id]['box'].addClass("fadein").removeClass("fadeout");


		}

		$("div.fadein:hidden").fadeIn();
		$("div.fadeout:visible").fadeOut();

	}

	load_next_box();

});


// Seriously now IE. What...?
if(Array.indexOf == undefined)
{
	Array.prototype.indexOf = function(obj, start)
	{
		for(var i=(start||0); i < this.length; i++)
			if(this[i] == obj)
				return i;
		return -1;
	}
}


/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);
