$.namespace("SF.ProductVariantsHandler");

/**
* Create a new product variant handler - can be more than 1 on a page (e.g. bundle)
* @class Represents a product variant handler
* @constructor
* @name SF.ProductVariantsHandler
* @param {HTMLElement} root As DOM reference to product description panel
*/
SF.ProductVariantsHandler = function(root, async) {
	var productID = $(root).find("input[rel='productId']").val() || $(root).find("input[name='productId']").val() || null;
	var childItemId = $(root).find("input[rel='childItemId']").val() || $(root).find("input[name='childItemId']").val() || null;
	var thisCurrentSuperSwatchName = "";
	var thisCurrentSuperSwatchImage = "";

	if(!productID) return null;

	var customEvent = Salmon.UI.CustomEvents.productAttributeChanged+productID;
	var form = $(root).find("form")[0] || $(root).find(".productForm")[0] || null; 
	var fields, attributeCollection = [];
	
	// find all form fields on the page that are attributes
	var attributeElements = $(root).find(".attribute");
	var isStaticImage = null;

	for(var i = attributeElements.length-1; i>=0; i--) {
		fields = $(attributeElements[i]).find("input[type='radio'], select");
		attributeCollection.push(new Attribute(fields));
	}

	// Now we trigger the default option to simulate a click on the first radio option
	// this ensures the options is subsequent dropdowns are valid for the selected option
	setDefaultFirstOption(fields);
	
	/**
	* Create a new attribute
	* @class Represents a product attribute
	* @constructor
	* @name Attribute
	* @param {Nodes[]} fields Array of DOM nodes
	*/
	function Attribute(fields) {
		var name = $(fields)[0].name;
		// has to be hard coded
		if(name==="Colour" || name==="Fragrance" || name==="Flavour" || name.substring(0,7) === "Colour_" || name.substring(0,10) === "Fragrance_" || name.substring(0,8) === "Flavour_") {
			return new ColourAttribute(fields);
		}
		else {
			return new SelectAttribute(fields[0]);
		}
	};

	/**
	* Create a new colour attribute in the form of radios
	* This has now been extended to work for Fragrance and Flavour also
	* @class Represents a colour attribute
	* @constructor
	* @name ColourAttribute
	* @param {Nodes[]} radios Array of DOM nodes (radios)
	*/	
	function ColourAttribute(radios) {
 		var me = this;
		var hoverClass = "hover";
		var currentColour = "no colour";
		var value = null;
		this.value = value;

		// determine user agent
		var user = new SF.UserAgent(); 
		var uagent = user.getUagent(); 

		// add indicator to show selected color
		var indicator = document.createElement("p");
		indicator.className = "indicator";
		indicator.innerHTML = currentColour;
		$(radios).parents("div.radios").append(indicator);

		var labels = (function(){
			var labels = [];
			for ( var i = 0; i < radios.length; i++ ) {
				radio = radios[i];
				label = getLabel(radio);
				labels.push(label);
			};

			return labels;
		}());
		
		setupLabels();
		
		function setupLabels() {
			var radio,
				label;
			for ( var i = 0; i < radios.length; i++ ) {
				radio = radios[i];
				label = getLabel(radio);
				label.colour = getLabelColour(radio);
				
				$(label).bind("click", label_onClick);

				// for mobile do not bind these event listeners
				if (uagent == 'desktop') {
					$(label).bind("mouseover", label_onMouseover);
					$(label).bind("mouseout", label_onMouseout);
				}
				
				if(radio.checked) {
					label_onClick.call(label);
				}
			}
		}

		setupStaticImage();

		function setupStaticImage(){
			var foundItem = false;
			var itemName = "";
			for (var whatItem in SF.ProductData.data){
				if(!foundItem) {
					itemName = whatItem;
					/* IN:019970 - Pip Hodge - commented the below line out because if we are viewing a product as Sneak a Peek from a PDP page
					*  (because it's from a 'You may also like' product), the itemName is actually the itemName of the PDP underneath
					*  which makes the swatches act on that and not the Sneak a Peek window.  Hope that makes sense.
					* foundItem = true;
					*/
				}
			}

			if (SF.ProductData.data[itemName]) {
				isStaticImage = (SF.ProductData.data[itemName].staticImage == true) ? true : false;
			} else {
				isStaticImage = false;
			}

			if($.browser.msie){
				var userAgent = $.browser.version;
				userAgent = userAgent.substring(0,userAgent.indexOf('.'));
				var version = userAgent;
				if(version <= 6){
					$("#imageSwatchHolder").css("border","solid 1px #fff");
				}
			}
		};
		
		function getLabels() {
			return labels;
		};

		function getLabel(radioNode) {
			return $(radioNode).next("label")[0] || $(radioNode).prev("label")[0] || null;
		};
		
		function getLabelColour(radioNode) {
			return radioNode.value;
		};
		
		function setValue(value) {
			me.value = value;
		};
		
		function setCurrentColour(value) {
			currentColour = value;
		};
		
		function updateIndicator() {
			indicator.innerHTML = currentColour;
		};

		function label_onClick() {
 		if($(".quickLookImage").length) {
                var swatchImgSrc =  $(this).find("img").attr("src")
                } else {
                var swatchImgSrc = $(this).css("background-image").replace(/"/g,"").replace(/url\(|\)$/ig, "") || null;
                }
			if (isStaticImage) {
				if(swatchImgSrc){
					showStaticSwatch(swatchImgSrc);
				}
			}

			if (this.colour === getCurrentColour()) {
				return false;
			};

			thisCurrentSuperSwatchName = this.colour;
			thisCurrentSuperSwatchImage = swatchImgSrc;
			setCurrentColour(this.colour);
			setValue(this.colour);
			updateIndicator();
			updateVariants(this);

			// We only want to do this on the PDP page ... 
			// this code was kicking in on Sneak a Peek which broke SAP.
			// and not bundles either! - DLT
			if ($('body#pgProductDetail').length > 0) {
				var mainImageSrc = $('div#productImage img#largeImage').attr('src').toString();
				var mainImageSrcArray = mainImageSrc.split('/'); 
				var imageSrc = mainImageSrcArray.pop(); 
				var mainImageSrcRoot = mainImageSrcArray.join('/'); 
				var imageSrcArray = imageSrc.split('?'); 
				var imageId = $('div#productImage img#largeImage').attr('class').toString();

				// switch thumbnail images
				var thumbs = $('ul#productThumbnails').find('li');
				var i = 0; 
	
				$(thumbs).each(function() {
					i++; 
				
					if ($(this).hasClass('altimage')) {
						var link = $(this).children('a').attr('href'); 				
						var image = $(this).children('a').children('img'); 
						var imageSrc = mainImageSrcRoot + '/' + imageSrcArray[0] + '_ALT0' + i + '?$PDP_THMBNL$'; 
	
						$(image).attr('src', imageSrc); 
					}
				});
	
				SF.ProductAltImages.performCheck(imageId); 
			}
		};
		
		function showStaticSwatch(whatSwatch){
			var croppedURLArr =whatSwatch.split('?') || null ; //we don't need additional params after ?			
			
			if(croppedURLArr){			
				var newSwatch =croppedURLArr[0].replace(/_SW/g,"_SW_M\?\$PDP_SW_M\$")
				if($("#productInformation").find("#imageSwatchHolder").length <= 0){
					addImageSwatchHolder();
				}
	
				addImageToSwatchHolder(newSwatch);
			}
		};

		function addImageSwatchHolder(){
			if($(".quickLookImage").length ){
				$(".quickLookImage").append("<div id=\"imageSwatchHolder\"></div>");
			} else {
				$("#productImage").append("<div id=\"imageSwatchHolder\"></div>");
			}
		};

		function addImageToSwatchHolder(image){
			 if($(".quickLookImage").length ){
                	$(".quickLookImage").find("#imageSwatchHolder").find("img").attr("width","50");
                	$(".quickLookImage").find("#imageSwatchHolder").find("img").attr("height","50");
					$(".quickLookImage").find("#imageSwatchHolder").find("img").attr("src",image);
               } else {
					$("#imageSwatchHolder").empty().append("<img />")
					$("#imageSwatchHolder").find("img").attr("src",image);
			}
		}
		
		function getCurrentColour() {
			return currentColour;
		};
		
		function label_onMouseover() {
			$(this).parent().siblings().find("label").removeClass(hoverClass);
			$(this).addClass(hoverClass);
		};
		
		function label_onMouseout() {
			$(this).removeClass(hoverClass);
		};	
	};
	
	function setDefaultFirstOption(radios) {
		updateVariants();
	};
	
	/**
	* Create a new select attribute in the form of a select box
	* @class Represents a product attribute
	* @constructor
	* @name SelectAttribute
	* @param {HTMLElement} select As DOM reference
	*/		
	function SelectAttribute(select) {
		var me = this;
		var value = null;
		this.value = value;
		
		var name = select.name;
		// If only 1 option in select then default to that option (first option is the select option value)
		if (select.length == 2) {
			this.value = select[1].value;
		}
		
		$(select).bind("change", change);
		$.subscribe(customEvent, updateMe);

		function change() {
			// console.log('change!'); 
		
			me.value = $(this).val();
			updateVariants();
		};
		
		function updateMe(e) {
			var data = e.data[0] || null;
			if(!data) return;
			if(data.attributeName === name) {
				removeOptions();
				addOptions(data.attributeValues);
			}
		};
		
		function removeOptions() {
			var options = select.options;
			var option = null;
			var optionsToRemove = [];
			for(var i = 1; i<options.length; i++) {
				option = options[i];
				if(option.value === "") continue;
				optionsToRemove.push(option);				
			}
			$(optionsToRemove).remove();		
		};
		
		function addOptions(options) {
			var option = null;
			for(var i = 0; i<options.length; i++) {
				option = document.createElement("option");
				option.value = options[i];
				option.innerHTML = options[i];
				select.appendChild(option);
			}
		};
	};

	/**
	*
	*	Commenting out price stuff - it seems to have been superceded by
	*	the PriceDisplay constructor. I may be wrong. Steve 26/02/2010
	*/
	
	/**
	* Creates the price handler
	* @constructor
	* @static
	* @name Price
	*/		
	/*
	var Price = new (function(){
		var node = $(root).find("li.price")[0] || null;
		if(!node) return;
		$.subscribe(customEvent, update);
		function update(e) {
			var data = e.data[0] || null;
			if(!data) return;
			var prices = data.prices || null;
			if(!prices) return;
			var price = prices[0] || null;
			if(typeof price !== "string") return;
			$(node).html(price);
		}	
	});
	*/
	
	/**
	* Creates the was price handler
	* @constructor
	* @static
	* @name WasPrice
	*/		
	/*
	var WasPrice = new (function(){
		var node = $(root).find("li.wasPrice")[0] || null;
		if(!node) return;
		$.subscribe(customEvent, update);
		function update(e) {
			var data = e.data[0] || null;
			if(!data) return;
			var prices = data.prices || null;
			if(!prices) return;
			var price = prices[1] || null;
			if(typeof price !== "string") return;
			$(node).html(price);
		}	
	});
	*/

	var PriceDisplay = new (function(){
		var ul = $(root).find("div.prices ul")[0] || null;
		if(!ul) return null;
		
		$.subscribe(customEvent, update);
		
		function update(e) {
			var data = e.data[0] || null;
			if(!data) return;
			var prices = data.prices || null;
			setDiscount(data.offerDiscount || null);
			if(prices.length === 0) return;
			setPrices(prices);
		};
		
		function setPrices(prices) {
			/* 
			* These need to be formatted like this: 
			*
				<ul>
					<li class="wwasPrice"><span>Was £1,199.00</span></li>
					<li class="wasPrice"><span>Was £1,099.00</span></li>
					<li class="price"><span class="now">Now <span class="amount">£999.00</span></span></li>
				</ul>
			*/

			$(ul).find("li.price").remove();
			$(ul).find("li.wasPrice").remove();
			$(ul).find("li.wwasPrice").remove();

			var html = "";

			for (var i = 0; i < prices.length; i++) {
				var priceArray = prices[i].split('&pound;'); 

				if (prices.length == 3) {			// need wwas, was and now
					if (i == 0) {					// wwas
						html +=	'<li class="wwasPrice"><span>' + prices[i] + '</span></li>';
					} else if (i == 1) {			// was
						html +=	'<li class="wasPrice"><span>' + prices[i] + '</span></li>'; 
					} else {						// now
						html +=	'<li class="price"><span class="now">' + priceArray[0] + '<span class="amount">' + '&pound;' + priceArray[1] + '</span></span></li>'; 
					}
				} else if (prices.length == 2) {	// need was and now
					if (i == 0) {					// was
						html +=	'<li class="wasPrice"><span>' + prices[i] + '</span></li>'; 
					} else {						// now
						html +=	'<li class="price"><span class="now">' + priceArray[0] + '<span class="amount">' + '&pound;' + priceArray[1] + '</span></span></li>'; 
					}
				} else {							// only display normal price
					html +=	'<li class="price">' + prices[i] + '</li>';
				}
			}

			$(ul).prepend(html);
		};

		function setDiscount(discount) {
			var offer = $(ul).find("li.offer");
			if(offer.has("a") && discount != "") {
				offer.find("a").html(discount);
			} else {
				offer.html(discount);
			}
		};
	});	

	
	/**
	* Creates the price history handler
	* @constructor
	* @static
	* @name PriceHistory
	*/		
	var PriceHistory = new (function(){
		var hideClass = "hide";
		var node = $(root).find("div.priceHistory")[0] || null;
		if(!node) return;

		$(node).addClass("priceHistoryEnhanced");
		var a = $(node).find("a.activator")[0] || null;
		if(!a) return;
		a.href="#";
		var details = $(node).find("div.details")[0] || null;
		if(!details) return;

		$(details).bgiframe();
		var ul = $(details).find("ul")[0] || null;
		if(!ul) return;
		$(details).addClass(hideClass);
		$(a).bind("mouseenter", showPanel);
		$(node).bind("mouseleave", hidePanel);
		function showPanel() {
			// Coremetrics price history tagging.
			var sfcmScript = $(details).find( ".sfcmScript" ).html(); 
			
			if ( sfcmScript ) 
				eval( sfcmScript );
			
			$(details).removeClass(hideClass);
		}
		
		function hidePanel() {
			$(details).addClass(hideClass);
		}
		
		function update(e) {
			var data = e.data[0] || null;
			if(!data) return;
			var priceHistory = data.priceHistory || null;
			if(priceHistory.length === 0) return;
			setPriceHistory(priceHistory);
		}
		
		function setPriceHistory(priceHistory) {
			var html = '';

			for(var i = 0; i<priceHistory.length; i++) {
				html +=	"<li>" + priceHistory[i] + "</li>";
			}

			ul.innerHTML = html;
		}

		$.subscribe(customEvent, update);
	});
	
	/**
	* Creates the image preview panel
	* -every product has an image to update
	* -sometimes that image has a related link "preview" which updates the MAIN IMAGE
	* -there is always a MAIN IMAGE	
	* @constructor
	* @static
	* @name ImagePreview
	*/		
	var ImagePreview = new (function(){
		var mainImage = $("#largeImage")[0] || null;
		var previewImage = $(root).find(".previewImage img")[0] || mainImage;
		var previewLink = $(root).find("h1 a.previewLink")[0] || null;
		var quickLookImage = $(root).find(".quickLookImage img")[0] || null;
		var hiddenImageURL = $(root).find("input[name='replacementMainImageURL']").val() || null;		
		var zoomImageURL = null;
		
		if(!(previewImage || quickLookImage)) return;
		
		if(previewLink) {
			$(previewLink).bind("click", previewLinkClick);
		}

		$.subscribe(customEvent, update);

		function update(e) {
			var data = e.data[0] || null;
			if(!data) return;

			var staticImageURL = data.staticImageURL;			
		
			if(staticImageURL.length===0) return;
			
			var previewImageURL = data.staticImageURL+Salmon.PageContext.IMAGEPARAMXTRASMALL;
			var bigImageURL = data.staticImageURL+Salmon.PageContext.IMAGEPARAMXTRALARGE;
			var mediumImageURL = data.staticImageURL+Salmon.PageContext.IMAGEPARAMMEDIUM;
			var mediumLargeImageURL = data.staticImageURL+Salmon.PageContext.IMAGEPARAMMEDIUMLARGE;			
						
			// if we are updating a small window (product bundle)
			if(previewLink) {
				//zoomImageURL = data.zoomImageURL;
				previewImage.src = mediumImageURL;
				previewImage.alt = data.altImageText;
				previewLink.className = data.imageReference;
				previewLink.href = bigImageURL;
			}
			// if we are updating a quicklook image panel
			else if(quickLookImage && !isStaticImage) {
				zoomImageURL = data.zoomImageURL;
				quickLookImage.src = mediumLargeImageURL;
				quickLookImage.alt = data.altImageText;
			}
			else if($("#productBundleItems").find(".bundleItems").length>0) {
				previewImage.className = data.imageReference;
				previewImage.src = previewImageURL;
				previewImage.alt = data.altImageText;
			}
			else {
				if(!isStaticImage){
					previewImage.className = data.imageReference;
					previewImage.src = bigImageURL;
					previewImage.alt = data.altImageText;
					zoomImageURL = data.zoomImageURL;
					
					largeImageChanged(data);
				}
			}
		}
		
		function largeImageChanged(sku) {
			$.publish(Salmon.UI.CustomEvents.productLargeImageChanged, sku);
		};
		
		//Replace main image with the image ref from that in the preview window
		function previewLinkClick() {
			mainImage.src = this.href;
			mainImage.className = this.className;
			if(SF.ProductZoom.Scene7Player) {
				SF.ProductZoom.Scene7Player.altUpdate();
			}
			return false;
		}	
	});
	
	//Replace main image with the image ref from that in the selected bundle superset colours
	function supersetColourClick() {
		var mainImage = $("#largeImage")[0] || null;
		var newImageName = thisCurrentSuperSwatchImage;
		newImageName = newImageName.replace(/_SW\$/g,"_M\$").replace(/_SW\?/g,"_M\?$PDP_SW_M$")
		var newClassName = newImageName.substring(newImageName.lastIndexOf("/")+1);
		newClassName = newClassName.substring(0,newClassName.lastIndexOf("_M?"));
		mainImage.src = newImageName;
		mainImage.className = newClassName;
		if(SF.ProductZoom.Scene7Player) {
			SF.ProductZoom.Scene7Player.altUpdate();
		}
		return false;
	}	

	/**
	* Updates the hidden form field with the sku
	* @constructor
	* @static
	* @name SkuHandler
	*/	
	var SkuHandler = new (function(){
		var node = form.catEntryId || null;
		if(!node) return;
		
		$.subscribe(customEvent, update);

		function update(e) {
			var data = e.data[0] || null;
			if(!data) return;
			var sku = data.itemSKU;
			if(sku.length===0) return;
			node.value = sku;
		}
	});
	
	
	/**
	* Creates the stock availability panel
	* @constructor
	* @static
	* @name StockAvailability
	*/		
	var StockAvailability = new (function() {
		// console.log('StockAvailability!'); 
	
		var node = $(root).find("p.stockAvailability")[0] || null;
		if(!node) return;
		var span = $(node).find("span")[0] || null;
		if(!span) return;
		$.subscribe(customEvent, update);
					
		//Conditionally run the stock check on load (only if a single item exists for this product)
		if (childItemId) {
			sendRequest(childItemId);
		}
		
		function update(e) {
			removeErrors();
			var data = e.data[0] || null;
			if(!data) return;
			var sku = data.itemSKU;
			if(sku.length===0) return;
			sendRequest(sku);
		};
		
		function sendRequest(sku) {	
			var data = $("#productBundleItems").find("form").serialize() || $(form).serialize();
			data += "&itemId="+sku;
			$.ajax({
				async: async,
				url: "/webapp/wcs/stores/servlet/AjaxStockIndicationView",
				type: "post", 
				dataType: "json",
				success: showStock,
				data: data,
				error: Salmon.UI.AjaxError
			});
		}
		
		function removeErrors() {
			$(form).find("div.errormessage").remove();
			$(form).find(".error").removeClass("error");
		};
		
		function showStock(data) {
			// console.log('showStock'); 
			// console.log(data); 
		
			$.publish(Salmon.UI.CustomEvents.stockAvailabilityChanged+productID, data);
			span.innerHTML = data.stockText;
		}
		
		function addStockLevelHandler(stockLevel) {
			var quantityNode = $("input[name='quantity']", root);

			if(stockLevel > 0 && quantityNode.val() > 1 && quantityNode.val() > stockLevel) {
				displayOutOfStockMessage();
			}
			
			quantityNode.unbind("change").change(function(ev) {
				if(this.value > stockLevel) {
					displayOutOfStockMessage();	
				}
			});
		}
		
		function displayOutOfStockMessage() {
		
		}
	});
	
	/**
	* Updates the description section of PDP, and details and specification sections
	* of overlay with sku specific short, long and aux description
	* @constructor
	* @static
	* @name DescriptionUpdate
	*/		
	var DescriptionUpdate = new (function() {
		var detailsId = "PTP_details_"+productID;
		var detailsDiv = document.getElementById(detailsId);
		if(!detailsDiv) return;
		
		var descriptionText = $("p.description span").get(0);
		
		//We may have either specification, or ingredients, or neither		
		var auxId = "PTP_ingredients_"+productID;
		var auxDiv = document.getElementById(auxId);
		if(!auxDiv) {
			var auxId = "PTP_specification_"+productID;
			var auxDiv = document.getElementById(auxId);
		}
		
		$.subscribe(customEvent, update);
		
		function update(e) {
			var data = e.data[0] || null;
			if(!data) return;

			if (descriptionText) {
				var shortDesc = data.shortDescription;
				if (shortDesc) {
					descriptionText.innerHTML = shortDesc;
				}
			}
			
			var description = data.longDescription;
			if (description) {
				detailsDiv.innerHTML = description;
			}

			//as stated, we may not have a spec or ingredients tab
			if(auxDiv) {
				var aux = data.auxDescription1;
				if(aux) {
					auxDiv.innerHTML = aux;
				}
			}
		};
	});
	
	function getCurrentKey() {
		var val = "P"+productID;
		var attrValue = null;
		
		for(var i = attributeCollection.length-1; i>=0; i--) {
			attrValue = attributeCollection[i].value;
			if(attrValue === null || attrValue === "") continue;
			val += "_"+attributeCollection[i].value;
		}		
		return val;
	};
	
	function getCurrentKeyLessLastOption() {
		var val = "P"+productID;
		var attrValue = null;
		for(var i = attributeCollection.length-1; i>=0; i--) {
			if (i > 0) {
				attrValue = attributeCollection[i].value;
				if(attrValue === null || attrValue === "") continue;
				val += "_"+attributeCollection[i].value;
			}
		}		
		return val;
	};

	function updateVariants(clickedLabel) {
		// console.log('updateVariants!'); 
	
		if(!$(root).hasClass("superset")){
			var currentKey = $.trim(getCurrentKey());

			// console.log(currentKey); 
		
			if(!SF.ProductData.data) {
				return;
			}

			// console.log(SF.ProductData.data); 
		
			var newDetails = SF.ProductData.data[currentKey];	

			if (!newDetails) {
				currentKey = $.trim(getCurrentKeyLessLastOption());
				newDetails = SF.ProductData.data[currentKey];	
			}

			if ($('body#pgProductBundle').length > 0) {
				if (clickedLabel) {
					// on bundles page replace small image	
					var image = $(clickedLabel).parents('div.otherDetails').siblings('div.previewImage').find('img') || null; 

					if (image.length > 0) {
						var colour = $(clickedLabel).parents('fieldset').siblings('p.indicator').html().toString().toUpperCase();
							// remove all non-alphanumeric characters from colour
							colour = colour.replace(/[^a-zA-Z0-9]+/g, ''); 
						var imageSrc = $(image).attr('src').toString(); 
						var imageSrcArray = imageSrc.split('?'); 
						var imageSrcSfx = imageSrcArray.pop(); 
						var imageSrcBaseArray = imageSrcArray[0].split('_'); 
						var imageSrc = imageSrcBaseArray[0] + '_' + colour + '?' + imageSrcSfx; 
						image.attr('src', imageSrc); 
					}
				}
			}

			$.publish(customEvent, newDetails);

			// activate zoom for new image
			if (SF.FlyoutZoom !== undefined) {
				if (SF.FlyoutZoom.Zoom) {
					SF.FlyoutZoom.Zoom.showViewer();
				}
			}
		} else {
			var thisCurrentSwatch = null;
			var tempCollection = $(".bundleItems .productForm");

			tempCollection.each(function(){
				$(this).find("input[value='NONE']").parent().find("label").click();
				var foundMatch = false;
				$(this).find("input[type='radio']").each(function(){
					if($(this).attr("value") == thisCurrentSuperSwatchName){
						foundMatch = true;
						$(this).parent().find("label").click();
						$(this).attr("checked",true); //Defect 129
						supersetColourClick();
					}
				});
				if(!foundMatch){
					$(this).find(".previewImage").find("img").attr("src","/wcsstore/ConsumerDirectStorefrontAssetStore/en_US/Style1/img/blank.gif");
					$(this).find(".stockAvailability").find("span.value").text("Unavailable");
				}
			});

			// the superset was clicked.
			// loop through the normal ones and check the ones that match the colour
			// and make sure that the ones that don't are unchecked.
			// not sure how to set updateVariants on them via a bound .click() when all 
			// i'm doing is removing checked items????
			// rob says I need to as I need to update the stock-availability status & such!
		}
	};
}
