var init = true;
function debug (debugValue) {
	//alert(debugValue);
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

// The SKU item object
function AlternativeImage (name, altText, smallImage, largeImage, hugeImage, featureColour) {

	this.name = name;
	this.altText = altText;
	this.smallImage = smallImage;
	this.largeImage = largeImage;
	this.hugeImage = hugeImage;
	this.featureColour = featureColour;
	
}

AlternativeImage.prototype.getName = function() {return this.name;};
AlternativeImage.prototype.getAltText = function() {return this.altText;};
AlternativeImage.prototype.getLargeImage = function() {return this.largeImage;};
AlternativeImage.prototype.getHugeImage = function() {return this.hugeImage;};
AlternativeImage.prototype.getSmallImage = function() {return this.smallImage;};
AlternativeImage.prototype.getFeatureColour = function() {return this.featureColour;};

function SkuAlternativeImages () {
	this.array = new Array();
}

SkuAlternativeImages.prototype.put = function( alternativeImage ) {
    if( ( typeof alternativeImage != "undefined" ) ) {
        this.array[this.array.length] = alternativeImage;
    }
}

function Price (nowPrice, wasPrice, savingPercentage, savingAmount, showWasPricePercentage, showWasPriceAmount ) {
	this.nowPrice = nowPrice;
	this.wasPrice = wasPrice;
	this.savingAmount = savingAmount;
	this.savingPercentage = savingPercentage;
	this.showWasPricePercentage = showWasPricePercentage;
	this.showWasPriceAmount = showWasPriceAmount;
}

Price.prototype.getNowPrice = function() {return this.nowPrice;};
Price.prototype.getWasPrice = function() {return this.wasPrice;};
Price.prototype.getSavingAmount = function() {return this.savingAmount;};
Price.prototype.getSavingPercentage = function() {return this.savingPercentage;};
Price.prototype.getShowWasPricePercentage = function() {return this.showWasPricePercentage;};
Price.prototype.getShowWasPriceAmount = function() {return this.showWasPriceAmount;};

function SkuSettings (price, alternativeImages) {
	this.alternativeImages = alternativeImages;
	this.price = price;
}

SkuSettings.prototype.getPrice = function() {return this.price;};
SkuSettings.prototype.getAlternativeImages = function() {this.alternativeImages;};

//SkuSettings.prototype.put = function(alternativeImages, prices);

// KeyValue - Defines the keys for our hashmap
function KeyValue( key, value) {
    this.key = key;
    this.value = value;
}

// Map - defines the hash map array
function Map() {
    this.array = new Array();
}

Map.prototype.put = function( key, value ) {
    if( ( typeof key != "undefined" ) && ( typeof value != "undefined" ) ) {
        this.array[this.array.length] = new KeyValue( key, value);
    }
}

Map.prototype.get = function( key ) {

	debug("map.get('" + key + "'");
    for( var k = 0 ; k < this.array.length ; k++ ) {
    	debug("checking specified key[" + key + "] against stored key[" + this.array[k].key + "]");
        if( this.array[k].key == key ) {
	    	debug("found specified key[" + key + "]");
            return this.array[k].value;
        }
    }
    return "";
}

Map.prototype.length = function() {
    return this.array.length;
}

// On initial load we re move the options from the sub-options until user has selected previous option
function initOptions(multipleProducts) {

	var dealingWithRadioButtons = false;

	// reset the diouble click variable
	
	// If this is a page with multiple products then we need to ensure we set all possible dropdowns
	var maxNoOfProducts = 1;
	var maxNoOfOptions = 10;
	var displayPriceLabel  = true;
	if (multipleProducts) {
		maxNoOfProducts = 10;
		displayPriceLabel  = false;
	}

	// Iterate through each product on the page (Assumes max of 10 for say a bundle/quick shop page)
	for (prodIdx = 0; prodIdx < maxNoOfProducts; prodIdx++) {
		var productPrefix = "";
		if (maxNoOfProducts > 1) {
			productPrefix = "p" + prodIdx;
		}

		var lastSelectedId  = "";	
		var lastSelectedElement  = "";	
		var lastSelectedOptionNo = 0;
		
		var previousSelected = false;
		// Iterate through each drop down box and check if it has a selected option
		for (initIdx = 1; initIdx <= maxNoOfOptions; initIdx++) {
			var elementId = productPrefix + "attrValue" + (initIdx);		
			
			if (document.getElementById(elementId)) {
				var definingOption = document.getElementById(elementId);
				if (definingOption != "undefined") {
				
					// We assume we have a set of Select boxes used for the defining attributes
					if (definingOption.type != null && definingOption.type != '') {
						// If the dropdown is selected then we need to ensure it is sorted
						var selIndex = definingOption.selectedIndex;
						var selValue = definingOption.options[selIndex].value;
	
						if (selIndex > 0) {
							previousSelected = true;						
							lastSelectedId = productPrefix;
							lastSelectedElement = definingOption;
							lastSelectedOptionNo = initIdx;
							
							// Ensure the correct option is still selected
						    for (var loop=1; loop<definingOption.options.length; loop++) {
						    	if (selValue === definingOption.options[loop].value) {
						    		definingOption.selectedIndex = loop;
									// Due to how the browser renders this on a refresh, we have encode the values back again
									definingOption.options[loop].value = definingOption.options[loop].value.replace(/&/gi,'&amp;');
						        }
						    }
						} else {
							if (initIdx==1 || previousSelected) {
								// Lets sort the current drop down 
								sortSelect(definingOption, true);
							} else {
								definingOption.length = 1; // We always leave the default option around
								definingOption.disabled="true";				
							}
							previousSelected = false; // This option has not been selected yet so preven tsubsequent options from being enabled
						}						
					}
					// Otherwise we have a set of Radio buttons for the defining attributes
					else {
						dealingWithRadioButtons = true;
					
						var selIndex = 0;
						var selValue = null;
						
						var radioChecked = false;
						
						for (i = 0; i < definingOption.childNodes.length; i++) {
							
							if (definingOption.childNodes[i].childNodes !== null) {
								
								for (j = definingOption.childNodes[i].childNodes.length - 1; j >= 0; j--) {
									
									if (definingOption.childNodes[i].childNodes[j].type == 'radio') {
										var radio = definingOption.childNodes[i].childNodes[j];
										
										if (radio.checked) {
											selIndex = j;
											selValue = radio.value;
											
											radioChecked = true;
										}
										
									}
									
								}
								
							}
		
						}					
					}
				}
			} else {
				//debug ("Reached end of attributes");
				initIdx = maxNoOfOptions + 1;
			}		

		}

		if (dealingWithRadioButtons) {
			// Save the default price details for use later
			var priceElementId = "#priceelementBlock";
			var price = $("#priceelementBlock").html();
			
			defaultPriceDetails.put(priceElementId.toUpperCase(), price);
					
		} else {
			// Save the default price details for use later
			var priceElementId = 'priceelement' + productPrefix;	
			if (document.getElementById(priceElementId)) {
				defaultPriceDetails.put(priceElementId.toUpperCase(), document.getElementById(priceElementId).innerHTML);
			}		
		}
		

		if ( document.getElementById('descriptiveAttributes') ) {
			defaultProductDescriptiveAttributes = document.getElementById('descriptiveAttributes').innerHTML;
		} 

		// Now that we have reselected all required options we need to ensure the correct price is shown using the last selected options
		// but only if a option selected
		if (previousSelected && !dealingWithRadioButtons) {
		    switchSkuSettings(document.OrderItemAddForm, lastSelectedElement, lastSelectedId, lastSelectedOptionNo, true);
		}
		

	}
	
	init = false;
}

function validateSelectedOptions (aForm, multipleProducts) {


	var maxNoOfProducts = 1;
	var maxNoOfOptions = 10;
	if (multipleProducts) {
		maxNoOfProducts = 10;
	}
	
	for (prodIdx = 1; prodIdx <= maxNoOfProducts; prodIdx++) {
		var productPrefix = "";
		if (maxNoOfProducts > 1) {
			productPrefix = "p" + prodIdx;
		}

		// Only validate if the add checkbox is present and set or noty present at all 
		var checkBoxId = productPrefix + "_selected";
		var bValidate=true;
		if (document.getElementById(checkBoxId)) {
			var includeProduct = document.getElementById(checkBoxId);
			if (!includeProduct.checked) {
				bValidate=false;
			}
		}
		
		if (bValidate) {
		for (i = 1; i <= maxNoOfOptions; i++) {
				var elementId = productPrefix + "attrValue" + (i);
				if (document.getElementById(elementId)) {
					var definingOption = document.getElementById(elementId);
					if (definingOption !== "undefined") {
						var selIndex = definingOption.selectedIndex;
						var errorText = definingOption.options[0].text + " " + definingOption.options[0].value;
						if (selIndex <= 0) {
							alert(errorText);
							return false;
						}
					}
				} else {
					i = maxNoOfOptions + 1;
				}		
			}		
		}
	}

	return true;
}

function handleSpecialChars(selValue){
	//handle encoded ampersand followed by eol
	var ampIdx=selValue.search(/\&amp;$/g);
	while(ampIdx>=0){
		selValue=insertString(selValue, ampIdx+5, "amp;");
		ampIdx=selValue.search(/\&amp;$/g);
	}
	//handle encoded ampersand followed by whitespace
	ampIdx=selValue.search(/\&amp;[\s\&]/g);
	while(ampIdx>=0){
		selValue=insertString(selValue, ampIdx+5, "amp;");
		ampIdx=selValue.search(/\&amp;[\s\&]/g);
	}						
	//handle non-ampersand special characters
	ampIdx=selValue.search(/\&[^(amp;)].*/g);
	while(ampIdx>=0){
		selValue=insertString(selValue, ampIdx+1, "amp;");
		ampIdx=selValue.search(/\&[^(amp;)]/g);
	}
	return selValue;
}
	
function insertString(origString, insertPos, insertStr) {
	var firstPart=origString.substring(0, insertPos);
	firstPart=firstPart+insertStr;
	var secondPart=origString.substring(insertPos);
	return firstPart+secondPart;
}
function getRightKeyValue(keyValue,optionNumber){
   if(keyValue=="undefined" || keyValue==null || keyValue ==""){
       return "";
   }
   var testMap = map;
   //if try to retrieve the data for the first option, we should retrieve the data from optionMap
   if(optionNumber == 1){
      testMap = optionValueMap;
   }
   var skuSettingsTmp = testMap.get(keyValue);
   if(skuSettingsTmp != "undefined" && skuSettingsTmp != null && skuSettingsTmp!=""){
       return keyValue;
   }
   var keyValue1 = keyValue.replace(/"/gi,'&#034;');
   keyValue1 = keyValue1.replace(/'/gi,"&#039;");		   
   skuSettingsTmp = testMap.get(keyValue1);
   if(skuSettingsTmp != "undefined" && skuSettingsTmp != null && skuSettingsTmp!=""){       
       return keyValue1;			           			       
   }
   var keyValue2 = handleSpecialChars(keyValue);
   skuSettingsTmp = testMap.get(keyValue2);
   if(skuSettingsTmp != "undefined" && skuSettingsTmp != null && skuSettingsTmp!=""){
       return keyValue2;			           			       
   }
   return keyValue;
}
// Thios function changes the images and prices
// based upon the selected options
function switchSkuSettings( aForm, aField, keyPrefix, optionNumber, displayPriceLabel) {
	//debug ("In switchSkuSettings....");
	
	// We build up a key value based upon all the definining attributes selected
	// TODO We assume max of 10 defining attributes at this stage, need to make this more generic
	var keyValue = "";
	var allOptionsSelected = true;
	var previousOptionSelected = true;
	var firstOptionValue = "";

	// For the current product on the page (support Product Display/ Bundle and Quick Shop so may be more thasn 1 product)
	// Check if all the options are selected and chaneg the price and image for the selected sku as necessary
	// We locate each select field named attrValue for the current product on the page and check if they are all selected
	for (i = 0; i <= 10; i++) {
		var elementId = keyPrefix + "attrValue" + (i+1);
		//debug("checking for element:" + elementId);
		
		if (document.getElementById(elementId)) {
			var definingOption = document.getElementById(elementId);
			if (definingOption !== "undefined") {
				//debug ("found attribute " + elementId);
		
				if (eval((i+1) > optionNumber)) {
					// We have gone past the options that was selected so we need to reset this option
					definingOption.selectedIndex = 0;
				} 
				var selIndex = definingOption.selectedIndex;
				var selValue = definingOption.options[selIndex].value;

				//alert("selectedIndex:" + selIndex + " selValue=" + selValue);			
				if (selIndex <= 0) {
					allOptionsSelected = false;
				} else {
					var selValue = definingOption.options[selIndex].value;
					//var dealedSelValue="";
					// Since the browser will render the values in the drop down by decoded we have to reencode the & character before we look it up
					// We dont reencode if this is called from the initOptions method as the valules will at this point be correct
					if (!init) {
						//alert("init=" + init + " selValue:" + selValue);
						//ampersands need special handling. pad &amp; with another amp;
						//add by Michael Zhou 05/09/08
						//Have no need to do handleSpecialChars(..), because in DynamicProductJavaScriptSetup.jspf
						//The rendered js code just looks like-
						//  map.put("Men&#039;s_Yes", skuSettings);
						//  optionValueMap.put("Men&#039;s", optionValues);
						//there they just use '..&#039;..' as a key. 
						//When did handleSpecialChars(selValue), the key has been changed into '..&amp;#039;..'
						//We must use a consistent key to retrieve the data. I disable the function handleSpecialChars.
					    //add end MZ
					    //need to try more times

						//selValue=handleSpecialChars(selValue);
						//selValue = selValue.replace(/&/gi,'&amp;');
						//dealedSelValue = handleSpecialChars(selValue);
						//alert("selValue:"+selValue +"***dealedSelValue:" +dealedSelValue);
					}
					//alert("selValue=" + selValue);
					//selValue = selValue.replace(/\"/g,'&#034;').replace(/&quot;/gi,'&amp;quot;');
					//selValue = selValue.replace(/\"/g,'&#034;');
					//selValue = selValue.replace(/&amp;/gi,'&amp;amp;');
					//selValue = selValue.replace(/&quot;/gi,'&amp;quot;');
					if (i === 0) {
						firstOptionValue = selValue.rtrim();
					}
					
					if (selValue == "") {
						allOptionsSelected = false;
					} else {
						if (keyValue != "") {
							keyValue = keyValue + "_";
						} else {
							keyValue = keyPrefix;
						}
						keyValue = keyValue + selValue.rtrim();					
						//alert("keyValue=:" + keyValue);
					}
				}
				
                keyValue = getRightKeyValue(keyValue,optionNumber);
                
				// We change the options for the next set of dropdowns if this is the one that has changed
				//debug("About to check " + (i+1) + " > " + optionNumber);
				if (eval((i+1) > optionNumber)) {
					//debug("Lets update the sub options for keyValue:" + keyValue);
					if (previousOptionSelected) {
						var subOptions = optionValueMap.get(keyValue);	
						if (subOptions !== "undefined" && subOptions !== null && subOptions != "") {
							//debug("Found sub options");
							definingOption.disabled="";
							//debug("Settings length to " + (subOptions.length+1));
							definingOption.length = subOptions.length+1;
							for (var subIdx = 0; subIdx < subOptions.length ; subIdx++ ) {
							
								currOptText = subOptions[subIdx];
								// replace &amp; twice to cope with the double escaped, "&amp;amp;" situation...
								// NB. this code does not yet cope with &apos; - may need to be added later.
								//currOptText = currOptText.replace(/&amp;/gi, '&');
								//currOptText = currOptText.replace(/&amp;/gi, '&');
								
								//currOptText = currOptText.replace(/&#034;/gi, '"');								
								//currOptText = currOptText.replace(/&quot;/gi,'"');
								
								definingOption.options[subIdx+1].text = currOptText;
								definingOption.options[subIdx+1].value = subOptions[subIdx]; //.replace(/&amp;/gi,'&');
							}							
							sortSelect(definingOption, true);
						} else {
							definingOption.length = 1;
							definingOption.disabled="true";
						}
					} else {
						definingOption.length = 1;
						definingOption.disabled="true";
					}
					
					// We are resetting this suboption so we cannot have selected all options
					allOptionsSelected = false;
				}
				
				//debug("current selected index =" + selIndex);
				if (selIndex <= 0) {
					previousOptionSelected = false;
				}
			}
		} else {
			//debug ("Reached end of attributes");
			break;
		}		
	}
	
	var priceElementId = 'priceelement' + keyPrefix;
	
	//alert("switchSkuSettings: looking for priceelement:" + priceElementId + " keyPrefix:" + keyPrefix);
	if (allOptionsSelected == true) {
		//alert("tony: switchSkuSettings: Lets find if the images or prices need to be changed using keyValue:" + keyValue);
		var skuSettings = map.get(keyValue);

        if (skuSettings === "undefined" || skuSettings === null || skuSettings === "") {
        		// The key values need to be double escaped here such that & -> &amp;amp; and " -> &amp;quot;
        		// NB. there is no functionality for &apos; yet - this may need to be added later.
                //keyValue = keyValue.replace(/&/g,'&amp;');
                //keyValue = keyValue.replace(/&amp;#034;/gi,'&quot;');
                //keyValue = keyValue.replace(/&/g,'&amp;');

				//alert("switchSkuSettings: Lets find if the images or prices need to be changed using converted keyValue:" + keyValue);
                skuSettings = map.get(keyValue);
        }
        
        //alert("skuSettings:" + skuSettings);
		if (skuSettings !== "undefined" && skuSettings !== null && skuSettings !== "") {
			// default to true if not passed
			if(displayPriceLabel == null) {	
				displayPriceLabel = true; 
			}
			
			// We found the details so let change the price information
			var priceString = "";
			
			var nowLabel = "";
			if (skuSettings.getPrice().getShowWasPricePercentage() === "true" || skuSettings.getPrice().getShowWasPriceAmount() === "true") {
				nowLabel = "Now&nbsp;";
			}
			
			priceString += "<ul><li>";
			// add price label if required
			if(displayPriceLabel) {
				priceString += "<span class='label'>Price&nbsp;" + nowLabel + "</span>";
			} else {
				priceString += "<span class='nowlabel'>" + nowLabel + "</span>";
			}
			
			priceString += "<span class='amount'>" + skuSettings.getPrice().getNowPrice() + "</span>";
	
			if (skuSettings.getPrice().getShowWasPricePercentage() === "true" || skuSettings.getPrice().getShowWasPriceAmount() === "true") {
				priceString += "<span class='price'><span class='waspricelabel'>Was </span><span class='wasprice'>" + skuSettings.getPrice().getWasPrice() + "</span></span>";
				if (skuSettings.getPrice().getShowWasPriceAmount() === "true") {
					priceString += "<span class='price'><span class='saveuptoamountlabel'>Save Up To </span><span class='saveuptoamount'>" + skuSettings.getPrice().getSavingAmount() + "</span></span>";
				}
				if (skuSettings.getPrice().getShowWasPricePercentage() === "true") {
					priceString += "<span class='price'><span class='saveuptopercentlabel'>Save Up To </span><span class='saveuptopercent'>" + skuSettings.getPrice().getSavingPercentage() + "%</span></span>";
				}
			}
			priceString += "</li></ul>";
			
			//alert("About to set priceElementId:" + priceElementId + " to " + priceString);
			document.getElementById(priceElementId).innerHTML=priceString;
		} else {
			document.getElementById(priceElementId).innerHTML="No price available.";
		}
	} else {
		document.getElementById(priceElementId).innerHTML=defaultPriceDetails.get(priceElementId.toUpperCase());
	}
	
	// NOw we change the main image if the first option has been selecetd 
	var mainImageElement = document.getElementById("mainimage");
	if (mainImageElement !== null && mainImageElement !== "undefined") {
        var mainImageLargeLinkElement = document.getElementById("pdlargerimagelink");
        var mainImageLargeImageElement = document.getElementById("pdlargerimage");	
        // For zoom	
        var hugeImageElement = document.getElementById("zoomItemImg")
        if (defaultMainImageSource === "") {
			defaultMainImageSource = mainImageElement.src;
			defaultMainImageAltText = mainImageElement.alt;
			defaultHugeImageSource = hugeImageElement.value;
			//alert(defaultHugeImageSource + "=" + hugeImageElement.value);

			defaultMainImageLargeLinkSource = mainImageLargeLinkElement.href;
/*			startPos = defaultMainImageLargeLinkSource.indexOf("imageName=");
			defaultMainImageLargeLinkSource = defaultMainImageLargeLinkSource.substring(startPos+10, defaultMainImageLargeLinkSource.length);
			endPos = defaultMainImageLargeLinkSource.indexOf("&");
			defaultMainImageLargeLinkSource = defaultMainImageLargeLinkSource.substring(0, endPos);
*/
		}
		currentMainImageLargeLinkSource = mainImageLargeLinkElement.href;
/*		startPos = currentMainImageLargeLinkSource.indexOf("imageName=");
		currentMainImageLargeLinkSource = currentMainImageLargeLinkSource.substring(startPos+10, currentMainImageLargeLinkSource.length);
		endPos = currentMainImageLargeLinkSource.indexOf("&");
		currentMainImageLargeLinkSource = currentMainImageLargeLinkSource.substring(0, endPos);
*/		
		if (firstOptionValue !== "") {
			aSkuImage = skuAlternativeImages.get(firstOptionValue)
           if (aSkuImage !== "undefined" && aSkuImage!== null && aSkuImage !== "") {
                    mainImageElement.src = aSkuImage.getLargeImage();
                    mainImageElement.alt = aSkuImage.getAltText();
                    
                    // For zoom
                    hugeImageElement.src = aSkuImage.getHugeImage();
                    

                    // Set the large image link as well
                    mainImageLargeLinkElement.href = mainImageLargeLinkElement.href.replace(currentMainImageLargeLinkSource, aSkuImage.getHugeImage());
                    mainImageLargeImageElement.href = mainImageLargeImageElement.href.replace(currentMainImageLargeLinkSource, aSkuImage.getHugeImage());

            } else {
                    mainImageElement.src = defaultMainImageSource;
                    mainImageElement.alt = defaultMainImageAltText;
                    mainImageLargeLinkElement.href = mainImageLargeLinkElement.href.replace(currentMainImageLargeLinkSource, defaultMainImageLargeLinkSource);
                    mainImageLargeImageElement.href = mainImageLargeImageElement.href.replace(currentMainImageLargeLinkSource, defaultMainImageLargeLinkSource);
                    hugeImageElement.src = defaultHugeImageSource;
            }

			// Ensure the main image param is set - used to avoid flicker of page when reloading
			document.getElementById("itemImg").value = mainImageElement.src;
			document.getElementById("itemAlt").value = mainImageElement.alt;
			                 
            // For zoom
			document.getElementById("zoomItemImg").value = hugeImageElement.src;

		} else {
			mainImageElement.src = defaultMainImageSource;
			mainImageElement.alt = defaultMainImageAltText;
			
            // For zoom
			hugeImageElement.src = defaultHugeImageSource;
			document.getElementById("zoomItemImg").value = hugeImageElement.src;
			
			// Switch the large image link back to the default
			mainImageLargeLinkElement = mainImageLargeLinkElement.href.replace(currentMainImageLargeLinkSource, defaultMainImageLargeLinkSource);			
			mainImageLargeImageElement.href = mainImageLargeImageElement.href.replace(currentMainImageLargeLinkSource, defaultMainImageLargeLinkSource);
		}
	}
	debug("All options selected = " + allOptionsSelected);
}

// Define page level variables
var skuAlternativeImages = new Map();
var map = new Map();
var optionValueMap = new Map();		
var defaultPriceDetails = new Map();
var defaultMainImageSource = "";
var defaultMainImageAltText = "";
var defaultHugeImageSource = "";
var defaultProductDescriptiveAttributes = "";

// Some generic sort functions for select fields
// sort function - ascending (case-insensitive)
function sortFuncAsc(record1, record2) {
    var value1 = record1.optText.toLowerCase();
    var value2 = record2.optText.toLowerCase();
	if (value1 > value2) return(1);
    if (value1 < value2) return(-1);
    return(0);
}

// Some generic sort functions for select fields
// sort function - ascending (case-insensitive)
function sortFuncNumericAsc(record1, record2) {
    return(record1.optText - record2.optText);
}

// sort function - descending (case-insensitive)
function sortFuncDesc(record1, record2) {
    var value1 = record1.optText.toLowerCase();
    var value2 = record2.optText.toLowerCase();
    if (value1 > value2) return(-1);
    if (value1 < value2) return(1);
    return(0);
}

function sortSelect(selectToSort, ascendingOrder) {
    if (arguments.length == 1) ascendingOrder = true;    // default to ascending sort

    // copy options into an array
    // NB We skip first row as this is always 'Please select...'
    var allNumeric = true;
    var myOptions = [];
    for (var loop=1; loop<selectToSort.options.length; loop++) {
        myOptions[loop-1] = { optText:selectToSort.options[loop].text, optValue:selectToSort.options[loop].value };
        if (allNumeric) {
        	allNumeric = (!isNaN(myOptions[loop-1].optText));
        }
    }

    // sort array
    if (ascendingOrder) {
    	if (allNumeric) {
            myOptions.sort(sortFuncNumericAsc);
    	} else {
	        myOptions.sort(sortFuncAsc);
    	}
    } else {
    	if (allNumeric) {
	        myOptions.sort();
       	} else {
	        myOptions.sort(sortFuncDesc);
       	}
    }

    // copy sorted options from array back to select box
    selectToSort.options.length = 1;
    
//  SCO01/04/000014
//  Unencode "double escaped" HTML character entities in the Option texts such that &amp;quot; -> &quot; 
//  and &amp;amp; -> &amp and place them in the Select object.
    for (var loop=0; loop<myOptions.length; loop++) {
        var optObj = document.createElement('option');
        optObj.value = myOptions[loop].optValue;
        
        var beforeConvert = myOptions[loop].optText;
        //it looks like no need to deal with, the value can not contain &amp;amp; add by Michael Zhou 05/09/08
        var afterConvert = beforeConvert.replace(/&amp;/gi,"&");   	

        optObj.innerHTML = afterConvert;
        selectToSort.appendChild(optObj);	
    }
}



//*******************************************************
// Refresh product details page when colour changes
// Only used for clients that do not load colour
// as a defning option
//*******************************************************
function refreshColour (aForm, aField) {

	// Construct url to refresh to
	var selIndex = aField.selectedIndex;
	var url = aField.options[selIndex].value;

	// Now add other field values so that we dont lose selected options
	var maxNoOfOptions = 10;
	for (i = 1; i <= maxNoOfOptions; i++) {
		// Append ant selected options to the url
		var elementId = "attrValue" + (i);		
		if (document.getElementById(elementId)) {
			var definingOption = document.getElementById(elementId);
			if (definingOption != "undefined") {
				var selIndex = definingOption.selectedIndex;
				if (selIndex > 0) {
					var selValue = definingOption.options[selIndex].value;
					var selName = definingOption.name;
					url += "&" + selName + "=" + selValue;
				}
			}
		}
	}
	
	if (document.getElementById("WC_CachedProductOnlyDisplay_FormInput_quantity_In_OrderItemAddForm_1")) {
		var qty = document.getElementById("WC_CachedProductOnlyDisplay_FormInput_quantity_In_OrderItemAddForm_1");
		url += "&" + qty.name + "=" + qty.value;
	}
	
	// TODO Add the current qty and any other selected options to the request
	window.location.href = url;

}




//********************************************************************************************************
// 

function switchRadioSkuSettings( aForm, aField, keyPrefix, optionNumber, displayPriceLabel) {

	
	var maxOptionsCount = -1;

	// For the current product on the page (support Product Display/ Bundle and Quick Shop so may be more thasn 1 product)
	// Check if all the options are selected and chaneg the price and image for the selected sku as necessary
	// We locate each select field named attrValue for the current product on the page and check if they are all selected
	for (i = 0; i <= 10; i++) {
		var elementId = keyPrefix + "attrValue" + (i+1);
		
//		alert(elementId); 
		
		debug("checking for element:" + elementId);
		
		if (document.getElementById(elementId)) {
			
			maxOptionsCount = i + 1;
			
			var definingOption = document.getElementById(elementId);
			if (definingOption !== "undefined") {
				//debug ("found attribute " + elementId);
				var selIndex = 0;
				var selValue = null;
				
				for (t = 0; t < definingOption.childNodes.length; t++) {
					
					if (definingOption.childNodes[t].childNodes !== null) {
						
						for (r = 0; r < definingOption.childNodes[t].childNodes.length; r++) {
							
							if (definingOption.childNodes[t].childNodes[r].type == 'radio') {
								var radio = definingOption.childNodes[t].childNodes[r];
								
								if (eval((i+1) > optionNumber)) {
									// We have gone past the options that was selected so we need to reset this option
									radio.checked = false;
								} 
								
								if (radio.checked) {
									selIndex = r;
									selValue = radio.value;
								}
							}
							
						}
						
					}

				}

				if (selIndex <= 0) {
					allOptionsSelected = false;
				} else {
					//var selValue = definingOption.options[selIndex].value;
					//var dealedSelValue="";
					// Since the browser will render the values in the drop down by decoded we have to reencode the & character before we look it up
					// We dont reencode if this is called from the initOptions method as the valules will at this point be correct
					if (!init) {
						//alert("init=" + init + " selValue:" + selValue);
						//ampersands need special handling. pad &amp; with another amp;
						//add by Michael Zhou 05/09/08
						//Have no need to do handleSpecialChars(..), because in DynamicProductJavaScriptSetup.jspf
						//The rendered js code just looks like-
						//  map.put("Men&#039;s_Yes", skuSettings);
						//  optionValueMap.put("Men&#039;s", optionValues);
						//there they just use '..&#039;..' as a key. 
						//When did handleSpecialChars(selValue), the key has been changed into '..&amp;#039;..'
						//We must use a consistent key to retrieve the data. I disable the function handleSpecialChars.
					    //add end MZ
					    //need to try more times

						//selValue=handleSpecialChars(selValue);
						//selValue = selValue.replace(/&/gi,'&amp;');
						//dealedSelValue = handleSpecialChars(selValue);
						//alert("selValue:"+selValue +"***dealedSelValue:" +dealedSelValue);
					}
					//alert("selValue=" + selValue);
					//selValue = selValue.replace(/\"/g,'&#034;').replace(/&quot;/gi,'&amp;quot;');
					//selValue = selValue.replace(/\"/g,'&#034;');
					//selValue = selValue.replace(/&amp;/gi,'&amp;amp;');
					//selValue = selValue.replace(/&quot;/gi,'&amp;quot;');
					if (i === 0) {
						firstOptionValue = selValue.rtrim();
					}
					
					if (selValue == "") {
						allOptionsSelected = false;
					} else {
						if (keyValue != "") {
							keyValue = keyValue + "_";
						} else {
							keyValue = keyPrefix;
						}
						keyValue = keyValue + selValue.rtrim();					
						//alert("keyValue=:" + keyValue);
					}
				}

			}
			
		} else {
			//debug ("Reached end of attributes");
			break;
		}		
	}
	
	var priceElementId = 'priceelement' + keyPrefix;
	
	if (defaultPriceDetails.length() < 1) {
		// We must store it as it is the default
		defaultPriceDetails.put(priceElementId.toUpperCase(), document.getElementById(priceElementId).innerHTML);
	}

	if (optionNumber < maxOptionsCount) {
	
		keyValue = "_" + keyValue;

		var skuPriceElement = document.getElementById(priceElementId + keyValue).innerHTML;
		
		if (skuPriceElement != "undefined" && skuPriceElement.innerHTML != "") {
			document.getElementById(priceElementId).innerHTML=document.getElementById(priceElementId + keyValue).innerHTML;
		} else {
			document.getElementById(priceElementId).innerHTML="No price available.";
		}
		
		updateDescriptiveValues(keyValue);
	}

	
	// NOw we change the main image if the first option has been selecetd 
	var mainImageElement = document.getElementById("mainimage");
	if (mainImageElement !== null && mainImageElement !== "undefined") {
        var mainImageLargeLinkElement = document.getElementById("pdlargerimagelink");
        var mainImageLargeImageElement = document.getElementById("pdlargerimage");	
        // For zoom	
        var hugeImageElement = document.getElementById("zoomItemImg")
       /* if (defaultMainImageSource === "") {
			defaultMainImageSource = mainImageElement.src;
			defaultMainImageAltText = mainImageElement.alt;
			defaultHugeImageSource = hugeImageElement.value;
			defaultMainImageLargeLinkSource = mainImageLargeLinkElement.href;
			startPos = defaultMainImageLargeLinkSource.indexOf("imageName=");
			defaultMainImageLargeLinkSource = defaultMainImageLargeLinkSource.substring(startPos+10, defaultMainImageLargeLinkSource.length);
			endPos = defaultMainImageLargeLinkSource.indexOf("&");
			defaultMainImageLargeLinkSource = defaultMainImageLargeLinkSource.substring(0, endPos);

		}*/
		currentMainImageLargeLinkSource = mainImageLargeLinkElement.href;
/*		startPos = currentMainImageLargeLinkSource.indexOf("imageName=");
		currentMainImageLargeLinkSource = currentMainImageLargeLinkSource.substring(startPos+10, currentMainImageLargeLinkSource.length);
		endPos = currentMainImageLargeLinkSource.indexOf("&");
		currentMainImageLargeLinkSource = currentMainImageLargeLinkSource.substring(0, endPos);
*/		
		if (firstOptionValue !== "") {
			aSkuImage = skuAlternativeImages.get(firstOptionValue)
           if (aSkuImage !== "undefined" && aSkuImage!== null && aSkuImage !== "") {
                    mainImageElement.src = aSkuImage.getLargeImage();
                    mainImageElement.alt = aSkuImage.getAltText();
                    
                    // For zoom
                    hugeImageElement.src = aSkuImage.getHugeImage();
                    

                    // Set the large image link as well
                    mainImageLargeLinkElement.href = mainImageLargeLinkElement.href.replace(currentMainImageLargeLinkSource, aSkuImage.getHugeImage());
                    mainImageLargeImageElement.href = mainImageLargeImageElement.href.replace(currentMainImageLargeLinkSource, aSkuImage.getHugeImage());

            } else {
                    mainImageElement.src = defaultMainImageSource;
                    mainImageElement.alt = defaultMainImageAltText;
                    mainImageLargeLinkElement.href = mainImageLargeLinkElement.href.replace(currentMainImageLargeLinkSource, defaultMainImageLargeLinkSource);
                    mainImageLargeImageElement.href = mainImageLargeImageElement.href.replace(currentMainImageLargeLinkSource, defaultMainImageLargeLinkSource);
                    hugeImageElement.src = defaultHugeImageSource;
            }

			// Ensure the main image param is set - used to avoid flicker of page when reloading
			document.getElementById("itemImg").value = mainImageElement.src;
			document.getElementById("itemAlt").value = mainImageElement.alt;
			                 
            // For zoom
			document.getElementById("zoomItemImg").value = hugeImageElement.src;
			
			// Addition for Zoom: swap the jqimg attribute of the main image for the zoom
			$('#mainimage').attr("jqimg", $("#zoomItemImg").val() );
			alert("hereFunc");

		} else {
			mainImageElement.src = defaultMainImageSource;
			mainImageElement.alt = defaultMainImageAltText;
			
            // For zoom
			hugeImageElement.src = defaultHugeImageSource;
			document.getElementById("zoomItemImg").value = hugeImageElement.src;
			
			// Switch the large image link back to the default
			mainImageLargeLinkElement = mainImageLargeLinkElement.href.replace(currentMainImageLargeLinkSource, defaultMainImageLargeLinkSource);			
			mainImageLargeImageElement.href = mainImageLargeImageElement.href.replace(currentMainImageLargeLinkSource, defaultMainImageLargeLinkSource);
		}
	}
	debug("All options selected = " + allOptionsSelected);
}




//********************************************************************************************************
// 

function updateDescriptiveValues(keyValue) {

	var descriptiveAttributesId = 'descriptiveAttributes';
	
	var descriptiveAttributes = document.getElementById(descriptiveAttributesId);
	
	if ( keyValue == null || keyValue == '' ) {
		document.getElementById(descriptiveAttributesId).innerHTML = defaultProductDescriptiveAttributes;
	} else {
		document.getElementById(descriptiveAttributesId).innerHTML = defaultProductDescriptiveAttributes + document.getElementById(descriptiveAttributesId + keyValue).innerHTML;
	}
	
}



//********************************************************************************************************
// 

function validateSelectedRadioOptions (aForm, multipleProducts) {

	if ( $("#addToBasket").hasClass("activeButton") ) {
		// go ahead and submit form
		return true;
	} else if ( $("#addToBasket").hasClass("noStockAvailable") ) {
		// alert
		alert("Sorry, this product is out-of-stock at present");
		return false;
	} else {
		// alert
		alert("Please select a size");
		return false;
	}

}


//*******************************************************
// swap the main image - copied from SAFE switchSkuSettings function

function swapMainImage (thisClickedItem) {
	
	

	var mainImageElement = document.getElementById("mainimage");
	if (mainImageElement !== null && mainImageElement !== "undefined") {
        var mainImageLargeLinkElement = document.getElementById("pdlargerimagelink");
        var mainImageLargeImageElement = document.getElementById("pdlargerimage");	
        // For zoom	
        var hugeImageElement = document.getElementById("zoomItemImg")
        if (defaultMainImageSource === "") {
			defaultMainImageSource = mainImageElement.src;
			defaultMainImageAltText = mainImageElement.alt;
			defaultHugeImageSource = hugeImageElement.value;
			//alert(defaultHugeImageSource + "=" + hugeImageElement.value);

			defaultMainImageLargeLinkSource = mainImageLargeLinkElement.href;
/*			startPos = defaultMainImageLargeLinkSource.indexOf("imageName=");
			defaultMainImageLargeLinkSource = defaultMainImageLargeLinkSource.substring(startPos+10, defaultMainImageLargeLinkSource.length);
			endPos = defaultMainImageLargeLinkSource.indexOf("&");
			defaultMainImageLargeLinkSource = defaultMainImageLargeLinkSource.substring(0, endPos);
*/
		}
		currentMainImageLargeLinkSource = mainImageLargeLinkElement.href;
/*		startPos = currentMainImageLargeLinkSource.indexOf("imageName=");
		currentMainImageLargeLinkSource = currentMainImageLargeLinkSource.substring(startPos+10, currentMainImageLargeLinkSource.length);
		endPos = currentMainImageLargeLinkSource.indexOf("&");
		currentMainImageLargeLinkSource = currentMainImageLargeLinkSource.substring(0, endPos);
*/		
		var firstOptionValue = thisClickedItem;
		
		

		if (firstOptionValue !== "") {
			aSkuImage = skuAlternativeImages.get(firstOptionValue)
           if (aSkuImage !== "undefined" && aSkuImage!== null && aSkuImage !== "") {
                    mainImageElement.src = aSkuImage.getLargeImage();
                    mainImageElement.alt = aSkuImage.getAltText();
                    
                    // For zoom
                    hugeImageElement.src = aSkuImage.getHugeImage();
                    
                    // Set the large image link as well
                    mainImageLargeLinkElement.href = mainImageLargeLinkElement.href.replace(currentMainImageLargeLinkSource, aSkuImage.getHugeImage());
                    mainImageLargeImageElement.href = mainImageLargeImageElement.href.replace(currentMainImageLargeLinkSource, aSkuImage.getHugeImage());

            } else {
                    mainImageElement.src = defaultMainImageSource;
                    mainImageElement.alt = defaultMainImageAltText;
                    mainImageLargeLinkElement.href = mainImageLargeLinkElement.href.replace(currentMainImageLargeLinkSource, defaultMainImageLargeLinkSource);
                    mainImageLargeImageElement.href = mainImageLargeImageElement.href.replace(currentMainImageLargeLinkSource, defaultMainImageLargeLinkSource);
                    hugeImageElement.src = defaultHugeImageSource;
            }

			// Ensure the main image param is set - used to avoid flicker of page when reloading
			document.getElementById("itemImg").value = mainImageElement.src;
			document.getElementById("itemAlt").value = mainImageElement.alt;
			                 
            // For zoom
			document.getElementById("zoomItemImg").value = hugeImageElement.src;
			
			// Addition for Zoom: swap the jqimg attribute of the main image for the zoom
			// SF 09.10.09 $('#mainimage').attr("jqimg", $("#zoomItemImg").val() );
			
			//Show hide alternatives as applicable.  Current CBS rule is that we only show alternatives
	        //if the selected colour is the feature colour.
	        var altView = document.getElementById("alternateView");
	
			//GS 19/11/09 - Need to ensure that altView is not null as otherwise a JS error occurs which causes the 
			//setting of the JQZoom image not to take effect and thus you are left zooming the first images huge image.
			if (altView != null) {
		        if (aSkuImage.getFeatureColour() !== "undefined" &&  aSkuImage.getFeatureColour() != null && aSkuImage.getFeatureColour() == 'true') {
					altView.style.visibility = 'visible';
				} 
				else {
					altView.style.visibility = 'hidden';	
				}				
			}
	
		} else {
			mainImageElement.src = defaultMainImageSource;
			mainImageElement.alt = defaultMainImageAltText;
			
            // For zoom
			hugeImageElement.src = defaultHugeImageSource;
			document.getElementById("zoomItemImg").value = hugeImageElement.src;
			
			// Switch the large image link back to the default
			// SF 09.10.09 mainImageLargeLinkElement = mainImageLargeLinkElement.href.replace(currentMainImageLargeLinkSource, defaultMainImageLargeLinkSource);			
			// SF 09.10.09 mainImageLargeImageElement.href = mainImageLargeImageElement.href.replace(currentMainImageLargeLinkSource, defaultMainImageLargeLinkSource);
			
				
			
		}
	}

}



//*******************************************************
// price updater - looks for skuSettings map array to get the latest prices

function updatePriceBlock (thisItem) {

	var skuSettings = map.get(thisItem);

	// if the skuSettings map is available in the source, then update the prices
	if (skuSettings !== "undefined" && skuSettings !== null && skuSettings !== "") {

		// setup the price string
		var priceString = "";
		priceString += "<ul><li>";
		
		// Output the latest price
		priceString += "<span class='amount amountSimple'>" + skuSettings.getPrice().getNowPrice() + " </span> ";

		//if the WAS price is available, then add it to priceString
		if (skuSettings.getPrice().getShowWasPricePercentage() === "true" || skuSettings.getPrice().getShowWasPriceAmount() === "true") {

			// was price
			priceString = "<ul><li><span class='wasprice label'></span> <span class='wasprice'>" + skuSettings.getPrice().getWasPrice() + "</span> ";

			//re-write the price string with a different class for discounted now price
			priceString += "<span class='discountedamount amountSimple'>" + skuSettings.getPrice().getNowPrice() + " </span> ";

			// save percent price
			if (skuSettings.getPrice().getShowWasPricePercentage() === "true") {
				priceString += "<span class='saveuptopercent label'>Save</span> <span class='saveuptopercent'>" + skuSettings.getPrice().getSavingPercentage() + "%</span> ";
			}
			// save amount price
			if (skuSettings.getPrice().getShowWasPriceAmount() === "true") {
				priceString += "<span class='saveuptoamount label'>Save</span> <span class='saveuptoamount'>" + skuSettings.getPrice().getSavingAmount() + "</span> ";
			}
		}
		priceString += "</li></ul>";

	
		//set #priceElementBlock in .detailsdisplay with contents of priceString
		$("#priceelementBlock").html(priceString);
		
	} else {
		$("#priceelementBlock").html("<strong>No price available</strong>");
	}

}

function loadPopupBasket() {

  // move the basket from where it was rendered to a better spot on the page

  var floatingBagBG = $('#floatingShoppingBagBackground');
  floatingBagBG.appendTo('#prodDetailsPageBody');
  $('#floatingShoppingBagBackground').show();

  var floatingBag = $('#floatingShoppingBag');
  floatingBag.appendTo('#prodDetailsPageBody');
  $('#floatingShoppingBag').show('slow');

  $('#keepShoppingButtonLink').click(
     function() {
  	   $('#floatingShoppingBagBackground').hide('slow');
  	   $('#floatingShoppingBag').hide('slow');
     }
   );
   
  $('#floatingShoppingBagBackground').click(
     function() {
  	   $('#floatingShoppingBagBackground').hide('slow');
  	   $('#floatingShoppingBag').hide('slow');
     }
   );
   
//  pageTracker._setCustomVar(1, "Wave-1", "Variation-1", 2);
//  pageTracker._trackEvent("Experiment","Add To Cart");
  
}

//*****************************************************************************************
// initiate jquery code

$(document).ready(function(){





/* SF: Partial re-write of PDP image functions for CBS - we'll need to completely refactor 
the whole lot of this file soon though as there's js and jquery interfering with each other 
and causing many problems */


	  if ($('#mainimage').length != 0) {

	 		var originalMainImage = $('#mainimage').attr('src');
			originalMainImage = originalMainImage.replace('LL','XL');
			$('#pdlargerimage').attr('href',originalMainImage);
			$('#pdlargerimagelink').attr('href',originalMainImage);
	
			// Start hide/show alternate view section when no alternates available
	        $('#attrValue1 .nonDefault').click(      
				function() {
					$('.imagedisplay #alternateView').hide()
				}
			);
	        $('#attrValue1 .default').click(      
				function() {
					$('.imagedisplay #alternateView').show()
				}
			);
	  }
		
		// End hide/show alternate view section when no alternates available
		
		
		//$('#alternateView ul li a img').click(      
			//function() {
				//$('#mainimage').attr('href','')
			//}
		//);
		
	//$('#mainimage').attr("jqimg", $("#zoomItemImg").val() );
	//$('#pdlargerimage').attr(href);
		
		
    // Loop over each alternate img
    //$( '#alternateView ul li a img' ).each(
	    //function( intIndex ){
		    //$( this ).bind (
		    //"click",
		   // function(){
		    //var ThumbImgHref = $('#alternateView ul li a').attr('href');
		    //var ThumbImgSrc = $('#alternateView ul li a img').attr('src');
		    //alert('href= ' + ThumbImgHref + ' src= ' + ThumbImgSrc);
		    //}
		  //); 
	   //} 
   // );
		









	//*******************************************************
	// setup the zoom
	$(".jqzoom").jqueryzoom();


	//*******************************************************
	// colour selector
	

	//**** Start SF added for CBS test *********
	
	
	var numberColours = $('#attrValue1 > li.checked').size();
  	if (numberColours <= 1) {
	  $('span.selectTitleColour').hide();
   	}
	
	var numberSizes = $('#attrValue2 > li.inStock').size();
  	if (numberSizes <= 1) {
  		$('#attrValue2 li.inStock input').attr('checked', true);
	 	$('span.selectTitleSize').hide();
		$("#addToBasket").addClass("activeButton");
   	}
   	
   	// If product has no stock, make button inactive and alert 'No stock'
  	if ($('#attrValue2 li.inStock').length==0) {
  		$("#addToBasket").removeClass("activeButton");
  		$("#addToBasket").addClass("noStockAvailable");
   	}
   	
	//**** End SF added for CBS test *********

	// setup the colour swatch when the page loads
	$("#attrValue1 li").each(function (i) {
		if ( $(this).hasClass("checked") ) {
			// highlight the default colour
			// OLD var thisValue1 = $(this).children("label").children("span").text().replace(/ /g,'');
			var thisValue1 = $(this).children("label").children("span").text();
			$("#selectedValue1").html(thisValue1);
			
			//The reason this regex replace happens is because these chars are not valid in class names and will have been stripped when the page was rendered.
			//Also need to de-reference the period (.) and quote(') as the CSS spec requires it and the hasClass call below will fail if the class name has a . or ' in it and we
			//don't de-reference it.
			thisValue1 = thisValue1.replace(/[()/ ]/g,'');
			thisValue1 = thisValue1.replace(/\./g,'\\\.');
			thisValue1 = thisValue1.replace(/\'/g,'\\\'');
			var myColourBg = $(this).children("label").attr("style");
			$(this).children("label").attr("style", myColourBg.replace(/.gif/g,'_over.gif'));

			$("#attrValue2 li").each(function (i) {
				if ( $(this).hasClass(thisValue1)) {
					$(this).show();
				}
			});
		}
	});
	
	$('#attrValue1 label').mouseover(function() {
		$(this).parent().addClass("hover");

		// change the colour swatch to ON as long as it isnt already checked
		if (!$(this).parent().hasClass("checked")) {
			var myColourBg = $(this).attr("style");
			$(this).attr("style", myColourBg.replace(/.gif/g,'-on.gif'));
		}

		$("#selectedValue1").html($(this).children("span").text());
		
		// Update the price to the Product level price as no SKU is now selected		
		var priceString = defaultPriceDetails.get("#priceelementBlock".toUpperCase());
		//set #priceElementBlock in .detailsdisplay with contents of priceString
		// SRF $("#priceelementBlock").html(priceString);
	});

	$('#attrValue1 label').mouseout(function() {
		$('#attrValue1 label').parent().removeClass("hover");

		// change the colour swatch to OFF as long as it isnt checked
		if (!$(this).parent().hasClass("checked")) {
			var myColourBg = $(this).attr("style");
			$(this).attr("style", myColourBg.replace(/-on.gif/g,'.gif'));
		}

		$("#selectedValue1").html("");
		$("#selectedValue1").html($("#attrValue1 li.checked label").children("span").text());

		// update the price again with the selected size (if there was one selected)
		$("#attrValue2 li").each(function (i) {
			if ( $(this).hasClass("checked")) {
				updatePriceBlock($(this).children("label").attr("for"));
			}
		});
			
	});
	
	

	
	
	

	$('#attrValue1 label').click(function() {
	
		// if this label's parent li isnt already
		if (!$(this).parent().hasClass("checked")) {
			
			// change the colour swatch to OFF for all swatches
			$("#attrValue1 li label").each(function (i) {
				var myColourBg = $(this).attr("style");
				$(this).attr("style", myColourBg.replace(/-on.gif/g,'.gif'));
			});
			
			// change this clicked colour swatch to ON
			var myColourBg = $(this).attr("style");
			$(this).attr("style", myColourBg.replace(/.gif/g,'-on.gif'));
		}

		// add a 'checked' class to the clicked li element
		$('#attrValue1 label').parent().removeClass("checked");
		$(this).parent().addClass("checked");

		// now get the value of the selected colour button and show those sizes
		$("#addToBasket").removeClass("activeButton");

		//The reason thsi regex replace happens is because these chars are not valid in class names and will have been stripped when the page was rendered.
		//Also need to de-reference the period (.) as the CSS spec requires it and the hasClass call below will fail if the class name has a . in it and we
		//don't de-reference it.
		var thisValue2 = $(this).children("span").text().replace(/[()/ ]/g,'');
			thisValue2 = thisValue2.replace(/\./g,'\\\.');
		$("#attrValue2 li").hide();
		$("#attrValue2 li").each(function (i) {
			// clear any previously selected sizes
			//$(this).removeClass("checked");
			//$(this).children("input").attr("checked", false); 
			// show those sizes of this colour
			if ( $(this).hasClass(thisValue2)) {
				$(this).show();
			}
		});
		

		// Update the price to the Product level price as no SKU is now selected		
		var priceString = defaultPriceDetails.get("#priceelementBlock".toUpperCase());
		//set #priceElementBlock in .detailsdisplay with contents of priceString
		// SRF $("#priceelementBlock").html(priceString);

		//*******************************************************
		// update the item level descriptive attributes
		var thisAttributeDesc = "#descriptiveAttributes_" + thisValue2;
		// SF $("#descriptiveItemAttributes").html( $(thisAttributeDesc).html() );
		


		//*******************************************************
		// swap the main image
		swapMainImage(thisValue2);
		
		
		// Make zoom image match non-default colour
		var newColourMainImageSrc = $('#mainimage').attr("src");
		newColourMainImageSrc = newColourMainImageSrc.replace('LL','XL');
		$('#mainimage').attr("jqimg",newColourMainImageSrc);
		
		
		
	});


	//*******************************************************
	// size selector + price updater

	$('#attrValue2 label').mouseover(function() {
		if ( $(this).parent().hasClass('inStock')) {
			$(this).parent().addClass("hover");
			// SRF $("#selectedValue2").html($(this).children("span").text());
		}
	});
	
	$('#attrValue2 label').mouseout(function() {
		$('#attrValue2 label').parent().removeClass("hover");
		$("#selectedValue2").html("");
		$("#selectedValue2").html($("#attrValue2 li.checked label").children("span").text());		
	});
	
	$('#attrValue2 label').click(function() {
		if ( $(this).parent().hasClass('inStock') && $(this).parent().hasClass('hover') ) {
			$('#attrValue2 label').parent().removeClass("checked");
			$(this).parent().addClass("checked");
			$("#addToBasket").addClass("activeButton");
		}
		
		updatePriceBlock($(this).attr("for"));

		
	});

});


