/**************************************************************************************************************************
	 Author              :      PA
	 Version		     :	    1.0
	 Date Created	     :         
	   
	 Change history      :
	
	 Task/Bug               Date(mm-dd-yyyy)            Author          Change Description
	 Trac 1387              01-02-2009                  HGolla          Removed conditional statement to display update link consistently.
	 
	 Update button should   07-27-2010                  HGolla          ProductSelector(pProductId, pDisplaySku, pCart) function has been
	 be disabled in                                                     modified to set size dropdown value to it's default value(Select Size)   
	 Shopping bag                                                       when color dropdown is selected with 'Select Color'.
     
	 In shopping bag,       08-02-2010                  HGolla          Make colorFlag=true in the the method repopulateColors() when colors list
	 update button is                                                   length is equal to 1.
	 disabled for a 
	 product with 
	 one color element.
***************************************************************************************************************************/

function SkuSelector() {

	this.skus = null; //variable to hold list of all product sku's
	
	this.mSelectedColor = 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.mAvailableColors = null; 
	
	//variable to hold current list of available sizes with respect to currently selected
	// size type and currently selected color
	this.mAvailableSizes = null;
	
	//Initializes the Available size types, colors and sizes with default values
	// from the given list of skus.	
	this.initialize = function(skuList, displaySku){
		this.skus = skuList;
		var displayedSku = this.getSku(displaySku);
		this.mSelectedSizeType = displayedSku.type;
		this.initializeAvailableColors(this.mSelectedSizeType);
		this.mSelectedColor = displayedSku.color;
		this.initializeAvailableSizesWithSizeType(this.mSelectedSizeType);
		this.mSelectedSizeName = displayedSku.sizeName;
	}	
	
		
	//Initializes the list containing all the available colors with respect
	//to the given size type.
	this.initializeAvailableColors = function (pSizeType) {
		this.mAvailableColors = new Array();
		var index = 0;
		for (var i = 0; i < this.skus.length; i++) {
			var currentSku = this.skus[i];
			if (currentSku.type == pSizeType) {
				if (!contains(this.mAvailableColors, currentSku.color)) {
					this.mAvailableColors[index] = currentSku.color;					
					index++;
				}

			}
		}		
		this.mAvailableColors.sort();
	}
	
	//Sets the default currently selected color.
	this.initializeDefaultSelectedColor = function() {
		var selectedColorIsPresentInAvailableColors = false;
			// Check if the previously selected color is actually present in the
			// available colors
			for (var i = 0; i < this.mAvailableColors.length; i++) {
				var color = this.mAvailableColors[i];
				if (color == this.mSelectedColor) {
					selectedColorIsPresentInAvailableColors = true;
					break;
				}
			}
			if (!selectedColorIsPresentInAvailableColors) {
				// If selected color code is not available now, initialize it to
				// the first one
				this.mSelectedColor = null;
			}
	
	}

	//Initializes the list containing all the available sizes with respect
	//to the given size type.
	this.initializeAvailableSizesWithSizeType = function(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) {
				if (!contains(this.mAvailableSizes, currentSku.sizeName)) {
					this.mAvailableSizes[index] = currentSku.sizeName;
					index++;
				}
			}
		}		
		this.mAvailableSizes.sort();
	}
	
	//Initializes the list containing all the available sizes with respect
	//to the given size type and color.
	this.initializeAvailableSizes = function(pSelectedColor, pSelectedSizeType) {
		//alert("calling initializeAvailableSizes("+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.color == pSelectedColor)) {
				if (!contains(this.mAvailableSizes, currentSku.sizeName)) {
					this.mAvailableSizes[index] = currentSku.sizeName;
					index++;
				}
			}
		}		
		this.mAvailableSizes.sort();
	}
	
	//Sets the default currently selected size.
	this.initializeDefaultSelectedSize = function () {
			var selectedSizeIsPresentInAvailableSizes = false;
			// Check if the previously selected color is actually present in the
			// available colors
			for (var i = 0; i < this.mAvailableSizes.length; i++) {
				var sizeName = this.mAvailableSizes[i];
				if (sizeName == this.mSelectedSizeName) {
					selectedSizeIsPresentInAvailableSizes = true;
					break;
				}
			}
			if (!selectedSizeIsPresentInAvailableSizes) {
				// If selected color code is not available now, initialize it to
				// the first one
				this.mSelectedSizeName = null;
			}
	}
		
	
	// Initializes the list containing all the available colors  based on size type and size name
	this.initializeAvailableColorsWithSizeTypeAndSizeName = function(pSizeType, pSizeName) {
		this.mAvailableColors = new Array();
		var index = 0;
		for (var i = 0; i < this.skus.length; i++) {
			var currentSku = this.skus[i];
			if ((currentSku.sizeName == pSizeName) && (currentSku.type == pSizeType)) {
				if (!contains(this.mAvailableColors, currentSku.color)) {
					this.mAvailableColors[index] = currentSku.color;
					index++;
				}
			}
			
		}
		this.mAvailableColors.sort();
	}
	
	
	
	//Returns the skuid based on the currently selected size type, color and size name.
	this.getSelectedSkuId = function() {
		for (var i = 0; i < this.skus.length; i++) {
			var sku = this.skus[i];
			if(sku.color!='' && sku.sizeName!=''){
				if ((sku.color == this.mSelectedColor) 
					&& (sku.sizeName == this.mSelectedSizeName)
						&& (sku.type == this.mSelectedSizeType)) {
					return sku.skuId;
				}
			} else if(sku.color=='' && sku.sizeName!=''){
				if ((sku.sizeName == this.mSelectedSizeName)
						&& (sku.type == this.mSelectedSizeType)) {
					return sku.skuId;
				}
			}else if(sku.color!='' && sku.sizeName==''){
				if (sku.color == this.mSelectedColor) {
					return sku.skuId;
				}
			}else {
				return sku.skuId;
			}
		}
		return null;
	}

	this.getSku = function(pSkuId) {
		for (var i = 0; i < this.skus.length; i++) {
			var sku = this.skus[i];
			if (sku.skuId == pSkuId) {
				return sku;
			}
		}
		return null;
	}

	
	
	this.setSelected = function(pSkuId) {

		for (var i = 0; i < this.skus.length; i++) {
			var sku = this.skus[i];
			if (sku.skuId == pSkuId) {
				this.mSelectedColorCode = sku.color;
				this.mSelectedSizeName = sku.sizeName;
			}
		}
	}
}

//Returns true if the given string is empty.
function isEmpty (pValue) {
	if ((pValue == null) || (trim(pValue) == "")) {
		return true;
	} else {
		return false;
	}
}


function trim(str)
{
  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;
}

function containsColor (array, value){
	for(var i=0;i<array.length;i++){
		if(array[i].colorCode == value){
			return true;
		}
	}
	return false;
}



function ProductSelector(pProductId, pDisplaySku, pCart){
	this.productId = pProductId;
	this.displaySku = pDisplaySku;
	this.skuSelector = new SkuSelector();
	this.cart = pCart;
	this.skuList = new Array();
	this.colorList = new Array();
	this.skuSizeArray = new Array();
	this.colorFlag = false;
	
	this.addSize = function(pSizeName){
		this.skuSizeArray.push(pSizeName);
	}
	
	this.addColor = function(pColor){
		this.colorList.push(pColor);
	}

	this.addSku = function(pSku){
		this.skuList.push(pSku);
	}
	this.initialize = function(){
		this.skuSelector.mSelectedSizeType = this.sizeType;
		this.skuSelector.initialize(this.skuList, this.displaySku);	
		this.repopulateAll();		
		handleUpdate(this.productId, this.displaySku, this.cart);	
		if(this.colorFlag == false){
			setSelectedColor(this.productId, this.displaySku, this.cart, "Select Color");
		}
	}
	
	//Sets the given color as the currently selected color and also 
	//reinitializes the available sizes, available size types, currently selected size and currently selected size type based on the
	// given color.
	this.setSelectedColorCode = function(pSelectedColor) {
		this.skuSelector.mSelectedColor = pSelectedColor;		
		this.skuSelector.initializeAvailableSizes(this.skuSelector.mSelectedColor, this.skuSelector.mSelectedSizeType);
		this.skuSelector.initializeDefaultSelectedSize();		
		this.repopulateAll();
		
	}
	
	//Sets the given size name as the currently selected size name and also 
	//reinitializes the available colors, available size types, currently selected color and currently selected size type based on the
	// given size name.
	this.setSelectedSizeName = function(pSelectedSizeName) {
		this.skuSelector.mSelectedSizeName = pSelectedSizeName;		
		this.skuSelector.initializeAvailableColorsWithSizeTypeAndSizeName(this.skuSelector.mSelectedSizeType, this.skuSelector.mSelectedSizeName);
		this.skuSelector.initializeDefaultSelectedSize();
		this.repopulateAll();		
	}
	
	//Wrapper function to repopulate size types, colors, sizes and sku id.
	this.repopulateAll = function(){
		this.repopulateColors(getElement(this.productId+this.displaySku+this.cart+ "colors"));
		this.repopulateSizes(getElement(this.productId+this.displaySku+this.cart + "sizes"));	
		this.repopulateId(document["frm"+this.productId+this.displaySku+this.cart].newSkuId);
	}
	
	//Rewrites the HTML code of given element with currently available color list and 
	// currently selected color
	this.repopulateColors = function (elem){	
		var htmlStr = "";
		if(this.skuSelector.mSelectedColor != null && this.skuSelector.mAvailableColors.length == 1
			&& this.skuSelector.mAvailableColors[0] == this.skuSelector.mSelectedColor){
					this.colorFlag = true;
					for(var i=0;i<this.colorList.length;i++){
					if(this.colorList[i].colorCode == this.skuSelector.mSelectedColor){
						htmlStr += this.colorList[i].colorName;
					}
					}	
		} else {
			htmlStr = "<select style=\"width:100px\" name=\"colorList\" onchange=\"javascript:setSelectedColor('"+this.productId+"','"+ this.displaySku +"','"+ this.cart+"', this.options[selectedIndex].value)\">";
			htmlStr += "<option>Select Color</option>";
			for(var i=0;i<this.colorList.length;i++){
				if(contains(this.skuSelector.mAvailableColors, this.colorList[i].colorCode)){ 
					if(this.colorList[i].colorCode == this.skuSelector.mSelectedColor){
						this.colorFlag = true;
						htmlStr += "<option value='"+this.colorList[i].colorCode+"' selected>"+this.colorList[i].colorName+"</option>";
					} else {
						htmlStr += "<option value='"+this.colorList[i].colorCode+"' >"+this.colorList[i].colorName+"</option>";
					}
				}	
			}
			htmlStr += "</select>";
		}
		if(elem!==null && typeof elem !== 'undefined'){
		  elem.innerHTML = htmlStr;
	        }
	}
	
	
	//Rewrites the HTML code of given element with currently available size list and 
	// currently selected size
	this.repopulateSizes = function(elem){
		var htmlStr= "";
		if(this.skuSelector.mSelectedSizeName != null && this.skuSelector.mAvailableSizes.length == 1
			&& this.skuSelector.mSelectedSizeName == this.skuSelector.mAvailableSizes[0]){
			htmlStr += this.skuSelector.mSelectedSizeName;
		} else{
			htmlStr = "<select style=\"width:100px\" name=\"sizeList\" onchange=\"javascript:setSelectedSize('"+this.productId+"','"+ this.displaySku +"','"+ this.cart+"', this.options[selectedIndex].text)\">";
			htmlStr += "<option>Select Size</option>";
			
			for(var i=0;i<this.skuSizeArray.length;i++){
				if(contains(this.skuSelector.mAvailableSizes, this.skuSizeArray[i])){ 
					if(this.skuSizeArray[i] == this.skuSelector.mSelectedSizeName){				
						htmlStr += "<option selected>"+this.skuSizeArray[i]+"</option>";
					} else {
						htmlStr += "<option >"+this.skuSizeArray[i]+"</option>";
					}
				}
			}
			htmlStr += "</select>";
		}
		if(elem!==null&& typeof elem !== 'undefined'){
		  elem.innerHTML = htmlStr;
	        }
	}
	
	 

	
	//Rewrites the HTML code of given element with currently selected sku id
	this.repopulateId = function(elem){	
		if(typeof elem !== 'undefined'){
		  elem.value = this.skuSelector.getSelectedSkuId();
		}
	}
	

	this.setSelectedSku = function(pSkuId) {

		this.skuSelector.setSelected(pSkuId);
		this.repopulateAll();
	}


}

function getElement(pElementId){
	return document.all? document.all[pElementId] : document.getElementById(pElementId);
}


function Product(pProductId, pSkuId, pSizeName, pType, pColor, pDisplaySkuId, pCart) {
		this.id = pProductId;
		this.skuId = pSkuId;
		this.color = pColor;
		this.type = pType;
		this.sizeName = pSizeName;
		this.displaySku = pDisplaySkuId;
		this.cart = pCart;
}

function Size(pProductId, pDisplaySkuId, pCart, pSizeName) {
		this.id = pProductId;		
		this.displaySku = pDisplaySkuId;
		this.cart = pCart;
		this.sizeName = pSizeName;
}

function Color(pProductId, pDisplaySkuId, pCart, pColorCode, pColorName) {
		this.id = pProductId;		
		this.displaySku = pDisplaySkuId;
		this.cart = pCart;
		this.colorCode = pColorCode;
		this.colorName = pColorName;
}


function Sku(pSkuId, pColor, pType, pSizeName) {
		this.skuId = pSkuId;
		this.color = pColor;
		this.type = pType;
		this.sizeName = pSizeName;
}

var productSelectorArray = new Array();

function getProductSelector(pProductId, pDisplaySku, pCart){
	for(var i=0;i<productSelectorArray.length;i++){		
		if(productSelectorArray[i].productId == pProductId 
				&& productSelectorArray[i].displaySku == pDisplaySku
				&& productSelectorArray[i].cart == pCart){			
			//alert("inside");
			return productSelectorArray[i];
		}
	}
	productSelectorArray.push(new ProductSelector(pProductId, pDisplaySku, pCart));	
	return productSelectorArray[productSelectorArray.length - 1];
	
}

//Initializes the SkuSelector with the given list and populates size types, colors, sizes and sku id.
function initialize(pProductList, pSkuSizeArray, pColorList){	
	this.productList = pProductList;
	this.skuSizeArray = pSkuSizeArray;
	this.colorList = pColorList;

	//alert("inside intialize....mSkuSizeListArray...." + mSkuSizeListArray);
	for(var i=0;i<this.productList.length;i++){
		var productSelector = getProductSelector(this.productList[i].id, this.productList[i].displaySku, this.productList[i].cart);		
		productSelector.addSku(new Sku(this.productList[i].skuId, this.productList[i].color, this.productList[i].type, this.productList[i].sizeName));		
	}

	for(var i=0;i<this.skuSizeArray.length;i++){
		var productSelector = getProductSelector(this.skuSizeArray[i].id, this.skuSizeArray[i].displaySku, this.skuSizeArray[i].cart);		
		productSelector.addSize(this.skuSizeArray[i].sizeName);		
	}
	
	for(var i=0;i<this.colorList.length;i++){
		var productSelector = getProductSelector(this.colorList[i].id, this.colorList[i].displaySku, this.colorList[i].cart);		
		productSelector.addColor(this.colorList[i]);		
	}
	
	for(var j = 0; j<productSelectorArray.length;j++){
		productSelectorArray[j].initialize();		
	}
}

function setSelectedColor(pProductId, pDisplaySku, pCart, pColorCode){
	var productSelector = getProductSelector(pProductId, pDisplaySku, pCart);
	if(productSelector != null){
		productSelector.setSelectedColorCode(pColorCode);
	}	
	handleUpdate(pProductId, pDisplaySku, pCart);	
}

function setSelectedSize(pProductId, pDisplaySku, pCart, pSizeName){
	var productSelector = getProductSelector(pProductId, pDisplaySku, pCart);
		if(productSelector != null){
			productSelector.setSelectedSizeName(pSizeName);
	}	
	handleUpdate(pProductId, pDisplaySku, pCart);
}


function hasChanged(origSkuId, origQty, newSkuId, newQty){
	if(newSkuId == "null" || newSkuId == ""){
		return "invalid";
	}

	if(origSkuId != newSkuId){
		return "true";
	}
	if(origQty != newQty){
		return "true";
	}

	return "false";
}

//function to alter/prepare the style of update functionality.
function prepareUpdateStyle(origSkuId, origQty, newSkuId, newQty, updateElem, pCart, frmName){	
	var flag = hasChanged(origSkuId, origQty, newSkuId, newQty);
	if(pCart=="bag"){
		if(flag == "true" || flag == "invalid"){		
			updateRequired = true; //global value set 
		}
	}

	if(flag == "true"){			
		updateElem.innerHTML = "<a href=\"#\" onclick=\"javascript:document['"+frmName+"'].submit();\">Update</a>";		
	} else if(flag == "invalid"){
		updateElem.innerHTML = "<span style=\"background-color:CCCCCC\"><a>Update</a></span>";		
	//Code Modifeied for trac 1155.
	} else {
		updateElem.innerHTML = "<a href=\"#\" onclick=\"javascript:document['"+frmName+"'].submit();\">Update</a>";
	}
	//End of code modified for trac 1155.
}

//function to take care of updating either cart or wishlist dependin upon the commerceItem/giftlistItem
function handleUpdate(pProductId, pDisplaySku, pCart){
 try{  
	var frmElem = document["frm" + pProductId + pDisplaySku + pCart];	
	if(pCart=="bag")
		return prepareUpdateStyle(frmElem.oldSkuId.value, frmElem.origQty.value, frmElem.newSkuId.value, frmElem[frmElem.commerceItemId.value].value, getElement(pProductId+pDisplaySku+pCart+ "update"), pCart, "frm" + pProductId + pDisplaySku + pCart);
	else 
		return prepareUpdateStyle(frmElem.oldSkuId.value, frmElem.origQty.value, frmElem.newSkuId.value, frmElem[frmElem.giftlistItemId.value].value, getElement(pProductId+pDisplaySku+pCart+ "update"), pCart, "frm" + pProductId + pDisplaySku + pCart);
	}catch(e){}
}

Event.observe(window, 'load', function(ev){
  $$('.shopping-bag-items #cart-prodInfo-status p.unavailable').each(function(cartitem){
    if(typeof cartitem !== 'undefined' && cartitem !== null){
       $$('.nopaypal').each(function(f){
         f.hide();
       });    
    }
  });
});

