/* 
   ----------------------------------------------------------------
		jQuery Extensions & Patches
   ----------------------------------------------------------------
*/
//fade toggle ectention
jQuery.fn.fadeToggle = function(speed, easing, callback) {
    return this.animate({opacity: 'toggle'}, speed, easing, callback);
};
/* Non-essential behaviours for Dunelm pages */
$(function(){
	
/* PRODUCT DETAILS ENHANCEMENTS ---------------------------------------------------------------- */

   //Fix the bloody alt-image clicks:
   $('#pagebody a.alternativeviewlink')
	   	.click(function(){
	   		if ($(".bundlesLifeStyle img").length) {
	   			var imgToChange = $('.bundlesLifeStyle img');
	   			var bundles = true;
	   		}
	   		else {
	   			var imgToChange = $('#pdlargerimage img');
	   		}
	   		
	   		var newImagePath = $(this).attr('href');
	   		var currentImagePath = imgToChange.attr('src');
	   		
	   		//Swap the alt into the new:
	   		//if pdp change the href for the g=hover function
	   		if (!bundles) {
	   			imgToChange.parent().parent().find("a")
	   			.attr('href', newImagePath.replace(/large/i, 'extralarge'));
	   		}
	   		imgToChange
		   			.fadeTo(100, 0.01, function(){
		   				$(this)
		   					.load(function(){$(this).fadeTo(100, 1);})
		   					.attr('src', newImagePath);		   					
		   			});
	   			
	   		//Swap the old into the alt:
	   		
	   		$(this)
	   			.attr('href', currentImagePath)
	   		.find('img')
	   			.fadeTo(100, 0.01, function(){
	   				$(this)
	   				.load(function(){$(this).fadeTo(100, 1);});
	   				if (currentImagePath.match(/_/)) $(this).attr('src',  currentImagePath.replace(/large/i, 'extrasmall'));
	   				else $(this).attr('src',  currentImagePath.replace(/large/i, 'small'));
	   			});
	   		
	   		return false;
	   			
	   });	   

/*	   
		// moved into styleX.style.polish.js to allow specific loading image
		// hope that hasn't broken it elsewhere! D.L.T.
	   //product images lightbox functions
	   if($("a.tbProd").length) {
   			$("a.tbProd").lightBox({
					overlayBgColor: '#FFFFFF',
					overlayOpacity: 0.5,
					imageLoading: '/wcsstore/ConsumerDirectStorefrontAssetStore/images/Master1_1/icon_lightBox_ticker.gif',
					useNavigation: false
			 });
		}
*/

		//set up rollover on larger image link
	    if($("a.largerAlt").length) {
	    	$("a.largerAlt").each(function(){
	    		var thisEl = $(this);
	    		thisEl.hide();
	    		$(this).parent()
	    		.hover(function(){
	    			thisEl.fadeToggle();
	    			},
	    			function(){
	    			thisEl.fadeToggle();
	    			});
	    		
	    	});	    	
	    }
	    
	   //addtobasket functions
	   	   
	   //append hidden feed back message
	   if ($("#bundlesIntro").length) {
	   	$("#bundlesIntro").after('<div id="bundlesFeedback" class="message"><p>&#160;</p></div>');
	   }
	   
	   //pre bundles set up
	   $("div.bundledProduct").each(function(){
	   
	   		//ie fix
	   		$(this).css("zoom","1");
	   		
	   		//style tweaks (if needed)
	   		/*$(this).find("h2.description a").hover(
	   			function(){
	   				$(this).find("cufon").css("text-decoration","underline");
	   			},
				  function () {
				    $(this).find("cufon").css("text-decoration","none");
				  }
			);*/
	   
	   		//set vars
	   		var oThisSize = $(this).find("div.options select");
	   		var oThisColour = $(this).find("div.options ul.colourChips");
	   		var oThisProdId = $(this).find("input.productIdentifier").val();
	   		
	   		//make sure browser does not retain selected
	   		oThisColour.find("li input").removeAttr("checked");
	   		oThisSize.find("option").removeAttr("selected");
	   		$(this).find("div.actions input").removeAttr("checked");
	   		
	   		//if colour + size then disable dropdown unless preselected
	   		if (oThisSize.length && oThisColour.length && (oThisSize.find("option").length!=1)){
	   			oThisSize.attr("disabled",true);
	   		}
	   		//select 'please select' if there (safari fix)
	   		if (oThisSize.length) {
	   			oThisSize.find("option").each(function(){
	   				if ($(this).val()== "Default") {
	   					$(this).attr("selected",true);	   				
	   				}
	   			});
	   		}
	   		//auto select single colors
	   		if (oThisColour.find("li").length == 1) {
	   			//get color value
	   			var colorValue = jQuery.trim(oThisColour.find("li").find("label").text());	  
	   			//make selected 		
	   			oThisColour.find("li").addClass("selected").find("input")[0].checked = true;
	   			//show selected text	   			
	   			oThisColour.parent().find("span.colDesc").css("display","block").find("span").html(colorValue);
	   			//check for drop down if there price it up
	   			if (oThisSize.length) PriceUpSizes(oThisSize,colorValue,oThisProdId);
	   			else {
	   				//check is stock aware then display as available
	   				if (checkStockMap(oThisProdId+colorValue) || !checkIsAvailable(oThisProdId+colorValue)) {	   					
	   					//single sku not available 	   					
						if ($(this).find("p.oosMessage").length) $(this).find("p.oosMessage").fadeIn("fast");						
						else $(this).find("div.actions").append('<p class="oosMessage">'+outOfStockMessage+'</p>');					
	   					//also disable check box
	   					$(this).find("div.actions input").attr("disabled",true);
	   				}
	   			}
	   		}
	   		else if (!oThisColour.length && oThisSize.find("option").length==1) {
	   			
	   			//if no color and only one drop down attr
	   			//get the one value	   			
	   			var sizeVal = HTMLEncode(oThisSize.find("option")[0].value);	   			
	   			if (checkStockMap(oThisProdId+sizeVal) || !checkIsAvailable(oThisProdId+sizeVal)) { 	   								   									
   					//single sku not available 	   					
					if ($(this).find("p.oosMessage").length) $(this).find("p.oosMessage").fadeIn("fast");						
					else $(this).find("div.actions").append('<p class="oosMessage">'+outOfStockMessage+'</p>');					
   					//also disable check box
	   				$(this).find("div.actions input").attr("disabled",true);
   				}
	   		}
	   });
	   // pre pdp set up
	    $("div#productActions").each(function(){
	    	//set vars
	   		var oThisSize = $(this).find("div.dropdownoptions select");
	   		var oThisColour = $(this).find("div.dropdownoptions ul.colourChips");
	   		
	   		//make sure browser does not retain selected
	   		oThisColour.find("li input").removeAttr("checked");
	   		oThisSize.find("option").removeAttr("selected");
	   		
	   		//if colour + size then disable dropdown
	   		if (oThisSize.length && oThisColour.length){
	   			oThisSize.attr("disabled",true);
	   		}
	   		if (!oThisSize.length && !oThisColour.length){
	   			//if no attributes
	   			//need to check is available first too **todo
	   			enablePDPButtons();
	   		}
	   		else {
	   			//disable wishlist button to start
	   			if ($("p.wishlist").length) $("p.wishlist").find("a")
	   			.addClass("disabled").unbind().click(function(){
	   				//if clicked whilst disabled
	   				checkSelection();
	   				return false;
	   			});
	   			//disable atb button
	   			$("a.buttonAddToBasket").unbind().addClass("disabled").click(function(){
	   				//if clicked whilst disabled	   				   			
		   			checkSelection();
		   			return false;  			
		   		});
   		 	}
   		 	//select 'please select' if there (safari fix)
	   		if (oThisSize.length) {
	   			oThisSize.find("option").each(function(){
	   				if ($(this).val()== "Default") {
	   					$(this).attr("selected",true);
	   				}
	   			});
	   		}
	   		//auto select single colors
	   		if (oThisColour.find("li").length == 1) {
	   			//get color value
	   			var colorValue = jQuery.trim(oThisColour.find("li").find("label").text());	  
	   			//make selected	   				
	   			oThisColour.find("li").addClass("selected").find("input")[0].checked = true;
	   			//show selected text	   			
	   			oThisColour.parent().find("span.colDesc").css("display","block").find("span").html(colorValue);
	   			//enable buttons if dropdown doesnt exist
	   			if (!oThisSize.length) {
	   				//check is stock aware then display as available
	   				if (!checkStockMap(colorValue) && checkIsAvailable(colorValue)) {
	   					enablePDPButtons();
	   				}
	   				else {
	   					//single sku not available 	   					
						if ($(this).find("p.oosMessage").length) $(this).find("p.oosMessage").fadeIn("fast");						
						else $(this).find("ul.actions").after('<p class="oosMessage">'+outOfStockMessage+'</p>');					
	   				}
	   			}
	   			//price up the dropdoan if it is
	   			else PriceUpSizes(oThisSize,colorValue,"");
	   		}
	   		else if (!oThisColour.length && oThisSize.find("option").length==1) {
	   			//if no color and only one drop down attr
	   			//get the one value
	   			var sizeVal = HTMLEncode(oThisSize.find("option")[0].value);
	   			   			
	   			if (!checkStockMap(sizeVal) && checkIsAvailable(sizeVal)) {
   					enablePDPButtons();
   				}
   				else {   						
   					//single sku not available 	   					
					if ($(this).find("p.oosMessage").length) $(this).find("p.oosMessage").fadeIn("fast");						
					else $(this).find("ul.actions").after('<p class="oosMessage">'+outOfStockMessage+'</p>');					
   				}
	   		}
	   		//check for image color preference
	   		changeImageToColor();
	   		
	   		//move the back buttons functions to the logic file, this really needs to be back end
	   		$("a.backButton").unbind().click(function(){	   			
	   			history.back(1);
	   			return false;
	   		});
	   	});   
	   
	   //initial check checkboxes
	   if ($("div.bundledProduct").find(".actions input:checked").length) {
	   		$("a.buttonAddToBasket").click(function(){
   		   		
		   		if ($("div.bundledProduct").find(".actions input:checked").length) {
		   			AddSelected2ShopCart(document.OrderItemAddForm); 
		   		}
		   		else {
		   			$("#bundlesFeedback").fadeIn("slow").find("p").html(noItemsSelected);
		   			animateToTop($("#bundlesFeedback"));
		   		}
		   		return false;		   
		   }); 
	   	}
	   	//if none are checked disable button
	   	else if ($("div.bundledProduct").find(".actions").length){
	   		$("a.buttonAddToBasket").unbind().addClass("disabled").click(function(){
	   			if($("#bundlesFeedback").length) {
	   				$("#bundlesFeedback").fadeIn("slow").find("p").html(noItemsSelected);	
	   				animateToTop($("#bundlesFeedback"));   				
	   			} 
	   			return false;  			
	   		});
	   		$("a.backButton").unbind().removeClass("disabled");		   			 
	   	}
	   	
	   	//check is just added then get prices ***to do*** only for pdp
	   	$("div.price").each(function(){
	   		if ($(this).find(".attrMemory").length) {
	   			var newSku = '';
	   			var memColour = '';
	   			var memSize = '';
	   			//if color swatches
	   			if ($(this).parent().find("ul.colourChips").length) {
		   			$(this).find(".attrMemory").each(function(i,val){
		   				if (newSku.length <= 0) newSku=HTMLEncode($(this).val());
		   				else newSku += '_'+HTMLEncode($(this).val());   				
		   				if (i==0) memColour = $(this).val();
		   				if (i==1) memSize = $(this).val();
		   			});	 
	   			}
	   			//if no color swatches and size dd
	   			else if ($(this).parent().find("div.dropdownoptions select").length){
	   				var sizeVal = HTMLEncode($(this).find(".attrMemory").val());
	   				newSku = sizeVal;	   			
		   			memSize = sizeVal;
	   			} 	   					
	   			 			
	   			//place prices of sku if remembered
	   			checkPrices($(this).parent(),newSku);
	   			//select remembered colour
	   			$(this).parent().find("ul.colourChips").find("li")
	   			.each(function(){
	   				var thisColour = $(this).find("input[type=radio]").val();
	   				if (thisColour==memColour){
	   					$(this).addClass("selected").find("input[type=radio]")[0].checked=true;
	   				}
	   			});
	   			//show selected text
	   			if (memColour)	{
	   				$(this).parent().find("span.colDesc").css("display","block").find("span").html(memColour);
	   				PriceUpSizes($(this).parent().find("div.dropdownoptions select"),memColour,"");
	   			}
	   			//enable sizes and pre select of remembered	   			
	   			$(this).parent().find("div.dropdownoptions select").removeAttr("disabled").find("option")
	   			.each(function(){
	   				if (this.value == memSize) this.selected = true;
	   			});
	   			//enable buttons if remembered
	   			enablePDPButtons();
	   		}
	   	});
	   	
	   
	   //on check function
	   $(".actions input[type=checkbox]").click(function(){
	   		
	   		//check this is available to be selected only if they have clicked to check it
	   		var stopAllCheck = false;
	   		if ($(this).is(":checked")) {
	   			//check color is selected
	   			if (!$(this).parent().parent().find(".colourChips input:checked").length && $(this).parent().parent().find(".colourChips").length){
		   			//select a color
		   			$(this).attr('checked', false);
		   			$("#bundlesFeedback").fadeIn("slow").find("p").html("Please choose all of the options and then click select");
		   			animateToTop($("#bundlesFeedback"));
		   			stopAllCheck = true;
		   		}	   		
		   		//check size is selected
		   		else if ($(this).parent().parent().find(".attribute select").val() == "Default" && $(this).parent().parent().find(".attribute select").length) {
		   			// tell user to select size
		   			$(this).attr('checked', false);
		   			 $("#bundlesFeedback").fadeIn("slow").find("p").html("Please choose all of the options and then click select");		   			
		   			animateToTop($("#bundlesFeedback"));
		   			stopAllCheck = true;
		   		}		   				   			   		   		
	   		}	   		
	   		
	   		if (!stopAllCheck) {
	   		
	   			/* To stop products from the bundle that have not been selected being added to the order we are populating the catentryid
	   			*  when the page loads in a unused input with a catEntryIdHidden class. Therefore, when the select box is checked copy the 
	   			*  "hidden" value into the "catentry" input so it get sent in the request.
	   			*  Added the same for partnumber as either will allow the sku to be added
	   			*/
	   			if ($(this).is(":checked")) {
	   				var catEntElem = $(this).parent().parent().find(".catEntryId");
	   				var catEntElemHidden = $(this).parent().parent().find(".catEntryIdHidden");
	   				var catEntValue = catEntElemHidden.attr('value');
	   				catEntElem.attr('value', catEntValue);
	   				
	   				var partNumberMem = $(this).parent().parent().find(".partnumberMemory"); 
	   				var partNumberParam = $(this).parent().parent().find(".partnumberParam");
	   				var partNumberVal = partNumberMem.attr('value');
	   				partNumberParam.attr('value', partNumberVal);
	   				
	   			}else{
	   				var catEntElem = $(this).parent().parent().find(".catEntryId");
	   				catEntElem.attr('value', '');
	   				
	   				var partNumberParam = $(this).parent().parent().find(".partnumberMemory");
	   				partNumberParam.attr('value', '');
	   			}
	   		
		   		//if one is checked then enable the add to basket button
		   		if ($(".actions input:checked").length) {
		   			$("div.message").fadeOut("slow")
		   			$("a.buttonAddToBasket").unbind().removeClass("disabled").click(function(){
		   				AddSelected2ShopCart(document.OrderItemAddForm); 
		   				return false;
		   			});	   			
		   		}
		   		else {
		   			$("a.buttonAddToBasket").unbind().addClass("disabled").click(function(){		   			
			   			$("#bundlesFeedback").fadeIn("slow").find("p").html(noItemsSelected);
			   			animateToTop($("#bundlesFeedback"));		   			
			   		});				   			
		   		}
		   	}
	   });
	   	   
	   //the color swtach functions
	   $("ul.colourChips li").css({
	   				overflow:"hidden",
	   				cursor:"pointer"
	   }).addClass("hideInputs").click(function(){	
	   		   		
	   		//assign this for later use
   			var thisEl = $(this);
   			var thisVal = jQuery.trim($(this).find("label").text());
   			
   			//determine if bundles or pdp
	   		if (thisEl.parent().parent().parent().parent().find("div.actions input[type=checkbox]").length){
	   			var bundles = true;
	   			var selectBox = $(this).parent().parent().parent().parent().find("div.options select");
	   			var rootElement = $(this).parent().parent().parent().parent();
	   			var prodId = $(this).parent().parent().parent().find(".productIdentifier").val();
	   		}
	   		else {
	   			var selectBox = $(this).parent().parent().parent().find("div.dropdownoptions select");
	   			var prodId = "";
	   			var rootElement = $(this).parent().parent().parent().parent().parent();
	   		}
	   		
	   		
	   		
	   		//make input selected
	   		$(this).parent().parent().find("ul.colourChips li").removeClass("selected");
	   		$(this).addClass("selected");		
	   		//for both types of page
	   		$(this).find("input[type=radio]")[0].checked = true;	   			
   			$(this).parent().parent().find("span.colDesc").css("display","block")
   			.find("span").html($(this).find("label").text());	   				
	   				
	   		
	   		//check selection is available
	   		//if size drop down is there
	   		if (selectBox.length) {
	   			var currentSizeVal = selectBox.val();
	   			if (currentSizeVal != "Default"){
	   				//reset the dropdown to size
	   				selectBox.find("option[selected]").removeAttr("selected");
					selectBox.find("option[value='Default']").attr("selected", "selected");								  						
	   			}
	   			
	   			//disable atb button + add to wishlist
	   			if (bundles) {
	   				//uncheck this
	   				rootElement.find("div.actions input")[0].checked = false;
	   				//check checked or not
	   				if (!$(".actions input:checked").length) {
	   					//disable the atb button
						$("a.buttonAddToBasket").addClass("disabled").unbind().click(function(){
							if($("#bundlesFeedback").length) {
				   				$("#bundlesFeedback").fadeIn("slow").find("p").html(noItemsSelected);	
				   				animateToTop($("#bundlesFeedback"));   				
				   			} 
							return false;
						});
	   				}
	   			}
	   			else {
	   				removeCheckSelection();
	   				//disable the atb button
					$("ul.actions a").addClass("disabled").unbind().click(function(){
						checkSelection();
						return false;
					});	   				
	   				//disable wish list link
	   				$("p.wishlist").find("a").addClass("disabled").unbind()
	   					.click(function(){
	   						checkSelection();				  				
		  					return false;
		  				});
	   			}
	   			
	   			//remove oos message
	   			if (rootElement.find("p.oosMessage").length) {
		  			rootElement.find("p.oosMessage").fadeOut("fast");
		  		} 
		  		 
	   			//change all the prices according to colour swatch picked
	   			PriceUpSizes(selectBox,thisVal,prodId);
	   			
	   			//enable and populate drop down
	   			selectBox.removeAttr("disabled"); 
	   			
	   			//create current skuName
	   			var skuName = prodId+thisVal;
	   			var partialSku = true;
	   		}
	   		else {
	   			var skuName = prodId;
   				skuName += thisVal;
   				var partialSku = false;
	   		}
	   		//reset alternative images on pdp
			if (!bundles) {
				removeCheckSelection();
				resetAlts();
			}	   
					
	   		//change image	   		
	   		imageChange(rootElement,skuName,$(this).find("input[type=radio]").val(),prodId,partialSku);
	   		
	   		if (skuName && !selectBox.length) {
	   			//Deal with Prices
	   			checkPrices(rootElement,skuName);
	   			
	   			   			   				   		
	   			var foundMatch = false;
	   			//loop through stock map
   				$.each(StockmapObj, function(key, value) {
   					//if it exists enable add to wishlist
   					if (skuName == key && !bundles) {	
   						$("p.wishlist").find("a").removeClass("disabled")
				  			.unbind().click(function(){
				  				Add2WishList(document.OrderItemAddForm);
				  				return false;
				  			});  
					}  					
   					//if not in stock
				  	if (skuName == key && value) {	
				  		
				  		if(thisEl.parent().parent().parent().parent().find("div.actions input[type=checkbox]").length) {		  		
				  			//found match
				  			thisEl.parent().parent().parent().parent().find("div.actions input[type=checkbox]").attr("disabled","disabled");
				  			thisEl.parent().parent().parent().parent().find("div.actions input[type=checkbox]")[0].checked = false;
				  		}
				  		else if (thisEl.parent().parent().parent().parent().parent().find("ul.actions a").length) {
				  			$("a.actionButton").unbind().addClass("disabled").click(function(){
				  				if($("#bundlesFeedback").length) {
					   				$("#bundlesFeedback").fadeIn("slow").find("p").html(noItemsSelected);	
					   				animateToTop($("#bundlesFeedback"));   				
					   			} 
				  				return false;
				  			});
				  		}
				  		//add or show a message to say out of stock
				  		if (rootElement.find("p.oosMessage").length) {
				  			rootElement.find("p.oosMessage").fadeIn("fast");
				  		}
				  		else {
				  			if(bundles) rootElement.find("div.actions").append('<p class="oosMessage">'+outOfStockMessage+'</p>');
				  			else rootElement.find("ul.actions").after('<p class="oosMessage">'+outOfStockMessage+'</p>');				  		
				  		}
				  		foundMatch = true;
				  	}
				  	//if is instock
				  	else if (skuName == key && !value) {
				  	
				  		//also check is available
				  		if (checkIsAvailable(skuName)) {		
					  		//remove disabled on bundles 		
					  		thisEl.parent().parent().parent().parent().find("div.actions input[type=checkbox]").removeAttr("disabled");
					  		//remove oos message
					  		if (rootElement.find("p.oosMessage").length) {
					  			rootElement.find("p.oosMessage").fadeOut("fast");
					  		}				  		
					  		//add atb functions for pdp
					  		if (!bundles) {
						  		$("ul.actions a").removeClass("disabled").unbind().click(function(){
						  			Add2ShopCart(document.OrderItemAddForm);
						  			return false; 
						  		});					  		
						  	}
					  		//flag match found
					  		foundMatch = true;	
					  	}  		
				  	}				  				  	
				});
				//if no matches were found show as diabled
				if (!foundMatch) {
					if (bundles) {
						thisEl.parent().parent().parent().parent().find("div.actions input[type=checkbox]").attr("disabled","disabled");
			  			thisEl.parent().parent().parent().parent().find("div.actions input[type=checkbox]")[0].checked = false;
			  			//if no other product selected disable atb button
			  			if (!$(".actions input:checked").length) {
			  				$("a.buttonAddToBasket").unbind().addClass("disabled").click(function(){
					   			if($("#bundlesFeedback").length) {
					   				$("#bundlesFeedback").fadeIn("slow").find("p").html(noItemsSelected);	
					   				animateToTop($("#bundlesFeedback"));   				
					   			} 
					   			return false;  			
					   		});
			  			}
				  		//add or show a message to say out of stock
				  		if (thisEl.parent().parent().parent().parent().find("div.actions p").length) {
				  			thisEl.parent().parent().parent().parent().find("div.actions p").fadeIn("fast");
				  		}
				  		else {
				  			thisEl.parent().parent().parent().parent().find("div.actions")
				  		.append('<p class="oosMessage">'+outOfStockMessage+'</p>');
				  		}
				  	}
				  	//if pdp
				  	else {
				  		//disable wishlist
				  		$("p.wishlist").find("a").addClass("disabled")
				  			.unbind().click(function(){return false;});
				  			
				  		//add or show a message to say out of stock
				  		if (thisEl.parent().parent().parent().parent().parent().find("p.oosMessage").length) {
				  			thisEl.parent().parent().parent().parent().parent().find("p.oosMessage").fadeIn("fast");
				  		}
				  		else {
				  			thisEl.parent().parent().parent().parent().find("ul.actions")
				  			.after('<p class="oosMessage">'+outOfStockMessage+'</p>');
				  		}
				  		//disable the atb button
					  	$("ul.actions a").addClass("disabled").unbind().click(function(){return false;});
				  	}
				}
	   		}
	   });
	  
   		$("div.options select,div.dropdownoptions select").change(function(){   			
	   			
   			//assign this for later use
   			var thisEl = $(this);
   			
   			//determine if bundles or pdp
	   		if (thisEl.parent().parent().parent().find("div.actions input[type=checkbox]").length){
	   			var bundles = true;
	   			var coloursElement = $(this).parent().parent().parent().find("div.options ul.colourChips");
	   			var rootElement = $(this).parent().parent().parent();
	   			var prodId = $(this).parent().parent().find(".productIdentifier").val();
	   		}
	   		else {
	   			var coloursElement = $(this).parent().parent().find("ul.colourChips");
	   			var prodId = "";
	   			var rootElement = $(this).parent().parent().parent().parent();
	   		}
   			
   			//if deselected then remove the checked
   			if ($(this).val()=="Default" && bundles) {
   				rootElement.find("div.actions input[type=checkbox]")[0].checked = false;
   				if (!$(".actions input:checked").length) {		   		
		   			$("a.buttonAddToBasket").unbind().addClass("disabled").click(function(){		   			
			   			animateToTop($("#bundlesFeedback"));
			   			return false;		   			
			   		});	
		   		}
   			}
   			//if deselected on the pdp
   			else if ($(this).val()=="Default" && !bundles) {
   				$("a.buttonAddToBasket").unbind().addClass("disabled").click(function(){
   					checkSelection();		   			
		   			return false;		   			
		   		});
		   		//disable wishlist
		  		$("p.wishlist").find("a").addClass("disabled")
		  		.unbind().click(function(){
		  			checkSelection();
		  			return false;
		  		});
   			}
   			//remove any selection checking
   			else if ($(this).val()!="Default" && !bundles) {
   				removeCheckSelection();
   			}
   			
   			//check if color is selected too   			
   			if (coloursElement.find("input:checked").length && coloursElement.length){
   				  				
   				var skuName = prodId;
   				skuName += coloursElement.find("input:checked").val();
   				skuName += "_"+HTMLEncode($(this).val());
   				if ($(this).val()=="Default") return;   				
   			}
   			//check if color is even there
   			else if (!coloursElement.length) {   				
   				var skuName = prodId;
   				skuName += HTMLEncode($(this).val());
   				if ($(this).val()=="Default") return;   				
   			}
   			//use sku to check stock
   			if (skuName) {   				
   				
   				//Deal with Prices
	   			checkPrices(rootElement,skuName); 
	   			
	   			//reset alternative images on pdp
				if (!bundles) resetAlts();
					
	   			//change image
	   			imageChange(rootElement,skuName,coloursElement.find("input:checked").val(),prodId); 
	   				
	   			
   				var foundMatch = false;
   				//loop through stock map
   				$.each(StockmapObj, function(key, value) { 
   					//if not in stock
				  	if (skuName == key && value) {
				  		//if it exists enable add to wishlist
	   					if (skuName == key && !bundles) {	
	   						$("p.wishlist").find("a").removeClass("disabled")
					  			.unbind().click(function(){
					  				Add2WishList(document.OrderItemAddForm);
					  				return false;
					  			});  
						}
				  		//found match				  		
				  		if (bundles) {
				  			rootElement.find("div.actions input[type=checkbox]").attr("disabled","disabled");
				  			rootElement.find("div.actions input[type=checkbox]")[0].checked = false;	
				  			//if no other products selected disable atb bitton too
				  			if (!$(".actions input:checked").length) {
				  				$("a.buttonAddToBasket").unbind().addClass("disabled").click(function(){
						   			if($("#bundlesFeedback").length) {
						   				$("#bundlesFeedback").fadeIn("slow").find("p").html(noItemsSelected);	
						   				animateToTop($("#bundlesFeedback"));   				
						   			} 
						   			return false;  			
						   		});
				  			}			  			
				  		}
				  		else {
				  			//disable the atb button
					  		$("ul.actions a").addClass("disabled").unbind().click(function(){					  								  			
					  			checkSelection();
					  			return false;
					  		});
				  		}
				  		//add or show a message to say out of stock
				  		if (rootElement.find("p.oosMessage").length) {
				  			rootElement.find("p.oosMessage").fadeIn("fast");
				  		}
				  		else {
				  			if (bundles) rootElement.find("div.actions").append('<p class="oosMessage">'+outOfStockMessage+'</p>');
				  			else rootElement.find("ul.actions").after('<p class="oosMessage">'+outOfStockMessage+'</p>');				  		
				  		}
				  		foundMatch = true;
				  	}
				  	//if is instock
				  	else if (skuName == key && !value) {
				  					  		
				  		//also check is available
				  		if (checkIsAvailable(skuName)) {				  						  							  					
					  		if (bundles) rootElement.find("div.actions input[type=checkbox]").removeAttr("disabled");
					  		if (rootElement.find("p.oosMessage").length) {
					  			rootElement.find("p.oosMessage").fadeOut("fast");
					  		}
					  		//add atb functions for pdp
					  		if (!bundles) {
						  		$("ul.actions a").removeClass("disabled").unbind().click(function(){
						  			Add2ShopCart(document.OrderItemAddForm);
						  			return false; 
						  		});
						  		$("p.wishlist").find("a").removeClass("disabled")
						  			.unbind().click(function(){
						  				Add2WishList(document.OrderItemAddForm);
						  				return false;
						  			}); 
						  	}
					  		foundMatch = true;	
					  	}			  		
				  	}				  	
				});
				//if no matches were found
				if (!foundMatch) {
										
					if (bundles) {
						rootElement.find("div.actions input[type=checkbox]").attr("disabled","disabled");
			  			rootElement.find("div.actions input[type=checkbox]")[0].checked = false;
			  			//if no other products selected disable atb bitton too
			  			if (!$(".actions input:checked").length) {
			  				$("a.buttonAddToBasket").unbind().addClass("disabled").click(function(){
					   			if($("#bundlesFeedback").length) {
					   				$("#bundlesFeedback").fadeIn("slow").find("p").html(noItemsSelected);	
					   				animateToTop($("#bundlesFeedback"));   				
					   			} 
					   			return false;  			
					   		});
			  			}
			  		}
			  		else {
			  					  			
			  			//disable wishlist
				  		$("p.wishlist").find("a").addClass("disabled")
				  			.unbind().click(function(){
				  			checkSelection();
				  			return false;
				  		});
			  			//disable the atb button
					  	$("ul.actions a").addClass("disabled").unbind().click(function(){
					  		checkSelection();
					  		return false;
					  	});					  	
			  		}
			  		//add or show a message to say out of stock
			  		if (rootElement.find("p.oosMessage").length) {
			  			rootElement.find("p.oosMessage").fadeIn("fast");
			  		}
			  		else {
			  			if (bundles) rootElement.find("div.actions").append('<p class="oosMessage">'+outOfStockMessage+'</p>');
			  			else rootElement.find("ul.actions").after('<p class="oosMessage">'+outOfStockMessage+'</p>');				  		
			  		}
				}
   			}
   		});
	


/* 
		RANGE DETAILS ENHANCEMENTS
   ---------------------------------------------------------------- */
   
	//Highlight the focused item in the range contents list while the user is playing with the form */
	
	$('#pagebody ul.rangeLister').each(function() {
		$('input, select', this).focus(function() {
			$(this).closest('li.rangeItem').addClass('focus').siblings().removeClass('focus');
		});
	});

	//Shunt the alt images around in the DOM
	$('#maincontent > div.imagedisplay > div.alternativeview')
		.appendTo('#maincontent > div.detailsdisplay');
		
	$('div.detailsdisplay, div.imagedisplay', 'body.rangeDetail #maincontent').wrapAll('<div id="liner"></div>');
	
   
   	/* SF 30.11.09 CR043 - Change bkg and color of current price if product has was price  
	$('.rangeLister .additionalPricingInfo li:last-child').addClass('darkerWas');
	$('.rangeLister .darkerWas').parent().parent().next().addClass('mainPriceHasWasPrice');
	$('.rangeLister .mainPriceHasWasPrice').parent().parent().parent().parent().addClass('formHasWasPrice');
	
	Removed this dynamic styling */	 
	
	$(".carouselWrap").each(function(){
		
		var cs = {
			cTh				: $(this),
			cShowing		: 2,
			cWidth			: $(this).css("width"),
			cLiWidth		: $(this).find("div.carouselControl>ul>li").css("width"),
			cLiPaddingRight	: $(this).find("div.carouselControl>ul>li").css("paddingRight"),
			cLiPaddingLeft	: $(this).find("div.carouselControl>ul>li").css("paddingLeft"),
			cLiBorderRight	: $(this).find("div.carouselControl>ul>li").css("borderRightWidth"),
			cLiBorderLeft	: $(this).find("div.carouselControl>ul>li").css("borderLeftWidth"),
			cLiHeight		: $(this).find("div.carouselControl>ul>li").css("height"),
			cControlObj		: $(this).find("div.carouselControl"),
			cButtonsObj		: $(this).find("div.carouselButtons"),	
			cPrevHtml		: '<span class="prev disabled">Previous</span>',
			cNextHtml		: '<span class="next">Next</span>'
		};	
		
		
				
		//set up styles
		cs.cButtonsObj.css("height",cs.cLiHeight);
		cs.cControlObj.css({
				height:cs.cLiHeight,
				position:"absolute",
				top:"0px",
				left:"0px"
				});
		
		//calculate positions
		var currentCarouselPosition = parseInt(cs.cControlObj.css("left"));
		var jump = parseInt(cs.cLiWidth)+parseInt(cs.cLiPaddingRight)+parseInt(cs.cLiPaddingLeft)+parseInt(cs.cLiBorderLeft)+parseInt(cs.cLiBorderRight);
		//number of items		
		var steps = $(this).find("div.carouselControl>ul>li").length;
		
		//if less items than capable of showing end function
		if (steps<=cs.cShowing) return;
		
			
		//Set up mark up
		cs.cTh.append(cs.cPrevHtml+cs.cNextHtml);
		
		
		
		
		//create animations
		cs.cTh.find("span.next").click(function(){
			
			if ((currentCarouselPosition+(jump*cs.cShowing))<(steps*jump)) {
				currentCarouselPosition += jump;
				cs.cControlObj.animate({ 			   
				    left: "-="+jump
				  }, 500 );
				if (currentCarouselPosition>=jump) cs.cTh.find("span.prev").removeClass("disabled");
				if ((currentCarouselPosition+(jump*cs.cShowing))>=(steps*jump)) cs.cTh.find("span.next").addClass("disabled");				  
			}
			
			
						
		});
		cs.cTh.find("span.prev").click(function(){
			if ((currentCarouselPosition+jump)>jump) {
				currentCarouselPosition -= jump;
				cs.cControlObj.animate({ 			   
				    left: "+="+jump
				  }, 500 );
				if ((currentCarouselPosition+jump)<=jump) cs.cTh.find("span.prev").addClass("disabled");
				if ((currentCarouselPosition+(jump*cs.cShowing))<=(steps*jump)) cs.cTh.find("span.next").removeClass("disabled");				  
			}
		});
		
	});
   
});

//change prices dynamicaly
function checkPrices(thisElement,skuName) {
	var skuSettings = map.get(skuName);
	if (!skuSettings) return;
	if (skuSettings.getPrice().getNowPrice()) {
		if (skuSettings.getPrice().getWasPrice()) thisElement.find("span.label").html("Now");
		else thisElement.find("span.label").html("");	
	   	thisElement.find("li.mainPrice").show()	   	
	   	.find("span.amount").html(skuSettings.getPrice().getNowPrice());
	}
	else thisElement.find("li.mainPrice").hide();
	
	if (skuSettings.getPrice().getWasPrice()) {
		thisElement.find("li.wasPrice").show()
		.find("span.label").html("Was").end()
		.find("span.amount").html(skuSettings.getPrice().getWasPrice());
	}
	else thisElement.find("li.wasPrice").hide();
	
	if (skuSettings.getPrice().getWasWasPrice()) {
		thisElement.find("li.wasWasPrice").show()
		.find("span.label").html("Was").end()
		.find("span.amount").html(skuSettings.getPrice().getWasWasPrice());
	}
	else thisElement.find("li.wasWasPrice").hide();
	
	if (skuSettings.getPrice().getSavingAmount() && skuSettings.getPrice().getWasPrice()) {
		thisElement.find("li.saveuptoamount").show()
		.find("span.label").html("Save").end()
		.find("span.amount").html(skuSettings.getPrice().getSavingAmount());
	}
	else thisElement.find("li.saveuptoamount").hide();
	
	
}
function imageChange(thisElement,skuName,colour,thisprodId,partialSku) {

	//if full sku is not there yet get the first full sku	
	if (partialSku) {	
		skuName = thisprodId+colour+"_"+optionValueMap.get(skuName)[0];	
		var skuSettings = map.get(skuName);		
		var imgKey = thisprodId+colour;		
	}
	else if (colour) {
		var skuSettings = map.get(skuName);
		var imgKey = thisprodId+colour;
	}
	else {
		var skuSettings = map.get(skuName);
		var imgKey = skuName;
	}
	
	if (skuSettings) {		
		var newSmallImage =  skuSettings.getAlternativeImages().get(imgKey).getSmallImage();
		var newLargeImage =  skuSettings.getAlternativeImages().get(imgKey).getLargeImage();
		var newHugeImage =  skuSettings.getAlternativeImages().get(imgKey).getHugeImage();
						
		if (newSmallImage.length) {
			if (thisElement.find("div.image img").length) {
				//check to see if its the same image if so stop change
				if 	(thisElement.find("div.image img").attr("src")==newSmallImage) return;
				if (!newSmallImage.match(".jpg")) return;
					
				thisElement.find("div.image img").fadeOut(200, function(){
					$(this).attr("src",newSmallImage).fadeIn(200);				
				})
				//fix for ie
				.attr("style","zoom:1");
				//change the zoom src on the a tag				
				thisElement.find("div.image a.largerAlt").attr("href",newHugeImage);
			}
			else {				
				//if the same, stop the change
				if 	(thisElement.parent().parent().find("div.productimage img").attr("src")==newLargeImage) return;
				if (!newLargeImage.match(".jpg")) return;
				//fade out old image and fade in new
				thisElement.parent().parent().find("div.productimage img").fadeOut(200);
				thisElement.parent().parent().find("div.productimage img").attr("src",newLargeImage).fadeIn(200);					
				
				thisElement.parent().parent().find("div.productimage a").attr("href",newHugeImage);
			}
		}
	}
	
}
function PriceUpSizes(dropDownElement,colour,prodId) {	
	//remove disabled as we are now using this dropdown
	dropDownElement.removeAttr("disabled");
	//set product indentfier + concat
	var semiSku = prodId+colour;
	//loop through stock and match prices for this colour
	var options = optionValueMap.get(semiSku);	
	if (options) {		
		//create new drop down options
		//if only one size select it and remove the please select and enable buttons
		if (options.length==1) {			
			var newOptionsHtml = '';
			var onlyOneSize = options[0];
			//if pdp we can enable buttons at this point as there is only 1 option
			enablePDPButtons();
			//change price as we have full sku			
			if(dropDownElement.parent().parent().parent().parent().attr("id")=="productActions") {				
				var getroot = dropDownElement.parent().parent().parent().parent();				
				checkPrices(getroot,semiSku+"_"+onlyOneSize);
			}
			else {
				var getroot = dropDownElement.parent().parent().parent();
				checkPrices(getroot,semiSku+"_"+onlyOneSize);
			}
			
		}
		else var newOptionsHtml = '<option value="Default">Please Select</option>';
		//loop through all options checking for values
		$.each(options, function(key, value) { 
	   		var skuSettings = map.get(semiSku+"_"+value);
			if (skuSettings) {
				//add each drop down				
				newOptionsHtml += '<option value="'+value+'">'+value+' '+skuSettings.getPrice().getNowPrice()+'</option>';						
			}			
		});	
		//append drop downs
		dropDownElement.html(newOptionsHtml);	
		//if second attribute check stock	
		if (onlyOneSize) {	
			if (checkStockMap(semiSku+'_'+onlyOneSize) || !checkIsAvailable(semiSku+'_'+onlyOneSize)){			
				oosEvents(dropDownElement);
			}
			else isEvents(dropDownElement);	
		}
	}	
}

function enablePDPButtons(){
	
	$("ul.actions a").removeClass("disabled").unbind().click(function(){
  			Add2ShopCart(document.OrderItemAddForm);
  			return false; 
  		});
  	if ($("p.wishlist").length) {
  		$("p.wishlist").find("a").removeClass("disabled")
  			.unbind().click(function(){
  				Add2WishList(document.OrderItemAddForm);
  				return false;
  			});
  	}

}
function resetAlts() {
	$("input.altsArray").each(function(){
		var thumb = $(this).parent().find("a");
		if ($(this).val()!=thumb.attr("href")) {
			thumb.attr("href",$(this).val())
			.find("img").attr("src",$(this).val().replace(/large/,/extrasmall/));
		}
	});
}

function checkStockMap(skuName) {
	var oos=false;
	$.each(StockmapObj, function(key, value) {   					
		if (skuName == key && value) {			
			oos=true;
		}
	});	
	if (oos) {return true;}
	else return false;
}

function checkIsAvailable(skuName) {	
	var oos=false;
	var skuSettings = map.get(skuName);		
	if (skuSettings) {
		if (skuSettings.getPurchasable()=="true") oos = true;			
		if (oos) {return true;}
		else return false;		
	}
	else return false;
}

function oosEvents(fromDropDown) {
	if (fromDropDown.parent().hasClass("attribute")) {
		var rootElement = fromDropDown.parent().parent().parent();
		var bundles=true;
	}
	else var rootElement = fromDropDown.parent().parent().parent().parent();
	
		
		//found match
		if (bundles) {
			rootElement.find("div.actions input[type=checkbox]").attr("disabled","disabled");
			rootElement.find("div.actions input[type=checkbox]")[0].checked = false;	
			  		  			
		}
		else {
			//disable the atb button
			$("ul.actions a").addClass("disabled").unbind().click(function(){return false;});
		}
		//add or show a message to say out of stock
		if (rootElement.find("p.oosMessage").length) {
			rootElement.find("p.oosMessage").fadeIn("fast");
		}
		else {
			if (bundles) rootElement.find("div.actions").append('<p class="oosMessage">'+outOfStockMessage+'</p>');
			else rootElement.find("ul.actions").after('<p class="oosMessage">'+outOfStockMessage+'</p>');				  		
		}		
	
}

function isEvents(fromDropDown){
	if (fromDropDown.parent().hasClass("attribute")) {
		var rootElement = fromDropDown.parent().parent().parent();
		var bundles=true;
		rootElement.find("div.actions input[type=checkbox]").removeAttr("disabled");
	}
	
}

function changeImageToColor() {
	var pathname = window.location.href;
    if (pathname.indexOf("#") != -1) {
    	var mfPartNumber = pathname.substr(pathname.indexOf("#") + 1);
    	var skuColour = map.get("MFPartNo-" + mfPartNumber);    	
    	var skuColourSelector = skuColour.replace(" ", "_");
    	skuColourSelector = skuColourSelector.replace("(", "");
    	skuColourSelector = skuColourSelector.replace(")", "");    	
    	//change image only work for home page at the mo
    	imageChange($("#productActions"),skuColour,skuColour,"",true);
    	
    }
}
function danddReviewControl() {	
	//manipulate the review text
   	if ($(".pr-snippet-write-first-review p").length) {
   		$(".pr-snippet-write-first-review p").remove();
   	}

}
function animateToTop(element){
	//scroll to the error message if off the page		   		
    var target_offset = element.offset();
    var target_top = target_offset.top;
    $('html, body').animate({scrollTop:target_top}, 500);		
}
function HTMLEncode(str){	
     //add special charachters as you need them or align with backend encoding
     //these are the ones I can find that are replaced by the backend
     str = str.replace(/\&/g,"&amp;");		//ampersands &
     str = str.replace(/\"/g,"&#034;");		//double quotes "
     str = str.replace(/\'/g,"&#039;");		//singlequotes '
     str = str.replace(/\</g,"&lt;");		//lower than <
     str = str.replace(/\>/g,"&gt;");		//greater than >    
     return str;
}

function checkSelection() {		
	var attrRoot = $("#productActions").find("div.attribute");	
	if ($("ul.colourChips li").length && !$("ul.colourChips").find("input:checked").length) {		
		//change text
		$("p.messageText").html("Please tell us what colour you would like").show();
		//make label black
		$("ul.colourChips").prev("label").addClass("errLabel");
		//add error class
		attrRoot.addClass("error");		
	}	
	else if ($("div.dropdownoptions select").length && $("div.dropdownoptions select").val()=="Default") {		
		if ($("ul.colourChips").find("input:checked").length) {			
			$("ul.colourChips").prev("label").removeClass("errLabel");			
		}
		$("p.messageText").html("Please tell us what "+$("div.dropdownoptions select").prev("label").find("span").html().toLowerCase()+" you would like").show();
		attrRoot.addClass("error");
		$("div.dropdownoptions select").prev("label").addClass("errLabel");
	}
	else {
		removeCheckSelection();
	}
}
function removeCheckSelection() {
	var attrRoot = $("#productActions").find("div.attribute");
	attrRoot.removeClass("error");
	attrRoot.find("label.errLabel").removeClass("errLabel");
	$("p.messageText").hide();
}



