/**************************************************************************************************************************
     Author              :      PA
     Version             :      1.0
     Date Created        :         
	   
     Change history      :
	
     Task/Bug                  Date(mm-dd-yyyy)         Author          Change Description
	
     Trac 1099                 20-06-2008               PSahu           To display backorder status & date for items with one size option.
	 
     Trac 1036                 08-21-2008               SGopidinne      Modified to change method name while adding an item to wishlist.
	  	 
     Trac 1179                 09-27-2008               Hgolla          Modified code as per anthro redesign.
	 
     Trac 1179                 10-08-2008               SNaina          Code modified as per Anthro Redesign 2008, product detail family view page.
     
     Remove javascript
     links on category
     pages(Task 79).           12-16-2008               HAlagesan       Code Modified to add a new cndition in "setSelectedColor" function.
	 
     Trac 1380                 03-11-2009               PSahu           Removed navId parameter after new navigation redesign. 	
	 
     Anthro Bazzar Voice 2009  03-16-2009               PVeedu          Modified page for Anthro Bazzar Voice 2009. 
	 
     Move functions to 
     js files                  08-10-2009               HAlagesan       New function changeImageColor() added.
     
         
    Wrong left nav and breadcrumb 
    are displayed for the 
    following scenario        08-13-2009                HAlagesan      isProduct = true and catId parameters added to setSelectedColor() function.
    
    Trac 1680                 09-02-2009                HAlagesan      sortSizeTypes function is modifed to form a array with size types in required order.
    
    Wrong size type displayed 
    in product detail page    09-24-2009                HAlagesan      initialSizeTypeArray value changed as per the requirement.
    
    Trac 2197                 04-16-2010                SGopidinne     setSelectedSizeForShopBySize() function modified.
    
    In product detail page, 
    out of stock SKU (size) 
    value is in selected 
    state                     04-26-2010                BTellajeera    When user comes from the category page which is sorted by Shop By Size drop down size option,
                                                                       setSelectedSizeForShopBySize() method has been modified to set the selected size if that SKU(size) is not Out Of Stock.
    
    Trac 1974                 06-08-2010                Rpark	     	for familymod template, updated functions setSelectedColor(), familyModWashLabelPopulate(), familyModQtyPopulate(), familyModSizePopulate()
    
    Trac 2391                 08-20-2010                HGolla         Removed unused colorName parameter.
***************************************************************************************************************************/
//Array which holds the product ids mapped to the ProductSelector objects. 
var productSelectorArray = new Array();

//Category array. It contains three maps: top, bottom, accessory. 
//Each entry contains a map linking product id to current scene7 image url
var productImageArray = new Array();
//Tops
productImageArray[0] = new Object();
//Bottoms
productImageArray[1] = new Object();
//Accessories
productImageArray[2] = new Object();

//Array to track selected product's colorcode
var productColorCodeArray=new Array();
productColorCodeArray[0]="";
productColorCodeArray[1]="";
productColorCodeArray[2]="";
//Array to track selected product
//@todo: Change the code to use OutfittingInfo bean instead of the array, as this array is reduntant 
var productIdArray=new Array();
productIdArray[0]="";
productIdArray[1]="";
productIdArray[2]="";


function getValueFromProductColorArray(index, prodid)
{
	return productImageArray[index][prodid];
}

function setValueToProductColorArray(index, prodid, URL)
{
	productImageArray[index][prodid]=URL;
}


	//Called upon clicking on scene7 image
	//The function redirects the user to produt details page
	//Or to the allurent popup 
	//productindex -- Outfitting subcategory index 0 top, 1 bottom, 2 accessory
	function getLinkURL(productindex) { 
		 baseUrl = "/anthro/catalog/productdetail.jsp?_dyncharset=ISO-8859-1&navAction=jump&id="; 
		 productId = productIdArray[productindex];
		 if ( arc.enabled ) 
		 {
			//The call bellow has to include product color
			//The implemintation is pending Allurent's bug fix
			arcDetailsLaunch( productId) ; 
		 } 
		 else 
		 {
			mixmatchFormObject = document.getElementsByName("mixMatchForm")[0];
			var tmpColorCode = productColorCodeArray[productindex];
			var tmpRedirectURL;			
			if((tmpColorCode!=null)&&(tmpColorCode!=""))
			{
				//document.location.href =  baseUrl + productId + "&color=" + tmpColorCode; 			
				tmpRedirectURL =  baseUrl + productId + "&color=" + tmpColorCode; 			
			}
			else
			{
				//document.location.href =  baseUrl + productId; 			
				tmpRedirectURL =  baseUrl + productId; 			
			}
			updateBuyThisOutfitValue(false); 
			updateOutfitCategorySuccessURL(tmpRedirectURL);
			mixmatchFormObject.submit();
			
		 } 
	} 



/*
	Displays a swatch div related to currently clicked product
	index -- category index (0 top, 1 bottom, 2 accessory)
	prodId -- product id
	pColorCode -- color code
*/
function displaySwatches(index, prodId)
{
	//Hide all seatches for all products in the given subcategory
	var parentDiv = document.getElementById("swatchdiv_" + index);
	var allSubDivs = parentDiv.getElementsByTagName("div");
	for(var ii=0;ii<allSubDivs.length;ii++)
	{
		var currentDivId = allSubDivs[ii].id;
		if(currentDivId.indexOf("swatchProductSelector_")!=-1)
		{
			allSubDivs[ii].style.display="none";
		}
	}
	//Show the appropriate swatch div
	document.getElementsByName("swatchProductSelector_" + prodId)[0].style.display="block";	
}

//Select/unselect uppropriate product images
/*
	index -- category index (0 top, 1 bottom, 2 accessory)
	prodId -- id if the product which image needs to be selected
*/
function handleProductImages(index, prodId)
{
	//Get the sliding selector div for the given subcategory
	subNuvObj = document.getElementById("subnav" + index);
	//Get all the images in the div
	allImages = subNuvObj.getElementsByTagName("img");
	//Cinstract the image id for the selected product
	tmpImageName = "img" + prodId;
	//Iterate through all images
	for(var ii=0;ii<allImages.length;ii++)
	{
		var tmpImage = allImages[ii];
		if(tmpImage.id!=tmpImageName)
		{
			//Hide images for unselected products			
			Element.removeClassName(tmpImage.id, "select");
			Element.addClassName(tmpImage.id, ""); //modified for trac 1179
		}
		else
		{
			//Display the image for the selected product
			Element.removeClassName(tmpImage.id, "");//modified for trac 1179
			Element.addClassName(tmpImage.id, "select");
		}
	}

}

/*
 * This class is used for sku selector functionality of multiple products.
 * The skuselector.js is used for skuselector functionality of single products.
 * This class acts as a wrapper class for skuselector.js and extends the skuselector
 * functionality for multiple products.  
 */
function ProductSelector(pProductId, isLeaderProduct){
	this.productId = pProductId;	
	this.skuSelector = new SkuSelector();
	this.skuList = new Array();
	this.sizeList = new Array();
	this.colorList = new Array();
	this.isLeaderProduct = isLeaderProduct;
	
	//Adds the given sku to the skuList Array
	this.addSku = function(pSku){
		this.skuList.push(pSku);
		this.addColor(pSku.colorCode, pSku.colorName);
	}
	
	//Adds the given size to the sizeList Array
	this.addSize = function(pSize){
		this.sizeList.push(pSize);
	}
	
	/*
	 *Adds the given colorcode, colorname combination 
	 * to the array if the color code does not exist in the colorlist already.
	 */	
	this.addColor = function(pColorCode, pColorName){
		if(!this.containsColorCode(pColorCode)){
			this.colorList.push(new Color(pColorCode, pColorName));
		}
	}
	
	/*
	 * Checks if the given color code exists in the color list.
	 * Returns true if the given color code exists in the 
	 * color list, otherwise returns false.
	 */
	this.containsColorCode = function(pColorCode){
		for (var i = 0; i < this.colorList.length; i++) {
			if(this.colorList[i].colorCode == pColorCode){
				return true;
			}
		}
		return false;
	}
	
	//Returns the color name of the given color code
	this.getColorName = function(pColorCode){
		if(pColorCode != null){
			for (var i = 0; i < this.colorList.length; i++) {
				if(this.colorList[i].colorCode == pColorCode){
					return this.colorList[i].colorName;
				}
			}
		}	
		return null;
	}
	
	this.initialize = function(){
		this.skuSelector.initialize(this.skuList, this.sizeList, "");	
	}	
	
	
	//Sets the given color as the currently selected color
	this.setSelectedColorCode = function(pSelectedColor) {
		if(isEmpty(pSelectedColor)){
		this.skuSelector.mSelectedColorCode =this.skuSelector.mAvailableColorCodes[0];
		this.skuSelector.initializeAvailableSizes(this.skuSelector.mSelectedColorCode, this.skuSelector.mSelectedSizeType);
		this.skuSelector.initializeDefaultSelectedSize();
		}
		else{
		this.skuSelector.mSelectedColorCode = pSelectedColor;
		this.skuSelector.initializeAvailableSizes(this.skuSelector.mSelectedColorCode, this.skuSelector.mSelectedSizeType);
		this.skuSelector.initializeDefaultSelectedSize();		
		}
	}
	
	//Sets the given size type as the currently selected size type 
	this.setSelectedSizeType = function(pSelectedSizeType) {
		this.skuSelector.mSelectedSizeType = pSelectedSizeType;
		this.skuSelector.initializeAvailableColors(this.skuSelector.mSelectedSizeType);
		this.skuSelector.initializeDefaultSelectedColor();
		this.skuSelector.initializeAvailableSizes(this.skuSelector.mSelectedColorCode, this.skuSelector.mSelectedSizeType);
		this.skuSelector.initializeDefaultSelectedSize();
		
	}

	//Sets the given size name as the currently selected size name
	this.setSelectedSizeName = function(pSelectedSizeName) {
		this.skuSelector.mSelectedSizeName = pSelectedSizeName;
		
	}
	
	//Repopulates the size types and highlights the currently selected size type
	this.repopulateSizeTypes = function(){		
			for(var i=0;i<this.skuSelector.mAvailableSizeTypes.length;i++){
				
				if(this.skuSelector.mAvailableSizeTypes[i] != ""){
					if(this.skuSelector.mAvailableSizeTypes[i] == this.skuSelector.mSelectedSizeType){	
						if(getElement("sizetype"+this.productId+this.skuSelector.mAvailableSizeTypes[i])!=null){			
							getElement("sizetype"+this.productId+this.skuSelector.mAvailableSizeTypes[i]).className="active";
						}	

					} else {
						if(getElement("sizetype"+this.productId+this.skuSelector.mAvailableSizeTypes[i])!=null){
							getElement("sizetype"+this.productId+this.skuSelector.mAvailableSizeTypes[i]).className="";
						}	
					}
				}	
			}
	}
	
	
	//Repopulates the sizes  and highlights the currently selected size
	this.repopulateSizes = function(isLeaderProduct){	
		var modifiedProductId = this.productId;
		if(isLeaderProduct!=null & isLeaderProduct=="true"){
			modifiedProductId = "l"+this.productId;
		}
		for(var i=0;i<this.skuSelector.mAllSizes.length;i++){			
			var currentSku = this.skuSelector.getSku(this.skuSelector.mAllSizes[i]);
			if(getElement("size"+modifiedProductId+this.skuSelector.mAllSizes[i]) != null){
				if(this.skuSelector.isAvailableSize(this.skuSelector.mAllSizes[i]) && currentSku != null){	
					if(this.skuSelector.mAllSizes[i] == this.skuSelector.mSelectedSizeName){
					//code added for Trac 1099.To display the back order status & date if a product is having only one size.						
						if(currentSku.availabilityStatus == this.skuSelector.AVAILABILITY_STATUS_IN_STOCK){							
						     getElement("size"+modifiedProductId+this.skuSelector.mAllSizes[i]).innerHTML = "<a class=\"sizeButton selected\" href=\"javascript:setSelectedSize(\'"+this.productId+"\',\'"+replaceAll(this.skuSelector.mAllSizes[i])+"\',\'"+isLeaderProduct+"\')\">"+this.skuSelector.mAllSizes[i]+"</a>"; 						
					    }else if(currentSku.availabilityStatus == this.skuSelector.AVAILABILITY_STATUS_BACKORDERABLE){								
						     getElement("size"+modifiedProductId+this.skuSelector.mAllSizes[i]).innerHTML = "<a class=\"sizeButton selected sizeButton backorderableSizeButton\" onmouseout=\"hideddrivetip()\" onmouseover=\"ddrivetip('available <div id=\\'availdate\\'>"+currentSku.availabilityDate+"</div>','#FFFFFF','#c7c7c7')\" href=\"javascript:setSelectedSize(\'"+this.productId+"\',\'"+replaceAll(this.skuSelector.mAllSizes[i])+"\',\'"+isLeaderProduct+"\')\">"+this.skuSelector.mAllSizes[i]+"</a>";					
					    }
				   //end of code added for Trac 1099.
					} else if(currentSku.availabilityStatus == this.skuSelector.AVAILABILITY_STATUS_BACKORDERABLE){				
						getElement("size"+modifiedProductId+this.skuSelector.mAllSizes[i]).innerHTML = "<a class=\"sizeButton backorderableSizeButton\" onmouseout=\"hideddrivetip()\" onmouseover=\"ddrivetip('available <div id=\\'availdate\\'>"+currentSku.availabilityDate+"</div>','#FFFFFF','#c7c7c7')\" href=\"javascript:setSelectedSize(\'"+this.productId+"\',\'"+replaceAll(this.skuSelector.mAllSizes[i])+"\',\'"+isLeaderProduct+"\')\">"+this.skuSelector.mAllSizes[i]+"</a>";									
					}
					else if(currentSku.availabilityStatus == this.skuSelector.AVAILABILITY_STATUS_DISCONTINUED || currentSku.availabilityStatus == this.skuSelector.AVAILABILITY_STATUS_OUT_OF_STOCK){				
						getElement("size"+modifiedProductId+this.skuSelector.mAllSizes[i]).innerHTML = "<span onmouseout=\"hideddrivetip()\" onmouseover=\"ddrivetip('sold out','#FFFFFF','#c7c7c7')\" class=\"\">"+this.skuSelector.mAllSizes[i]+"</span>";
					}
					 else {	
						getElement("size"+modifiedProductId+this.skuSelector.mAllSizes[i]).innerHTML = "<a class=\"sizeButton availableSizeButton\" href=\"javascript:setSelectedSize(\'"+this.productId+"\',\'"+replaceAll(this.skuSelector.mAllSizes[i])+"\',\'"+isLeaderProduct+"\')\">"+this.skuSelector.mAllSizes[i]+"</a>";
					}				
				} 
				else{
					getElement("size"+modifiedProductId+this.skuSelector.mAllSizes[i]).innerHTML="";
				}
			}							
		}
	}

// This function replaces all instances of a string with a given string.

function replaceAll(oldStr) {

  var findStr="'";
  var repStr="\\'";

  var srchNdx = 0;  
  var newStr = "";  
  while (oldStr.indexOf(findStr,srchNdx) != -1)  
                    
  {
    newStr += oldStr.substring(srchNdx,oldStr.indexOf(findStr,srchNdx));
                    
    newStr += repStr;
                    
    srchNdx = (oldStr.indexOf(findStr,srchNdx) + findStr.length);
                    
  }
  newStr += oldStr.substring(srchNdx,oldStr.length);
                    
  return newStr;
}

	/*
	 * Wrapper function to repopulate size types, sizes.
	 * Repopulating the size types will take care of showing the selected size type as
	 * highlighted
	 * Repopulating the sizes will take care of displaying the sizes according to their availability status.
	 * Showing the selected color as highlighted is implemented as a seperate script named colorswatches.js
	 * Displays the selected color, selected size in the page
	 * Sets the value of CartFormModifierFormHandler.catalogRefIds value to the selected sku id.
	 * Sets the name of the quantity field to the selected sku id.
	 */
	this.repopulateAll = function(isLeaderProduct){
		var modifiedProductId = this.productId;
		if(isLeaderProduct!=null & isLeaderProduct=="true"){
			modifiedProductId = "l"+this.productId;
		}
		//Repopulates the size types.
		this.repopulateSizeTypes();
		
		//Repopulates the sizes
		this.repopulateSizes(isLeaderProduct);
		var colorName = this.getColorName(this.skuSelector.mSelectedColorCode);
		if(colorName != null){
		//If there is selected color, displays the selected color in the page.
			if(getElement(modifiedProductId+"selectedColor") != null){		
				getElement(modifiedProductId+"selectedColor").innerHTML=colorName.toUpperCase();				
			}			
			// code is added for trac 1179 at 10-08-2008 
			if(getElement(modifiedProductId+"selectedColorMoreInfo") != null){				
				getElement(modifiedProductId+"selectedColorMoreInfo").innerHTML=colorName.toUpperCase();				
			}
			// End of code is added for trac 1179 at 10-08-2008 
			
			if(getElement(this.productId+"selColor") != null){
				getElement(this.productId+"selColor").innerHTML=colorName.toUpperCase();
			}	
		}	
		else {
		//If there is no selected color, displays selected color as empty in the page.
			if(getElement(modifiedProductId+"selectedColor") != null){	
				getElement(modifiedProductId+"selectedColor").innerHTML="";
			}
			// code is added for trac 1179 at 10-08-2008 
			if(getElement(modifiedProductId+"selectedColorMoreInfo") != null) {				
				getElement(modifiedProductId+"selectedColorMoreInfo").innerHTML="";			
			}
			// End of code is added for trac 1179 at 10-08-2008 
			if(getElement(this.productId+"selColor") != null){
				getElement(this.productId+"selColor").innerHTML="";
			}	
		}


		
		if(this.skuSelector.mSelectedSizeName != null){
		//If there is selected size, displays the selected size in the page.
			if(getElement(this.productId+"selectedSize") != null){
				getElement(this.productId+"selectedSize").innerHTML=this.skuSelector.mSelectedSizeName.toUpperCase();
			}	
			
			if(getElement(this.productId+"selSize")){
				getElement(this.productId+"selSize").innerHTML=" "+this.skuSelector.mSelectedSizeName.toUpperCase();
			}
		} else {
		//If there is no selected size, displays "NO SIZE SELECTED" in the page.
			if(getElement(this.productId+"selectedSize") != null){
				getElement(this.productId+"selectedSize").innerHTML="NO SIZE SELECTED";
			}	
			
			if(getElement(this.productId+"selSize")){
				getElement(this.productId+"selSize").innerHTML="NO SIZE SELECTED";
			}			
		}
		
		//If there is an element with id "<productid>selType", displays the selected size type in the page.
		if(getElement(this.productId+"selType") != null){
			if(this.skuSelector.mSelectedSizeType != null){
				if(this.skuSelector.mSelectedSizeName != null){
					if(this.skuSelector.mAvailableSizeTypes.length>1){
				//If there is selected size type, displays the selected size in the page.
				getElement(this.productId+"selType").innerHTML=","+" "+this.skuSelector.mSelectedSizeType.toUpperCase();	
					}
					else if(this.skuSelector.mAvailableSizeTypes.length==1){
						if(this.skuSelector.mSelectedSizeType=="regular"){
						getElement(this.productId+"selType").innerHTML="";
						}
                        else{
						getElement(this.productId+"selType").innerHTML=","+" "+this.skuSelector.mSelectedSizeType.toUpperCase();
						}
					}
					else{
					getElement(this.productId+"selType").innerHTML="";
					}
				}
				else
				{
                    getElement(this.productId+"selType").innerHTML= "";
				}
			} else {
				//If there is no selected size type, displays the selected size type as in the page.
				getElement(this.productId+"selType").innerHTML= "";
			}
		}

		
		/*
		 * If there is a selected sku, then sets the value of CartFormModifierFormHandler.catalogRefIds, 
		 * name of the quantity field with selected sku id.
		 * Sku is considered as selected if a size is selected for a product
 		 * if there is a select checkbox, Sku is considered as selected if both size and select checkbox is selected for a product.
		 */

		if(this.skuSelector.getSelectedSku() != null 
			&& (getElement(this.productId+"selectBox")==null 
				|| getElement(this.productId+"selectBox").checked)){

			var selectedSku = this.skuSelector.getSelectedSku();
			if(getElement(this.productId+"catalogRefId") != null){
				getElement(this.productId+"catalogRefId").value = selectedSku.skuId;
			}
			if(getElement(this.productId+"qty") != null){
				getElement(this.productId+"qty").name = selectedSku.skuId;			
				activateAddToBagButton(this.productId);
			}
		} else {
			if(getElement(this.productId+"catalogRefId") != null){
				getElement(this.productId+"catalogRefId").value = "";
			}
			if(getElement(this.productId+"qty") != null){
				getElement(this.productId+"qty").name = "";
				deactivateAddToBagButton(this.productId);
			}
		
		}
	}
}	


function activateAddToBagButton(prodId){
	var atbBtn = $('An_AddToBagButton_'+prodId);
	if(atbBtn !== 'undefined' && atbBtn !== null){
	 atbBtn.removeClassName("disabled");
	 atbBtn.href = "javascript:void(0)";
	 atbBtn.onclick = function(){ addItemToCart(prodId)};
	 atbBtn.onmouseover = "";
	 atbBtn.onmouseout = "";
	}
}

function deactivateAddToBagButton(prodId){
	var atbBtn = $('An_AddToBagButton_'+prodId);
	if(atbBtn !== 'undefined' && atbBtn !== null){
	 atbBtn.addClassName("disabled");
	 atbBtn.href = "javascript:void(0)";
	 atbBtn.onclick = "";
	 atbBtn.onmouseout= function(){ hideddrivetip()}; 
	 atbBtn.onmouseover=function(){ ddrivetip('<div id=tooltip>PLEASE SELECT A SIZE</div>', '#FFFFFF','#8B0000','160',true);};
    }
}

//Returns the productselector object based on the given product id.
function getProductSelector(pProductId, createNew, pIsLeaderProduct){
	/*
	 * Loops through and returns the productselector object
	 * from the product selector array for the given product id
	 */
	for(var i=0;i<productSelectorArray.length;i++){		
		if(productSelectorArray[i].productId == pProductId && productSelectorArray[i].isLeaderProduct == pIsLeaderProduct){		
			return productSelectorArray[i];
		}
	}
	
	if(createNew){
	/* 
	 * If the createNew boolean flag is set to true and 
	 * product selector is not available for the given product id,
	 * then creates a new productselector object for the given product id and
	 * returns the newly created productselector object.
	 */
		productSelectorArray.push(new ProductSelector(pProductId, pIsLeaderProduct));	
		return productSelectorArray[productSelectorArray.length - 1];
	} else {
		/*If the createNew boolean flag is not set to true and 
	 	 * product selector is not available for the given product id
	 	 * then return null
	 	 */
		return null;
	}	
	
}

/*
 * Adds the given sku to the product selector of the given product id.
 */
function addSku(pProductId, sku, pIsLeaderProduct){	
	var productSelector = getProductSelector(pProductId, true, pIsLeaderProduct);
	productSelector.addSku(sku);
}

/*
 * Adds the given size to the product selector of the given product id.
 */
function addSize(pProductId, size, pIsLeaderProduct){
//alert("addSize"+pProductId+pIsLeaderProduct);
	var productSelector = getProductSelector(pProductId, true, pIsLeaderProduct);
	productSelector.addSize(size);
}


/*
 * Initializes the product selector of the given product id.
 * Internally initializes the skuselector wrapped by product selector.
 * Sets the given color code as the selected color.
 * Sku selector initializes the available sizetypes, available colors, available colors,
 * default selected size type and default selected color based on the skuList and sizeList
 * properties of product selector.
 */
//Code modified for Trac 1680.
function initializeProduct(productId, colorCode, pIsLeaderProduct, pDefaultSizeType){
	var productSelector = getProductSelector(productId, true, pIsLeaderProduct);
	productSelector.skuSelector.mSelectedColorCode = colorCode;
	productSelector.skuSelector.mDefaultSizeType = pDefaultSizeType;
	productSelector.initialize();
}
//End of code modified for Trac 1680.


/******************************************************
Outfitting setSelectedColorForOutfitting

********************************************************/
function setSelectedColorForOutfitting(imgElem, pProductId, pColorId, pColorCode, prodImg, pSkuId, pColorName, isLeaderProduct, pCatIndex){
  if(document.forms["OutfittingProductColorForm"]!=null) {
	  var colorBeanElement = document.getElementsByName("/uo/userprofiling/OutfittingProfileFormHandler.OutfittingInfo.productColorSelections[" + pCatIndex + "]")[0];
	  if(colorBeanElement!=null) {		    
		  colorBeanElement.value = pColorId;		  
		  //alert(colorBeanElement.getAttribute("name") + " set to: " + colorBeanElement.value);
	  }
	}	
  setSelectedColor(imgElem, pProductId, pColorCode, prodImg, pSkuId, pColorName, isLeaderProduct);
  //Call pngfilter on the outfit image, named for example "img71461"
  LoadPngImage("img"+pProductId);
} 

/******************************************************
Called when user clicks on swatch from mixmatch page.
Updates user's colorSelection bean, set it to colorid.
It will be set when the page is submitted again
Changes prod selector image, and outfit image (TO DO)
Additional params: pColorId, pIndex
This might need to be cleaned up
********************************************************/
function setSelectedColorForMixMatch(imgElem, pProductId, pColorId, pColorCode, prodImg, mixmatchImg, pSkuId, pColorName, isLeaderProduct, pCatIndex) {   
  if (document.forms["mixMatchForm"] != null) {
    var colorBeanElement = document.getElementsByName("/uo/userprofiling/OutfittingProfileFormHandler.OutfittingInfo.productColorSelections[" + pCatIndex + "]")[0];
    if (colorBeanElement!=null) {
      colorBeanElement.value = pColorId;
      //alert("colorid is: " + pColorId);
    }
  }
  productColorCodeArray[pCatIndex]=pColorCode;
  var imgProdName = "img"+pProductId;
  var imgMixMatchName;
  //changes product image and mixmatch image  
  changeImage(imgProdName, prodImg); 
  //changeImage(imgMixMatchName, mixmatchImg);
  
  
  
  if(pCatIndex==0)
  {
	changeImage("imgMixMatchtops", mixmatchImg);
	imgMixMatchName = "imgMixMatchtops";
  }
  else if(pCatIndex==1)
  {
	changeImage("imgMixMatchbottoms", mixmatchImg);
	imgMixMatchName = "imgMixMatchbottoms";
  }
  else if(pCatIndex==2)
  {
	changeImage("imgMixMatchaccessories", mixmatchImg);
	imgMixMatchName = "imgMixMatchaccessories";
  }
  //changes the color text that is displayed
  changeSelectedColorText(pProductId, pColorName);
	//highlight selected swatch
  imgClicked(imgElem.id, imgElem);
  
  //Save the newly selected image in the productcolorarray
  setValueToProductColorArray(pCatIndex, pProductId, mixmatchImg)

  LoadPngImage(imgMixMatchName);

  } 




/******************************************************
Outfitting setSelectedProduct
Hidden inputs for mixmatch.jsp example name="prodSelection0"
Parameters: imgElem (currently not being used)
pProductId - product id
pColodCode - product's color code
pIndex - index of category 0 = tops; 1 = bottoms; 2 = accessories
********************************************************/
function setSelectedProductForOutfitting(imgElem, pProductId, pColorId, pIndex){  
  
  var mixmatchform = document.forms["mixMatchForm"];
  if(mixmatchform!=null)
  {
	  var productBeanElement = document.getElementsByName("/uo/userprofiling/OutfittingProfileFormHandler.OutfittingInfo.productSelections[" + pIndex + "]")[0];
	  var colorBeanElement = document.getElementsByName("/uo/userprofiling/OutfittingProfileFormHandler.OutfittingInfo.productColorSelections[" + pIndex + "]")[0];	  
      updateBuyThisOutfitValue(false);
	  
	  if(productBeanElement!=null)
	  {		
		  productBeanElement.value = pProductId;
		  //alert("bean's productid set to = " + pProductId);		  
	  }
	  if(colorBeanElement!=null)
	  {		
		  colorBeanElement.value = pColorId;		
		  //alert("colorid = " + pColorId);  
	  }	 	  
	  //mixmatchform.submit();
  }   
} 


/*
Called from outfit_prodimages.jsp on the product onclick event
Loads appropriate scene7 images on the left side of mixmatch

imgElem -- image object that was clicked
pProductId -- id of the product which image was clicked
pColorId -- id of the selected color for the product
pColorCode -- code of the selected color for the product
pIndex -- category index (0 top, 1 bottom, 2 accessory)
imageSrc -- scene7 image url
*/
function setSelectedProductForOutfittingWithColor(imgElem, pProductId, pColorId, pColorCode, pIndex, imageSrc){  

  height = "307px";
  width = "168px";  
  //Update scene7 image 
  if(pIndex==0)
  {
	changeImage("imgMixMatchtops", imageSrc);
	//LoadPngImageWithSize("imgMixMatchtops", width, height);
	LoadPngImage("imgMixMatchtops");
  }
  else if(pIndex==1)
  {
	changeImage("imgMixMatchbottoms", imageSrc);
	//LoadPngImageWithSize("imgMixMatchbottoms", width, height);
	LoadPngImage("imgMixMatchbottoms");
  }
  else if(pIndex==2)
  {
	changeImage("imgMixMatchaccessories", imageSrc);
	//LoadPngImageWithSize("imgMixMatchaccessories", width, height);
	LoadPngImage("imgMixMatchaccessories");
  }
  //Display and hide apprropriate swatches
  displaySwatches(pIndex, pProductId);
  //Track selected prodId
  productIdArray[pIndex]=pProductId;
  //Track selected colorCode
  productColorCodeArray[pIndex]=pColorCode;
  //Select/unselect upporopriate product images
  handleProductImages(pIndex, pProductId)
	

  setSelectedProductForOutfitting(imgElem, pProductId, pColorId, pIndex);

  
} 


/*
Called when user changes the selected category 1 or 2 on the mixmatch page (categoryDropDown.jsp, category2Dropdown.jsp)
The function sets the value of buy this outfit property to false and then submits the form
*/
function submitToUpdateOutfitCategory1()
{  
  var mixmatchform = document.forms["mixMatchForm"];
  if(mixmatchform!=null)
  {
      updateBuyThisOutfitValue(false); 
	  updateOutfitCategorySuccessURL("");
	  mixmatchform.submit();
  }   
}

function updateOutfitCategorySuccessURL(sValue)
{
	successURLObject = document.getElementsByName("/uo/userprofiling/OutfittingProfileFormHandler.updateOutfitCategorySuccessURL")[0];
	if(successURLObject!=null)
	{
		successURLObject.value=sValue;
	}
	

}


/*
Called when user clicks on Buy This Outfit button in mixmatch.jsp
The function sets the value of buy this outfit property to true and then submits the form
*/
function submitToUpdateSelections()
{  
  var mixmatchform = document.forms["mixMatchForm"];
  if(mixmatchform!=null)
  {
      updateBuyThisOutfitValue(true);	  
	  mixmatchform.submit();
  }   
}

/*
Called from submitToUpdateOutfitCategory1, submitToUpdateSelections, setSelectedProductForOutfitting
Sets the value of buy this outfit property
*/
function updateBuyThisOutfitValue(bValue)
{
      var buyThisOutfit = document.getElementsByName("/uo/userprofiling/OutfittingProfileFormHandler.buyThisOutfit")[0];
	  if(buyThisOutfit!=null)
	  {
		buyThisOutfit.value=bValue;
	  }
}


/*
 * Sets the given color code as selected and reinitializes all products.
 * Also takes the extra parameters to show different swatches for selected and
 * unselected image.
 * It calls the imgClicked function from the colorswatches.js. This function takes
 * care of showing the current image as selected and rest of the images below to this
 * color swatch as unselected.
 */
 /* this function setSelectedColor is used on the product level; there's a dup in swatches.js that is used on the category level */
 /* Code modified for Trac 1974 */
 /* added pSizeName, pIsBigImage, pTemplateType so we can use this to specify if template = familymod, update the generic span id selectedColor in function changeColor */
function setSelectedColor(imgElem, pProductId, pColorCode, pProdImg, pSkuId, pColorName, pIsLeaderProduct, pCurrentPage, pSizeName, pIsBigImage, prodTempl){
	var uniqueId = pProductId;
	var imglinkHandle = "imglink" + uniqueId;
	var productSelector = getProductSelector(pProductId, false, pIsLeaderProduct);
	if(productSelector != null){
		productSelector.setSelectedColorCode(pColorCode);
		initializeAllProducts(pIsLeaderProduct);
	}
	changeColor(pProductId, pColorCode, pProdImg, pSkuId, pColorName, pIsLeaderProduct, null, prodTempl);	
	imgClicked(imgElem.id, imgElem);
	// code is added for "Remove javascript links on category pages"(Task 79).
	if(!(pCurrentPage == "ProductDetailPage")){
		if(getElement(imglinkHandle) != null){
		getElement(imglinkHandle).href=encodeURI(contextPath+'/catalog/productdetail.jsp?id='+pProductId+'&catId='+catId+'&pushId='+pushId+'&popId='+popId+'&navAction='+navAction+'&color='+pColorCode+'&isProduct=true');
		}
	}
	// End of code is added for "Remove javascript links on category pages"(Task 79).

	if (prodTempl == "familymod") {
	 var elementId = imgElem.id;
	 var numswatches = $$("span.familyModSwatches a");
	 for (var i=0;i<numswatches.length;i++)
	 {
		 var getswatchelem = numswatches[i].id;
		 var elem=document.getElementById(getswatchelem);
		 if (elementId != getswatchelem) {
			elem.className="unselected";
			elem.name="unselected"; // this is what the swatch looks at and defaults back to after mouseout
		}
	 }
	
	 selectFamilyModSwatches(pProductId);
	}
}

function selectFamilyModSwatches(prodId) {
 familyModWashLabelPopulate(prodId);
 //take care of size categories
 var findeachtab = $$("ul#skuNav li");
 if (findeachtab.length > 0){
	 familyModSizeCategoryPopulate(prodId);
 }
 //////////////////////////////
 familyModSizePopulate(prodId);
 familyModQtyPopulate(prodId);
}

function familyModWashLabelPopulate(prodId){
 var washlabelelementId = "l"+prodId+"selectedColor"; // is always leader for fam mod
 var numprodid = $$("span.famprodSummary");
 for (var i=0;i<numprodid.length;i++)
 {
	 var getwashlabelelem = numprodid[i].id;
	 var washlabelelem=document.getElementById(getwashlabelelem);
	 if (washlabelelementId != getwashlabelelem) {
		washlabelelem.style.visibility="hidden";
		washlabelelem.style.display="none";
	}
	else{
		washlabelelem.style.visibility='visible';
		washlabelelem.style.display='inline';
	}
 }
 
 /* hide/show appropriate style # */
 var matchstyleid = "style"+prodId;
 var numstyles = $$("div.eachstyle");
 for (var i=0;i<numstyles.length;i++)
 {
	 var getstyleid = numstyles[i].id;
	 var styleidelem=$(getstyleid);
	 if (matchstyleid != getstyleid) {
		styleidelem.style.visibility="hidden";
		styleidelem.style.display="none";
	}
	else{
		styleidelem.style.visibility='visible';
		styleidelem.style.display='block';
	}
 }
 
}

function familyModSizeCategoryPopulate(prodId)
{
	var numeachtab = $$('ul#skuNav li');
	var matchEachTab = "eachtab"+prodId;
	for (var i=0;i<numeachtab.length;i++)
	{
		var geteachtabelem = "li."+numeachtab[i].id;
		var eachtabelem = $$(geteachtabelem);
		if (numeachtab[i].id != matchEachTab)
		{
		 for (var j=0;j<eachtabelem.length;j++)
		 {
			eachtabelem[j].style.visibility='hidden';
			eachtabelem[j].style.display='none';
		 }
		}
		else {
		 for (var j=0;j<eachtabelem.length;j++)
		 {
			eachtabelem[j].style.visibility='visible';
			eachtabelem[j].style.display='inline';
		 }
		}
	}
}

function familyModQtyPopulate(prodId)
{
 var numqtyinput = $$('ul#sizes div');
 var matchQtyDivInputId = 'p_qty'+prodId;
 var matchQtyInputId = prodId+'qty';

 for (var i=0;i<numqtyinput.length;i++)
 {
	 var getqtyinputelem = numqtyinput[i].id;
	 var qtyinput = $(getqtyinputelem);
	 if (getqtyinputelem != matchQtyDivInputId)
	 {
		 qtyinput.style.visibility='hidden';
		 qtyinput.style.display='none';
	 }
	 else{
		 qtyinput.style.visibility='visible';
		 qtyinput.style.display='inline';
	 } 
 }
 var numqtyinput2 = $$('ul#sizes div input.qty');
 for (var j=0;j<numqtyinput2.length;j++)
 {
	 var getqtyid = numqtyinput2[j].id;
	 var otrqtyid = $(getqtyid);
	 if (getqtyid != matchQtyInputId)
	 {
		 /* set the other color code's qty to 0 so that it doesn't get added to bag */
		 otrqtyid.value='0';
	 }
	 else{
		 /* set the selected color code's qty to 1 */
		 otrqtyid.value='1';
	 } 
 } 
}

function familyModSizePopulate(prodId)
{
 var matchSizeId = prodId+"selectedSize";
 var numsizes = $$('div#p_size label span');

 var temp = 'li.size'+prodId;
 var sizeselects = $$(temp);
// alert(sizeselects.length);

 for (var i=0;i<numsizes.length;i++)
 {
	 var getsizeelem = numsizes[i].id;
	 var sizespan = $(getsizeelem);
	 if (getsizeelem != matchSizeId)
	 {
		 sizespan.style.visibility='hidden';
		 sizespan.style.display='none';
	 }
	 else{
		 sizespan.style.visibility='visible';
		 sizespan.style.display='inline';
	 }
 }

 var numsizeselects = $$('ul#sizes li');
 var matchSizeSelectId = 'size'+prodId;

 for (var i=0;i<numsizeselects.length;i++)
 {
	 var getsizeselectelem = 'li.'+numsizeselects[i].id;
	 var sizeselects = $$(getsizeselectelem);
	 if (numsizeselects[i].id != matchSizeSelectId)
	 {
		 for (var j=0;j<sizeselects.length;j++)
		 {
			 sizeselects[j].style.visibility='hidden';
			 sizeselects[j].style.display='none';
		 }
	 }
	 else{
		 for (var j=0;j<sizeselects.length;j++)
		 {
			 sizeselects[j].style.visibility='visible';
			 sizeselects[j].style.display='inline';
		 }
	 }
 }
}

// Sets the given size type as selected and reinitializes all products.
function setSelectedType(pProductId, pSizeType, isLeaderProduct){
	var productSelector = getProductSelector(pProductId, false, isLeaderProduct);
	if(productSelector != null){
		productSelector.setSelectedSizeType(pSizeType);
		initializeAllProducts(isLeaderProduct);
	}	
	
}

// Sets the given size as selected and reinitializes all products.
function setSelectedSize(pProductId, pSizeName, isLeaderProduct){

	var productSelector = getProductSelector(pProductId, false, isLeaderProduct);
	if(productSelector != null){
			productSelector.setSelectedSizeName(pSizeName);
			initializeAllProducts(isLeaderProduct);	
	}
	
}
function setSelectedSizeForShopBySize(pProductId, pSizeName1,pSizeName2,isLeaderProduct){	
	var productSelector = getProductSelector(pProductId, false, isLeaderProduct);
	if(productSelector != null){
		//Code modified for trac 2197
		var sizeName3 = null;
		var currentSkuWithSizename1 = null;
		var currentSkuWithSizename2 = null;
		var currentSkuWithSizename3 = null;
		if(pSizeName1.indexOf("(")!= -1 ){
			sizeArray = pSizeName1.match(/\d+(,\d{3})*(\.\d{1,2})?/g);
			if(sizeArray.length == 3){
				pSizeName1 = sizeArray[0];
				pSizeName2 = sizeArray[1].replace("Euro ", "");
				pSizeName2 = pSizeName2 +" EURO";
				sizeName3 = sizeArray[2] +" EURO";
			}else if(sizeArray.length == 2){
				pSizeName1 = sizeArray[0];
				pSizeName2 = sizeArray[1].replace("Euro ", "");
				pSizeName2 = pSizeName2 +" EURO";
			}
		}
		currentSkuWithSizename1 = productSelector.skuSelector.getSku(pSizeName1);
		currentSkuWithSizename2 = productSelector.skuSelector.getSku(pSizeName2);
		if(sizeName3 != null){
		  currentSkuWithSizename3 = productSelector.skuSelector.getSku(sizeName3);
		}
		if(currentSkuWithSizename1 != null && currentSkuWithSizename1.availabilityStatus != 1001){
			productSelector.setSelectedSizeName(pSizeName1);
			initializeAllProducts(isLeaderProduct);	
		}else if(currentSkuWithSizename2 != null && currentSkuWithSizename2.availabilityStatus != 1001){
			productSelector.setSelectedSizeName(pSizeName2);
			initializeAllProducts(isLeaderProduct);	
		}else if(currentSkuWithSizename3 != null && currentSkuWithSizename3.availabilityStatus != 1001){
			productSelector.setSelectedSizeName(sizeName3);
			initializeAllProducts(isLeaderProduct);	
		}
		//End of code modified for trac 2197		
	}
}
/**
 * Initializes all the products by calling repopulateAll function of each productselector.
 * Enables the Add to bag and Add to Wishlist buttons if atleast one sku is selected for any one of the products.
 * Disables the Add to bag and Add to Wishlist buttons if no sku is selected for any product.
 * toolTip will be displayed with the specified messages on MouseOver on the disabled Add to bag and Add to Wishlist buttons.
 * Sku is considered as selected if a size is selected for a product
 * if there is a select checkbox, Sku is considered as selected if both size and select checkbox is selected for a product.
 */	
function initializeAllProducts(isLeaderProduct){
	//checks whether the sku is selected or not.
	var skuSelected = false;
	//ckecks whether the size is selected.
	 var sizeSelect = false;
	//checks whether the checkbox is selected when size is not selected
	var boxSelected = false;
    //this variable is used along with the skuSelected to know whether the sku is selected or not
	var checkBox = true;

  // LI TESTING
  //for(var i=0;i<productSelectorArray.length;i++){
  // alert(productSelectorArray.productId); 
  //}
	for(var i=0;i<productSelectorArray.length;i++){
		productSelectorArray[i].repopulateAll(isLeaderProduct);

		if(productSelectorArray[i].skuSelector.getSelectedSku() != null){			
			if(getElement(productSelectorArray[i].productId+"selectBox")!=null){
				if(getElement(productSelectorArray[i].productId+"selectBox").checked){
					skuSelected = true;
				}
			} else {
               	sizeSelect = true;
              	skuSelected = true;
			}	
		} else{
		 	if(getElement(productSelectorArray[i].productId+"selectBox")!=null){
		    	if(getElement(productSelectorArray[i].productId+"selectBox").checked){
                     boxSelected = true;
                     checkBox = false;
				}
			} else{
				sizeSelect = true;
			}
		}
	}
	
  	if(skuSelected && checkBox){
	  	// code is added for trac 1179 at 10-08-2008 
	  	// check for null
	  	// Code is modified for Anthro Bazzar Voice 2009 
	  	if (getElement("addToBagBtn") != null )	{
			getElement("addToBagBtn").innerHTML="<a href=\"javascript:addItemToBag();\" class=\"button\" title=\"Add to Bag\">add to bag</a>";
		}
		if(getElement("addToWishlistBtn") !=null) {
			getElement("addToWishlistBtn").innerHTML="<a href=\"javascript:expandCollapse('addToWishlistPopup','over');\" alt=\"Add to Wishlist\" >add to wishlist</a>";
		}
		// End of Code is modified for Anthro Bazzar Voice 2009 
		//End of code is added for trac 1179 at 10-08-2008 	
		//getElement("addToWishlistBtn").innerHTML="<a href=\"javascript:addItemToWishlist();\"><img src=\"../images/btn_addtowishlist_off.gif\" onmouseover=\"this.src='../images/btn_addtowishlist_on.gif'\" onmouseout=\"this.src='../images/btn_addtowishlist_off.gif'\" alt=\"Add to Wishlist\"/></a>";
   	} else {	
        var message = "";
        if(sizeSelect){
        	message = "PLEASE SELECT A SIZE";
		} else{
			if(boxSelected){
				 message = "PLEASE SELECT A SIZE";
			 }
			 else{
				message = "PLEASE SELECT AN ITEM";
			 }
		}
		// code is added for trac 1179 at 10-08-2008 
		// check for null
		// Code is modified for Anthro Bazzar Voice 2009 
        if (getElement("addToBagBtn") != null ) { 
			getElement("addToBagBtn").innerHTML="<a href=\"javascript:void(0);\" class=\"button\" style=\"cursor:pointer\" onmouseout=\"hideddrivetip()\" onmouseover=\"ddrivetip(\'<div id=tooltip>"+message+"</div>\',\'#FFFFFF\',\'#8B0000\',\'160\',true)\"  title=\"Add to Bag Disabled\">add to bag</a>";
		}
		if(getElement("addToWishlistBtn")!=null) {
			getElement("addToWishlistBtn").innerHTML="<a href=\"javascript:void(0);\"  style=\"cursor:pointer\"  onmouseout=\"hideddrivetip()\" onmouseover=\"ddrivetip(\'<div id=tooltip>"+message+"</div>\',\'#FFFFFF\',\'#8B0000\',\'160\',true)\" alt=\"Add to Wishlist Disabled\">add to wishlist</a>";
		}
		// End of Code is modified for Anthro Bazzar Voice 2009 
		//End of code is added for trac 1179 at 10-08-2008 		
		/* if(getElement("addToWishlistBtn")!=null)
		{
		getElement("addToWishlistBtn").innerHTML="<img style=\"cursor:pointer\" src=\"../images/btn_addtowishlist_disabled.gif\"  onMouseout=\"hideddrivetip()\" onMouseover=\"ddrivetip(\'<div id=tooltip>"+message+"</div>\',\'#FFFFFF\',\'#8B0000\',\'160\',true)\" alt=\"Add to Wishlist Disabled\">";
		}*/
	}	
}

function SkuSelector() {

	this.AVAILABILITY_STATUS_IN_STOCK = 1000;
	this.AVAILABILITY_STATUS_OUT_OF_STOCK = 1001;
	this.AVAILABILITY_STATUS_PREORDERABLE = 1002;
	this.AVAILABILITY_STATUS_BACKORDERABLE = 1003;
    	this.AVAILABILITY_STATUS_DISCONTINUED = 1005;

	this.contextPath = "";
	this.skus = null; //variable to hold list of all product sku's
	
	this.mSelectedColorCode = null; //variable to hold currently selected color

	this.mSelectedSizeType = null; //variable to hold currently selected size type

	this.mSelectedSizeName = null; //variable to hold currently selected size name

	//variable to hold current list of available colors with respect to currently selected
	// size type and currently selected size name
	this.mAvailableColorCodes = null; 

	//variable to hold current list of available size types with respect to currently selected
	// color and currently selected size name
	this.mAvailableSizeTypes = null; 

	//variable to hold current list of available sizes with respect to currently selected
	// size type and currently selected color
	this.mAvailableSizes = null;
	
	this.mAllSizes = null;

	//Initializes the Available size types, colors and sizes with default values
	// from the given list of skus.	
	this.initialize = function(skuList, sizeList, path){		
		this.skus = skuList;
		this.mAllSizes = sizeList;
		this.contextPath = path;
		
		this.initializeAvailableSizeTypes();
		this.initializeDefaultSelectedSizeType();
		this.initializeAvailableColors(this.mSelectedSizeType);
		this.initializeDefaultSelectedColor();
		this.initializeAvailableSizes(this.mSelectedColorCode,
				this.mSelectedSizeType);
		this.initializeDefaultSelectedSize();
	}	
	
	
	//Initializes the list containing all the available size types.
	this.initializeAvailableSizeTypes =  function(){
		//alert("calling initializeAvailableSizeTypes");
		this.mAvailableSizeTypes = new Array();
		var index = 0;
		for (var i = 0; i < this.skus.length; i++) {
			var currentSku = this.skus[i];
			if (this.mAvailableSizeTypes,this.skus[i].type!="" && !contains(this.mAvailableSizeTypes,this.skus[i].type)) {
				this.mAvailableSizeTypes[index] = this.skus[i].type;
				index++;
			}
		}
           this.mAvailableSizeTypes.sort();
          this.sortSizeTypes(this.mAvailableSizeTypes);
	}
	
	//Code modified for Trac 1680.
	 this.sortSizeTypes = function(array){
	 	var defaultSizetype = this.mDefaultSizeType;
	 	var selectedColorCode = this.mSelectedColorCode;
		initialSizeTypeArray = new Array("petite","regular","short","tall");
		
		referenceSizeTypeArray = new Array();
		var k = initialSizeTypeArray.indexOf(defaultSizetype);
		var j=0;
		for(var i=k; i<initialSizeTypeArray.length; i++){
			 referenceSizeTypeArray[j++]=initialSizeTypeArray[i];
		}
		for(var i=0; i<k; i++){
			 referenceSizeTypeArray[j++]=initialSizeTypeArray[i];
		}
						
		availableSizeTypeArray = new Array();
		var count = 1;
		var size = 0;
		
		if(contains(array,defaultSizetype)){
			availableSizeTypeArray[0] = defaultSizetype;
			for (var i = 0; i < referenceSizeTypeArray.length; i++) {
				var sizeType = referenceSizeTypeArray[i];
				if (sizeType != defaultSizetype && contains(array,sizeType)) {
					availableSizeTypeArray[count] = sizeType;
					count++;
				}
			}
		} else {
			for (var i = 0; i < referenceSizeTypeArray.length; i++) {
				var sizeType = referenceSizeTypeArray[i];
				if (contains(array,sizeType)) {
					availableSizeTypeArray[size] = sizeType;
					size++;
				}
			}
		}
		
		inStockSizeTypeArray = new Array();
		var count = 0;
		
		for (var i = 0; i < this.skus.length; i++) {
			var currentSku = this.skus[i];
			if(currentSku.availabilityStatus != this.AVAILABILITY_STATUS_OUT_OF_STOCK && currentSku.colorCode == selectedColorCode){
				inStockSizeTypeArray[count] = currentSku.type;
				count++;
			} 
		}
		
		availableInStockSizeTypesArray = new Array();
		availableOutOfStockSizeTypesArray = new Array();
		var count = 0;
		var size = 0;
		
		for (var i = 0; i < availableSizeTypeArray.length; i++) {
			var sizeType = availableSizeTypeArray[i];
			if (contains(inStockSizeTypeArray,sizeType)) {
				availableInStockSizeTypesArray[count] = sizeType;
				count++;
			} else {
				availableOutOfStockSizeTypesArray[size] = sizeType;
				size++;
			}
		}
		
		if(availableOutOfStockSizeTypesArray.length != 0){
			var init = availableInStockSizeTypesArray.length+1;
			for (var i = 0; i < availableOutOfStockSizeTypesArray.length; i++) {
				availableInStockSizeTypesArray[init] = availableOutOfStockSizeTypesArray[i];
				init++;
			}
		}
		this.mAvailableSizeTypes = availableInStockSizeTypesArray;
    }
	//End of code modified for Trac 1680.
	
	//Sets the default currently selected size type.
	this.initializeDefaultSelectedSizeType = function () {
		//alert("calling initializeDefaultSelectedSizeType");
		
		if (isEmpty(this.mSelectedSizeType)) {
			// Get default size type from brand config
			this.mSelectedSizeType = this.mAvailableSizeTypes[0];
		} else {
			// Check if the current selected size type is actually available
			var currentSelectedSizeTypeIsAvaiable = false;
			for (var i = 0; i < this.mAvailableSizeTypes.length; i++) {
				var sizeType = this.mAvailableSizeTypes[i];
				if (sizeType == this.mSelectedSizeType) {
					currentSelectedSizeTypeIsAvaiable = true;
					break;
				}
			}
			if (!currentSelectedSizeTypeIsAvaiable) {
				// Set to the first available size type
				this.mSelectedSizeType = this.mAvailableSizeTypes[0];
			}
		}
	}		
	
	//Initializes the list containing all the available colors with respect
	//to the given size type.
	this.initializeAvailableColors = function (pSizeType) {
		//alert("calling initializeAvailableColors(pSizeType)");
				
		this.mAvailableColorCodes = new Array();
		var index = 0;
		for (var i = 0; i < this.skus.length; i++) {
			var currentSku = this.skus[i];
			//if (currentSku.type == pSizeType) {
				if (this.mAvailableColorCodes, currentSku.colorCode!="" && !contains(this.mAvailableColorCodes, currentSku.colorCode)) {
					this.mAvailableColorCodes[index] = currentSku.colorCode;
					index++;
				}

			//}
		}
	}
	
	//Sets the default currently selected color.
	this.initializeDefaultSelectedColor = function() {
		//alert("calling initializeDefaultSelectedColor");
			
		// If no color is selected, select the sorted first color
		if (isEmpty(this.mSelectedColorCode)) {
			this.mSelectedColorCode = this.mAvailableColorCodes[0];
		} else {
			var selectedColorIsPresentInAvailableColors = false;
			// Check if the previously selected color is actually present in the
			// available colors
			for (var i = 0; i < this.mAvailableColorCodes.length; i++) {
				var color = this.mAvailableColorCodes[i];
				if (color == this.mSelectedColorCode) {
					selectedColorIsPresentInAvailableColors = true;
					break;
				}
			}
			if (!selectedColorIsPresentInAvailableColors) {
				// If selected color code is not available now, initialize it to
				// the first one
				this.mSelectedColorCode = this.mAvailableColorCodes[0];
			}
		}
	
	}
	
	//Initializes the list containing all the available sizes with respect
	//to the given size type and color.
	this.initializeAvailableSizes = function(pSelectedColor, pSelectedSizeType) {
		// Retrieve available sizes for this product			
		this.mAvailableSizes = new Array();
		var index = 0;
		for (var i = 0; i < this.skus.length; i++) {
			var currentSku = this.skus[i];
			//if ((currentSku.type == pSelectedSizeType) && (currentSku.colorCode == pSelectedColor)) {
				if (this.mAvailableSizes, currentSku.sizeName!="" && !contains(this.mAvailableSizes, currentSku.sizeName)) {
					this.mAvailableSizes[index] = currentSku.sizeName;
					index++;
				}
			//}
		}		
	
	}
	
	//Sets the default currently selected size.
	this.initializeDefaultSelectedSize = function () {
  		availableSizesinSizeType = new Array();
		for (var i = 0; i < this.mAvailableSizes.length; i++) {
 			var sizeName1 = this.mAvailableSizes[i];
 			if(this.getSku(this.mAvailableSizes[i]) != null && (this.getSku(this.mAvailableSizes[i]).availabilityStatus == this.AVAILABILITY_STATUS_IN_STOCK || this.getSku(this.mAvailableSizes[i]).availabilityStatus == this.AVAILABILITY_STATUS_BACKORDERABLE))
 			{
 				availableSizesinSizeType.push(sizeName1);
 			}
 
		}
 
		if(availableSizesinSizeType.length==1){
			this.mSelectedSizeName =availableSizesinSizeType[0] ;
		}
		else{
  			for (var i = 0; i < this.mAvailableSizes.length; i++) {
    			var sizeName = this.mAvailableSizes[i];
    			if (sizeName == this.mSelectedSizeName) {
     				if(this.getSku(this.mAvailableSizes[i]) != null && (this.getSku(this.mAvailableSizes[i]).availabilityStatus == this.AVAILABILITY_STATUS_IN_STOCK || this.getSku(this.mAvailableSizes[i]).availabilityStatus == this.AVAILABILITY_STATUS_BACKORDERABLE))
     				{
      					return;
     				}
    			}
   			}
  			this.mSelectedSizeName = null;
		}
 	}

	
	
	
	//Returns the skuid based on the currently selected size type, color and size name.
	this.getSelectedSku = function() {
		for (var i = 0; i < this.skus.length; i++) {
			var sku = this.skus[i];
			if(sku.colorCode!='' && sku.sizeName!=''){
				if ((sku.colorCode == this.mSelectedColorCode) 
					&& (sku.sizeName == this.mSelectedSizeName)
						&& (sku.type == this.mSelectedSizeType)) {
					return sku;
				}
			} else if(sku.colorCode=='' && sku.sizeName!=''){
				if ((sku.sizeName == this.mSelectedSizeName)
						&& (sku.type == this.mSelectedSizeType)) {
					return sku;
				}
			} else if(sku.colorCode!='' && sku.sizeName==''){
				if (sku.colorCode == this.mSelectedColorCode) {
					return sku;
				}
			}else {
				return sku;
			}
		}
		return null;
	}
	
	this.getSku = function(pSizeName) {

		for (var i = 0; i < this.skus.length; i++) {
			var sku = this.skus[i];
			if(this.mSelectedColorCode != null){
				if ((sku.colorCode == this.mSelectedColorCode) 
					&& (sku.sizeName == pSizeName)
						&& (sku.type == this.mSelectedSizeType)) {

					return sku;
				}
			} else {
				if ((sku.sizeName == pSizeName)

						&& (sku.type == this.mSelectedSizeType)) {

					return sku;
				}	
			}
		}
		return null;
	}
	
	this.getColorName = function(pColorCode){
		for (var i = 0; i < this.skus.length; i++) {
			var sku = this.skus[i];
			if (sku.colorCode == pColorCode) {
				return sku.colorName;
			}
		}
		return null;
	}
	
	this.isAvailableSize = function(pSizeName){
		for (var i = 0; i < this.mAvailableSizes.length; i++) {			
			if (this.mAvailableSizes[i] == pSizeName) {
				return true;
			}
		}
		return false;
	}
}

function Sku(pSkuId, pSizeName, pType, pColorCode, pColorName, pAvailabilityStatus, pAvailabilityDate, pImagePath) {
		this.skuId = pSkuId;
		this.sizeName = pSizeName;		
		this.type = pType;
		this.colorCode = pColorCode;
		this.colorName = pColorName;		
		this.availabilityStatus = pAvailabilityStatus;
		this.availabilityDate = pAvailabilityDate;
		this.imagePath = pImagePath;
}


//Returns true if the given string is empty.
function isEmpty (pValue) {
	if ((pValue == null) || (trim(pValue) == "")) {
		return true;
	} else {
		return false;
	}
}
function trim(str)
{
  if (str == true)
  return str.replace(/^\s*|\s*$/g,"");
}


//Checks whether the given array contains the given value
//Returns true if the given array contains the given value, otherwise false.
function contains (array, value){
	for(var i=0;i<array.length;i++){
		if(array[i] == value){
			return true;
		}
	}
	return false;
}


// Returns the element by using the given id with respect to browser compatibility.	
function getElement(elementId){
	return document.all ? document.all[elementId] : document.getElementById(elementId);
}
// code is added for "Remove javascript links on category pages"(Task 79).
function InitializeOutfitValues(pCatId,pNavAction,pPopId,pPushId){
		
		this.catId = pCatId;
		this.navAction = pNavAction;
		this.popId = pPopId;
		this.pushId = pPushId;
		
		
}
// End of code is added for "Remove javascript links on category pages"(Task 79).

function changeImageColor(color, id){
	if(getElement("wardrobeId") != null){
	   var wardrobeVar = getElement("wardrobeId").value;
	}
	if(getElement("imgdownload"+id) != null){
		var downloadUrl = scene7Url+id+"_"+color+"_b?$"+wardrobeVar+"$";
         getElement("imgdownload"+id).innerHTML = "<a href=\"javascript:downloadImage('"+downloadUrl+"');\">download image</a>";
    }
	if(getElement("l"+id+"zoomviewer") != null){
    getElement("l"+id+"zoomviewer").href="javascript:openProductPopupWindow('"+contextPath+"/popups/popup_zoomviewer.jsp?productid="+id+"&color="+color+"');";
	}
	if(getElement("color"+id)!=null){
	   getElement("color"+id).value=color;
	}

	if(getElement("colorId")!=null){
	   getElement("colorId").value = color;
	}
}
