//**********************************************************************
//
// Object structure defination
// 
// Objects in multidementional structure: products -> product -> colors -> sizes.
// 
// Each objects has it own operational functions.
//
//**********************************************************************

// This object provide the top level structure to hold products.
// Each productList element is a product.
//

function productsObj (n) {

	this.productList = new Array(n);
	
	this.updateByColor = updateByColor;
	
	this.updateByColorAndSize = updateByColorAndSize;
	
	this.updateQuantity = updateQuantity;
	
	this.Add2ShopCart = Add2ShopCart;
		
	this.toString = productsToString;
}

// This object is product.
// Each each colorList element is color. 
//
function productObj (styleIdProductId, styleId, n) {

	this.productShortDesc = "";					// Product short description.
	
	this.userSelectedSizeId = null;				// User actually click and select a size value at anytime store the size Id here. This change as user change size.
												// Another word this is the user clicked size and not the pre-selected size.
	
	this.styleIdProductId = styleIdProductId;  	// Unique id for this product use in this javaScript object structure.
	this.styleId = styleId;
	this.colorList = new Array(n);
	
	this.lastSelectedColor = null;				// This track the last color the user selected.
	this.lastSelectedSize = null;				// This keep track the user last selected size Object use for presistent logic part.
	
	this.buyQty = 1;							// This store user buy quantity value.
	
	this.updateUserSelectedSizeId = updateUserSelectedSizeId;
	
	this.toString = productToString;
}

// This object is color.
// Each each sizeList element is size. 
//
function colorObj (colorId, n) {

	this.colorId = colorId;
	this.sizeList = new Array(n);

	this.findSizeByColorAvailableSize = findSizeByColorAvailableSize;
	
	this.findLastSizeByColor = findLastSizeByColor;
	
	this.updateColorSizeToSelectedSize = updateColorSizeToSelectedSize;
	
	this.resetColorSizeIsSelectedStatus = resetColorSizeIsSelectedStatus;
	
	this.toString = colorToString;
}

// This object is size.
// 
function sizeObj (sizeId, isAvailable, catentryId, availQty, isSelectedSize) {

	this.sizeId = sizeId;
	this.isAvailable = isAvailable;
	this.catentryId = catentryId;
	this.availQty = availQty;
	
	this.isSelectedSize = isSelectedSize;
	
	this.toString = sizeToString;
}
//this obj is minicart
function minicartObj(mcarrylength,cookieCatentryId,cookieQuantity) {

	this.cookieCatentryId = cookieCatentryId;
	this.cookieQuantity = cookieQuantity;
	
}

var minicartList = new Array(0);

//**********************************************************************
//
// Structure functon defination
//
//**********************************************************************

// This function update the tracking structure when user change color.
//
function updateByColor(thisColorElement, sizePos, styleIdProductId, colorId) {

	function getProduct (pl, sidpid) {
    	for (var i = 0; i < pl.length; ++i) {
        	if (pl[i].styleIdProductId == sidpid) {
            	return pl[i];
            }
        }
        return false;
    }
    
    function getColor (cl, cid) {
    	for (var j = 0; j < cl.length; ++j) {
        	if (cl[j] && cl[j].colorId == colorId) {
            	return cl[j];
            }
        }
        return false;
    }
    
    function getSizeFromColor (cl) {
        var ret = false;
        ret = cl.lastSelectedSize;
        return ret;
    }
    //clear error messsages
    $(thisColorElement).parent().siblings("div.ItemsizeDescWrapper").find("div.errorMessages").css("visibility","hidden");
	$(thisColorElement).parent().siblings("div.qty_wrapper").find("div.errorMessages").css("visibility","hidden");
	// Find the correct product, color and size in the array.
    
    var product = getProduct(this.productList, styleIdProductId);
	
	if (product) {
    	
        var color = getColor(product.colorList, colorId);
        
        if (color) {
        	// Color found.
            
            // If last selected size has value, then select the current color with same size, iff the size is available for this color.
            var lastSelectedSizeId = null;
            
            if (product.userSelectedSizeId) {
            	lastSelectedSizeId = product.userSelectedSizeId;
            } else if (product.lastSelectedSize) {
            	lastSelectedSizeId = product.lastSelectedSize.sizeId;
            }
            
            var currentSelectedSizeObj = null;
            
            if(lastSelectedSizeId != null) {
            
            	// No most current user selected size id was found.
                // Find out if last selected size is available in the current selected color.
                currentSelectedSizeObj = color.findSizeByColorAvailableSize(lastSelectedSizeId);
                
                if (currentSelectedSizeObj != null) {
                	// Found it.  Reset and update the current color size to indicate it is now the most recent selected size.
                    color.resetColorSizeIsSelectedStatus();
                    color.updateColorSizeToSelectedSize(lastSelectedSizeId);
                } else {
                	// Not size availble found in this color.
                    // Find out if the original selected size in this color is available.
                    currentSelectedSizeObj = color.findLastSizeByColor();
                }
                
            } else {
            	// Empty lastSelectedSize mean that there were no size for that last color or size selected by the user.
				// Find out from this color where the last selected size is and assign to lastSelectedSize.
				currentSelectedSizeObj = color.findLastSizeByColor();
            }
            
            // Update size.
            if (currentSelectedSizeObj != null) {
            	// Update productObj last selected size.
                product.lastSelectedSize = currentSelectedSizeObj;
                
                // Now update the UI CSS selection to remove the pre-selected size value from FRY original code.
                // This is vitual view only for the frontend.
                var sizeLists = $(thisColorElement).parent().siblings('div:first').find('ul');
                
                $(sizeLists).removeAttr('class');
                
                $(sizeLists).find('li').each(function () {
                    if (product.lastSelectedSize.sizeId == $(this).find('span').children().text() && !$(this).hasClass('unavailable')) {
                        $(this).parent().addClass('current-sizes').siblings('.current-sizes').removeClass('current-sizes');
                        $(this).addClass('selected-size').siblings('.selected-size').removeClass('selected-size');
                    }
                });
            }
        }
        // Update to current selected color
        product.lastSelectedColor = colorId;
    }
    
    //debug("In updateByColor: \n\n " + this.toString());
	// update the color label with the alt text from the color image
    var color_options = $(thisColorElement).parent().children("li");
    var colorLabel = thisColorElement.getElementsByTagName("img")[0].alt;
    var colorLabelWrapper = thisColorElement.parentNode.parentNode.getElementsByTagName("span")[0];
    colorLabelWrapper.innerHTML = colorLabel;
    // update the viewable available sizes
    var sizeWrapper = $(thisColorElement).parent().siblings('div.item_size_wrapper')[0];
    var sizeLists = $(sizeWrapper).children('ul');
    $(sizeLists).each(function () {
    	$(this).removeAttr('class');
    });
    var i = parseInt( $(thisColorElement).attr('rel'), 10);
    sizeLists[i].className = 'current-sizes';
    /*
    var currentList = $(".current-sizes", sizeWrapper);
    var currentSize = $(".selected-size", currentList);
    var sizeValue = $("span", currentSize)[0].firstChild.nodeValue;
    var inputField = $("input", sizeWrapper)[0];
    $(inputField).attr("value", sizeValue);
    */
    // update the price per color
    var detailWrapper = thisColorElement.parentNode.parentNode.parentNode.getElementsByTagName("div")[0];
    var priceWraper = detailWrapper.getElementsByTagName("ul")[0];
    var thePrices = priceWraper.getElementsByTagName("li");
    var totalPrices = thePrices.length;
    for(var p = 0; p<totalPrices; p++) {
    	thePrices[p].className = '';
    }
    thePrices[i].className = 'current_price';
    // determine to show message if item is not part of sale
    var nonsaleMessageArea = thisColorElement.parentNode.parentNode.getElementsByTagName("span")[1];
    if($(thisColorElement).hasClass("not_part")) {
    	var itemAmt = thePrices[i].getElementsByTagName("p")[0].firstChild.nodeValue;
        var theMessage = "Selected color is not on sale. Price is " + itemAmt;
        nonsaleMessageArea.innerHTML = theMessage;
        nonSalesItem = "true";
    } else {
    	nonsaleMessageArea.innerHTML = " ";
        nonSalesItem = "false";
    }
    if($(thisColorElement).hasClass("is_part")) {
    	var itemAmt = thePrices[i].getElementsByTagName("p")[0].childNodes[0].firstChild.nodeValue;
        var itemRegAmt = thePrices[i].getElementsByTagName("p")[0].childNodes[2].firstChild.nodeValue;
        var theMessage = "Selected color is on sale. Price is " + itemAmt + " reg " + itemRegAmt;
        nonsaleMessageArea.innerHTML = theMessage;
        nonSalesItem = "true";
    } else {
    	nonsaleMessageArea.innerHTML = " ";
        nonSalesItem = "false";
    }

    // update image
	var productWrapper = thisColorElement.parentNode.parentNode.parentNode.parentNode.getElementsByTagName("div")[0];
	var imageWrapper = $(productWrapper).hasClass('item-image-area') ? $(productWrapper).children('div') : $('ul.image_wrapper').children('li');
	var totalImages = imageWrapper.length;
	
	for (var t = 0; t < totalImages; t++) {
		
		$(imageWrapper[t]).removeClass("current-image");
		var me = $(imageWrapper[t]).next();
		if($(me[0]).hasClass('current-online-image')){
			$(me[0]).removeClass("current-online-image");
		}
		if (t==i) {
			$(imageWrapper[t]).addClass("current-image");
			var nn = $(me[0].nodeName);
			if($(me[0].nodeName == "SPAN")){
				$(me[0]).addClass("current-online-image");
			}
			
		}
	}

	// Update the product Id
	setProductId ();
	// update select color box
	$(color_options).removeClass("item_current-color");
	$(thisColorElement).addClass("item_current-color");
}

function checkLineItemQuantity(buyQty,LineLimitQuantity){
	
	var item_qty = 0;
	var lmt_qty=0;
	item_qty = parseInt(buyQty);
	lmt_qty=parseInt(LineLimitQuantity);
	if(item_qty > lmt_qty){
		return false;
	}
	return true;
}

// This funciton add product to cart
// submitType: 	0 - single product detail page submit.
//				1 - multiproduct page submit.
//
function Add2ShopCart(fm, submitType, LineLimitQuantity, alertMsg){
 
	var catentryIdList = "";
	var quantityList = "";
	var styleIdList = "";
	var selectedItemCount = 0;
	var processedItemCount = 0;
	var selectedItemNotAvailableCount = 0;
	var groupItemNotAvailableMsg = "";

	var appendComma = false;
	
	var msgItemNotAvailable = "not available in the quantity you requested";
	var SelSizeMsg = "Please select a size.";
	var msgOutOfStock = "out of stock";
	
	var submitFormCheck = true;
    
    var productList = this.productList;
	//refresh minicart
    buildQtyInMinicart();
    function getIndexByStyleIdProdId (sidpid) {
    	for (var i = 0; i < productList.length; i++) {
        	if (sidpid == productList[i].styleIdProductId)
            	return i;
        }
        return false;
    }
	var errorMsg = false;
	
    if (submitType == '0') {
        var prod = productList[0];
        selectedItemCount++;

		var inputQtyWrapper = $(fm).find("#qty_wrapper").find("#itm_qty_wrapper").find('dl:first').find('dd:first').find('select:first');
		
		if (prod.lastSelectedSize != null) {
		
			if (inputQtyWrapper.attr('name') == 'quantity') {
			
	        	if (!isValidQty(inputQtyWrapper.val())) {
	            	errorMsg=true;
	                return;
	            } 
				else {
	           		
	            	var inputQty=  inputQtyWrapper.val();
	            	var lastBuyQty=prod.buyQty;
	            	prod.buyQty=inputQty;
	            	if(checkQtyExceedMiniCart(prod.lastSelectedSize.catentryId)>15){
	                	errorMsg=true;
						$(inputQtyWrapper).parent().parent().parent().siblings("#errorMessages").find("#errorMid").text("max limit 15 reached");
			            $(inputQtyWrapper).parent().parent().parent().siblings("#errorMessages").css("visibility", "visible");
			          	prod.buyQty=lastBuyQty;
			            return;
		            }else{
		            	prod.buyQty=inputQty;
		            	}
				}
			}
            if (prod.userSelectedSizeId==null || prod.userSelectedSizeId=='') {
		        $("#ItemsizeDescWrapper").find("#errorMessages").find("#errorMid").text("Please select a size");
            	$("#ItemsizeDescWrapper").find("#errorMessages").css("visibility", "visible");
		        errorMsg=true;
		        return;
		    }
            //alert("Before calling the line item method");
		//	if(!checkLineItemQuantity(prod.buyQty, LineLimitQuantity)){
		//		alert(alertMsg);
		//		return;
		//	}
			//end
            if (parseInt(prod.lastSelectedSize.availQty) == 0) {
            	groupItemNotAvailableMsg += "\nItem: " + prod.productShortDesc + " - " + msgOutOfStock;
                ++selectedItemNotAvailableCount;
            }
            if (parseInt(prod.lastSelectedSize.availQty) < parseInt(prod.buyQty)) {
            	groupItemNotAvailableMsg += "\nItem: " + prod.productShortDesc + " - " + msgItemNotAvailable;
                ++selectedItemNotAvailableCount;
            }
            if (appendComma == true){
            	catentryIdList += ",";
                quantityList += ",";
                styleIdList += ",";
            }
			if(prod.lastSelectedSize != null && prod.lastSelectedSize.catentryId!=null){
				catentryIdList += prod.lastSelectedSize.catentryId;
				quantityList += prod.buyQty;		// Note that this value is actually come from the same value as the user see at the last movement of submit getting in above  logic.
				styleIdList += prod.styleId;
				appendComma = true;
				++processedItemCount;
			}
        } else {
				//groupItemNotAvailableMsg += "\nItem: " + prod.productShortDesc + " - " + msgOutOfStock;
				//++selectedItemNotAvailableCount;
	            var errmsgdiv=$(document).find("#ItemsizeDescWrapper").find("#errorMessages");
            	errmsgdiv.css("visibility", "visible");
            	var errmiddiv=errmsgdiv.find("#errorMid").text("Please select a size");
            	errorMsg=true;
				return;
		}
    } else if (submitType == '1') {
    	
		$(fm).find('input:checked').each(function () {
    		var index = getIndexByStyleIdProdId($(this).attr('name'));
	        if (index >= 0) {
        		var prod = productList[index];
            	selectedItemCount++;
	            if (prod.lastSelectedSize != null) {
            		var inValidQtyMsg = "Please enter valid quantity for item: " + prod.productShortDesc;
	                if (submitType == '1') {
						var inputQtyWrapper = $(this).parent().parent().find('dl:first').find('dd:first').find('select:first');
						
						if (inputQtyWrapper.attr('name') == 'qty') {
						
	                    	if (!isValidQty(inputQtyWrapper.val())) {
	                        	alert(inValidQtyMsg);
	                            return;
	                        } 
							else {
	                        	var inputQty=  inputQtyWrapper.val();
	                        	var lastBuyQty=prod.buyQty;
	                        	prod.buyQty=inputQty;
	                        	if(checkQtyExceedMiniCart(prod.lastSelectedSize.catentryId)>15){
		                        	errorMsg=true;
									$(inputQtyWrapper).parent().parent().parent().siblings("#errorMessages").find("#errorMid").text("max limit 15 reached");
						            $(inputQtyWrapper).parent().parent().parent().siblings("#errorMessages").css("visibility", "visible");
						           prod.buyQty=lastBuyQty;
						            return;
					            }else{
					            	prod.buyQty=inputQty;
					            	}
							}
						}
                	}
                	// else if (submitType == '0') {
                	//	var quantity = document.getElementsByName("quantity")[0].value;	
					//	prod.buyQty = quantity;
                	//}
	                
					// End speical condition for qty check above.
					if (prod.userSelectedSizeId==null || prod.userSelectedSizeId=='') {
		            	var divIdforcss=$(this).parent().parent();
		            	var errmsgdiv=divIdforcss.find("#ItemsizeDescWrapper").find("#errorMessages");
		            	errmsgdiv.css("visibility", "visible");
		            	var errmiddiv=errmsgdiv.find("#errorMid").text("Please select a size");
		            	errorMsg=true;
		                return;
		            }
					// Validate qty.				
				//if (!isValidQty(prod.buyQty)) {
				//alert(inValidQtyMsg);
				//return;
				//}
					
					//Changes made for multi product page
		//	if(!checkLineItemQuantity(prod.buyQty, LineLimitQuantity)){
		//		errorMsg = true;
		//		return;
		//	}
					//end
						
					if (parseInt(prod.lastSelectedSize.availQty) == 0) {
                		groupItemNotAvailableMsg += "\nItem: " + prod.productShortDesc + " - " + msgOutOfStock;
						++selectedItemNotAvailableCount;
                	}
					
					// Validate qty verse available qty.
					if (parseInt(prod.lastSelectedSize.availQty) < parseInt(prod.buyQty)) {
					groupItemNotAvailableMsg += "\nItem: " + prod.productShortDesc + " - " + msgItemNotAvailable;
					++selectedItemNotAvailableCount;
				}
		
					// Append comma only in this format: [a, b, c,....,z] where a-z can be any number or char string.  Only and skip last comma.
					if (appendComma == true){
					catentryIdList += ",";
					quantityList += ",";
					styleIdList += ",";
				}
					
					if(prod.lastSelectedSize != null && prod.lastSelectedSize.catentryId!=null){
					catentryIdList += prod.lastSelectedSize.catentryId;
					quantityList += prod.buyQty;		// Note that this value is actually come from the same value as the user see at the last movement of submit getting in above  logic.
					styleIdList += prod.styleId;
					appendComma = true;
					++processedItemCount;
					}			
				} else {
					//groupItemNotAvailableMsg += "\nItem: " + prod.productShortDesc + " - " + msgOutOfStock;
				//	++selectedItemNotAvailableCount;

					$(this).parent().parent().find("#ItemsizeDescWrapper").find("#errorMessages").find("#errorMid").text("Please select a size.");
					$(this).parent().parent().find("#ItemsizeDescWrapper").find("#errorMessages").css("visibility", "visible");
		            errorMsg=true;
					return;
				}
        	}
    	});
    	
    	
    }
    
  
	
	// No item was checked
	if (selectedItemCount == 0){
	
		alert("Please check item Add to Bag checkbox to add to bag");
		return;
	}	
	
	// Item not availlable.
	if(selectedItemNotAvailableCount > 0){

		alert("Sorry, the item you tried to add to your shopping bag is either out of stock or not available in the quantity you requested." 
				+ "\n" + groupItemNotAvailableMsg);
		return;	
	}
	
	// Build submit form.
	fm.catEntryId.value = catentryIdList;
	fm.quantity.value = quantityList;
	fm.addCatID.value = styleIdList;
	fm.numOfProducts.value = processedItemCount;
	
	// Single product submit.
	if(!errorMsg){
	if (submitType == '0')
	{
		fm.action='TCPOrderItemAdd';
		fm.URL.value='OrderItemDisplay';
	}
	
	addHREF = $('#addLink').attr("href");
	$("#addLink").removeAttr('href');
	$("#addImg").attr("src", "//content.childrensplace.com/www/b/TCP/assets/buttons/btn_addToBag_Grey.gif");
	$("#addButton1").attr("disabled", true);
	$("#addButton1").attr("src", "//content.childrensplace.com/www/b/TCP/assets/buttons/btn_addCheckedItemsToBag_G.gif");
	$("#addButton2").attr("disabled", true);
	$("#addButton2").attr("src", "//content.childrensplace.com/www/b/TCP/assets/buttons/btn_addCheckedItemsToBag_G.gif");
		
	if (isShoppingCart=="true")
	{
		//fm.URL.value='ShoppingCartDisplayView';
		fm.submit();
	}
	else
	{
		// START build cookies
		
		var minicartUrl = "MinicartView";
		var orderId = fm.orderId.value;
		url = fm.action +
			  "?storeId=10001&catalogId=10001&langId=-1" +
			  "&catEntryId=" + catentryIdList +
			  "&quantity=" + quantityList +
			  "&addCatID=" + styleIdList +
			  "&numOfProducts=" + processedItemCount +
			  "&orderId=" + orderId +
			  "&URL=" + minicartUrl;
		
		var layerDiv = document.getElementById("outfit_layer");
		if (layerDiv)
		{
			$('#outfit_layer').remove();
			$('#disable_body_layer').remove();
			$("#refinements_controls > dl > dd > select").css("visibility", "visible");
			$("#category-sort > dd > select").css("visibility", "visible");
			$('body').removeClass('popup');
			window.scrollTo(0,0);
		}
		
		updateCart(url);
		buildQtyInMinicart();
	}	
	}
}

	function updateCart(url)
	{
		$("#confirmation").load(url ,function()
		{
			getMinicartContent(); 
		});
	}

	function getMinicartContent()
	{
		getOffsetValue(document.getElementById("confirmation"));
		if (document.getElementById("errorConf"))
		{
			var content = document.getElementById("errorConf").innerHTML;
			//alert('content = ' + content);
			if(content.trim().length > 0)
			{
				$("#errorMsg").css("display","block");
				$("#errorMsg").html("");
				$("#errorMsg").append(content);
			}
		}
		
		isShowConf = true;
		buildMinicart();
		$("#minicartWrap").css("display","none");
		$("#confirmation").css("display","block");
		$("#minicart").css("display","block");
		updateShoppingLine();
		window.scrollTo(0,0);
		window.setTimeout('hideConfirmation(0)', 5000);
	}
	
	function disableButtonClick(){
	
		$(".buttonRemove").removeAttr('href');
	}
	
	function buildConfirmationFooter(){
		var minicartcookievalue = Get_Cookie('minicartcookie');
		if (minicartcookievalue != null)
		{   
			var cookieArray = minicartcookievalue.split("#");
			document.getElementById('total_item').innerHTML = '<b>' + cookieArray[cookieArray.length-1].split("|")[0] + ' item(s)</b>';
			document.getElementById('sub_total').innerHTML = '<b>' + cookieArray[cookieArray.length-1].split("|")[1] + '</b>';
			var promoButtonImg = '<a href="${shoppingCartURL}"><img src="${baseHREF}assets/images/minicart/viewedit_cart.gif"/></a>';
			var coutButtonImg = '<a href="javascript:hCheckout();"><img src="${baseHREF}assets/images/minicart/checkout_cart.gif"/></a>';
			$('#promoButton').html(cartButtonImg); 
			$('#coutButton').html(coutButtonImg);
			
			showGWPMessage();
		}
	} 	
	
	function showGWPMessage(){  
		var gwpItemsCookieValue = Get_Cookie("gwpItemsCookie");
		if(gwpItemsCookieValue!=null){ 
			//undecided#478207#nice jeans get all#480060|
			var itemDescs = gwpItemsCookieValue.split("|");
	   		var description = "";
	   		for (var i = 0; i < itemDescs.length-1; i++){
	   		 	 description = itemDescs[i];
	   		 	 document.getElementById('gwpMessage').innerHTML = '<b>' + 'You\'ve earned a FREE ' + description + '</b>';
	 	   	}
		
		   //document.getElementById('gwpMessage').style.visibilty = "visible";
	   	}
	}
	 
	function hideConfirmation(close)
	{
		if (!lockConf || close == 1)
		{
			//$("#minicart").slideUp(200)
			$("#minicart").css("display","none");
			$("#confirmation").css("display","none");
			$("#minicartWrap").css("display","block");
			isShowConf = false;
			lockConf = false;
		}
	}

	function closeOutfitLayer()
	{
		$('#outfit_layer').remove();
		$('#disable_body_layer').remove();
		$("#refinements_controls > dl > dd > select").css("visibility", "visible");
		$("#category-sort > dd > select").css("visibility", "visible");
		$('body').removeClass('popup');
	}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, '');
};

// This function update sizeid to a color.
//
function updateByColorAndSize(styleIdProductId, colorId, sizeId,li_id){

	//refresh minicart
   // buildQtyInMinicart();
    
	function getProduct (pl, sidpid) {
    	for (var i = 0; i < pl.length; i++) {
        	if (pl[i].styleIdProductId == sidpid) {
            	return pl[i];
            }
        }
        return false;
    }
    
    function getColor (cl, cid) {
    	for (var i = 0; i < cl.length; i++) {
        	if (cl[i].colorId == cid) {
            	return cl[i];
            }
        }
        return false;
    }
    
	// Find the product in the list.
	var product = getProduct(this.productList, styleIdProductId);
    
	$(li_id).parent().parent().siblings("div.ItemsizeDescWrapper").find("div.errorMessages").css("visibility","hidden");
	$(li_id).parent().parent().siblings("div.qty_wrapper").find("div.errorMessages").css("visibility","hidden");
    if (product) {
    	
        var color = getColor(product.colorList, colorId);
        
        if (color) {
		
            // Color found. Check if the size is available to be selected for this color.
            
            var currentSelectedSizeObj = color.findSizeByColorAvailableSize(sizeId);
            
            if (currentSelectedSizeObj != null) {
                // Found size is available to be selected for this color.
                
                // Keep track of the initial selected with new selected size value.
                // The initial selected size is either marked as first page load or when user selected it.
                
                color.resetColorSizeIsSelectedStatus();
                color.updateColorSizeToSelectedSize(sizeId);
                
                // Keep track of what being selected in product level and that will be used for final sumbit of the form later.
                product.lastSelectedColor = colorId;
                product.lastSelectedSize = currentSelectedSizeObj;
                
                // No need to update the UI CSS selection to remove the pre-selected size value from FRY original code.
                // FRY original code is working correctly to highlight the user wanted size.
                // Keep track of the user wanted size in product level and it will be used to first check for the user wanted size if available when user switch color.
                
                product.updateUserSelectedSizeId(sizeId);
                
            }
            
            for (var i = 0; i < product.colorList.length; i++) {
            	var currentSelectedSizeObj = product.colorList[i].findSizeByColorAvailableSize(sizeId);
                if (currentSelectedSizeObj != null) {
 		                	product.colorList[i].resetColorSizeIsSelectedStatus();
		                    product.colorList[i].updateColorSizeToSelectedSize(sizeId);
		                    currSizeList=product.colorList[i].sizeList;
		                    
		                    var chkboxobj=$(li_id).parent().parent().siblings('label.options_label').find('input:checkbox');
									if(chkboxobj!=null && chkboxobj.attr('id')=="add2cartCheckbox"){
									chkboxobj.removeAttr('checked');
									$(li_id).parent().parent().siblings('label.options_label').find('input:checkbox').click();
									}
               }
            }
		}
	}
}

// This function update the product buy quantity, if available.
//
function updateQuantity (styleIdProductId, buyQty, obj){

	//refresh minicart
    buildQtyInMinicart();
	// Check for buyQty is number or greater than 1;
	if(!isValidQty(buyQty)){

		alert("Please enter valid quantity");
		obj.focus();
		obj.select();
		
		return;
	}

	
	// Find the product in the list.
	for (var i = 0; i < this.productList.length; ++i){
		
		$(obj).parent().parent().parent().siblings("#errorMessages").css("visibility", "hidden");
		
		
		if(this.productList[i].styleIdProductId == styleIdProductId){
		
			// Found the product.
			var outOfStockMsg = "Sorry, the item you tried to add to your shopping bag is either out of stock or not available in the quantity you requested.";
			
			if(this.productList[i].lastSelectedSize != null){
			
				//debug(this.productList[i].lastSelectedSize.availQty + " >= " + buyQty);
				
				var lastBuyQty=this.productList[i].buyQty;
				this.productList[i].buyQty = buyQty;
				var TotqtyInMinicart=checkQtyExceedMiniCart(this.productList[i].lastSelectedSize.catentryId);
				
				if(TotqtyInMinicart>15){
					this.productList[i].buyQty = lastBuyQty;
					$(obj).parent().parent().parent().siblings("#errorMessages").find("#errorMid").text("max limit 15 reached");
	            	$(obj).parent().parent().parent().siblings("#errorMessages").css("visibility", "visible");
				}
					
				if( this.productList[i].lastSelectedSize.isSelectedSize==false){
				if (this.productList[i].userSelectedSizeId==null || this.productList[i].userSelectedSizeId.userSelectedSizeId=='') {
	            	$(obj).parent().parent().parent().parent().siblings("#ItemsizeDescWrapper").find("#errorMessages").find("#errorMid").text("Please select a size");
	            	$(obj).parent().parent().parent().parent().siblings("#ItemsizeDescWrapper").find("#errorMessages").css("visibility", "visible");
            	}
				/*
				if(parseInt(this.productList[i].lastSelectedSize.availQty) >= parseInt(buyQty)){
				
					// Update buying quantity.
					this.productList[i].buyQty = buyQty;
					
				}else{
				
					
					alert(outOfStockMsg);
					obj.focus();
					obj.select();
				}
				*/
			
			}
				
				// Quantity not available.
				
				/*
				alert(outOfStockMsg);
				obj.focus();
				obj.select();
				*/
				
			}
			else if(this.productList[i].lastSelectedSize == null){
				$(obj).parent().parent().parent().parent().siblings("#ItemsizeDescWrapper").find("#errorMessages").find("#errorMid").text("Please select a size");
	            $(obj).parent().parent().parent().parent().siblings("#ItemsizeDescWrapper").find("#errorMessages").css("visibility", "visible");
			
			}
			
			return;
		}
	}

	//debug("In updateProductQuantity: \n\n " + this.toString());
}

// This function find out from this color where the last selected or available first selected size is.
//
function findLastSizeByColor(){

	for (var i = 0; i < this.sizeList.length; ++i){
		
		if(this.sizeList[i].isSelectedSize == true){
			return this.sizeList[i];
		}
	}
	return null;
}

// This function find out if the given size id is available to this color.
//
function findSizeByColorAvailableSize(sizeId){

	for (var i = 0; i < this.sizeList.length; ++i){
		
		if(this.sizeList[i].sizeId == sizeId && this.sizeList[i].isAvailable == true){
			return this.sizeList[i];
		}
	}
	return null;
}

// This function reset the previous selected status to false.
//
function resetColorSizeIsSelectedStatus(){

	for (var i = 0; i < this.sizeList.length; ++i){
		
		this.sizeList[i].isSelectedSize = false;
	}
}

// This function mark the size in this color as selected.
//
function updateColorSizeToSelectedSize(sizeId){

	for (var i = 0; i < this.sizeList.length; ++i){
		
		if(this.sizeList[i].sizeId == sizeId && this.sizeList[i].isAvailable == true){
			this.sizeList[i].isSelectedSize = true;
		}
	}
}

// This function update user initial selected size in product level.
//
function updateUserSelectedSizeId(sizeId){

	this.userSelectedSizeId = sizeId;
}



function checkQtyExceedMiniCart(mccatentryId){
		// Invalid qty set the tracking structure buyQty to zero.

		var tempqty=0;
		if(minicartList.length>0){
			for (var i = 0; i < minicartList.length-1; ++i){
					if(minicartList[i].cookieCatentryId == mccatentryId){
						var tempvar=0;
						if (typeof minicartList[i].cookieQuantity=="string")
							tempvar=parseInt(minicartList[i].cookieQuantity);
						else
							tempvar=parseInt(minicartList[i].cookieQuantity);
						
						tempqty=tempqty+tempvar;
					}
			}
		}
		
		var pl = productsTrack.productList;
		
			//get total eligible qty available to buy .
			for (var i = 0; i < pl.length; i++) {
                if(pl[i].lastSelectedSize!=null && pl[i].lastSelectedSize.catentryId==mccatentryId){
                	var tempvar=0;
                	if (typeof pl[i].buyQty=="string")
						this.tempvar=parseInt(pl[i].buyQty);
					tempqty=tempqty+this.tempvar;
				}
            }
            return tempqty;
}


//validate qty from minicart

	function buildQtyInMinicart(prodcatentryid,prodqty)
	{
		
		var minicartcookievalue = getCookie('minicartcookie');
		if (minicartcookievalue != null)
		{   
			var cookieArray = minicartcookievalue.split("#");
			var mcarrylength=cookieArray.length;
			var cookieCatentryId='';
			var cookieQuantity= '';
			minicartList = new Array(mcarrylength);
			
			for (i = 0; i < cookieArray.length-1; i++)
			{
				var currentMinicart=new minicartObj(cookieCatentryId,cookieQuantity);
				minicartList[i] = currentMinicart;
				iValues = cookieArray[i].split("|");
				var catentryId=iValues[8];
				var arryquantity=iValues[4];
				minicartList[i].cookieCatentryId=catentryId;
				minicartList[i].cookieQuantity=arryquantity;	
			}
			
		}	
	}

	function populateSelectqtyDropdown(fm){
	
	$(fm).find("div.qty_wrapper").find("div.itm_qty_wrapper").find('dl:first').find('dd:first').find('select:first').each(function () {
  	   
		   var select = $(this);
		   var options = $(this).attr('options');  
		   $('option', select).remove();
		   $(this).append('<option value="1" selected="selected">1</option> ');
		   $(this).append('<option value="2" >2</option> ');
		   $(this).append('<option value="3" >3</option> ');
		   $(this).append('<option value="4" >4</option> ');
		   $(this).append('<option value="5" >5</option> ');
		   $(this).append('<option value="6" >6</option> ');
		   $(this).append('<option value="7" >7</option> ');
		   $(this).append('<option value="8" >8</option> ');
		   $(this).append('<option value="9" >9</option> ');
		   $(this).append('<option value="10" >10</option> ');
		   $(this).append('<option value="11" >11</option> ');
		   $(this).append('<option value="12" >12</option> ');
		   $(this).append('<option value="13" >13</option> ');
		   $(this).append('<option value="14" >14</option> ');
		   $(this).append('<option value="15" >15</option> ');
		   
		});
	}
// This function validate a quantity value.
//
function isValidQty(qty){

	var rc = true;
	
	if(!isInteger(qty) || qty <= 0){
	
		rc = false;
	}
	
	return rc;
}

// This function add muiltiProduct page item to wish list.
// Note that current design only allow one product to be added to wish list at a time.
//
function AddToWishListMultiProducts(form, errMsgBadQty, isRegisterUser, styleIdProductId){

	var rc = true;
	
	for (var i = 0; i < productsTrack.productList.length; ++i){
	
		if(productsTrack.productList[i].styleIdProductId == styleIdProductId){
			
			if(productsTrack.productList[i].lastSelectedSize == null){
			 	rc = false;
			 	break;
			}
			
			form.catEntryId.value = productsTrack.productList[i].lastSelectedSize.catentryId;

			// 	This is a speical condition for qty check and IMPORTANT for submit of the right qty:
			// 	Validate qty value format at run time.
			// 	In this case user may update and keep ignore the warning and not to change the value
			// 	and the tracking structure does not get update due to FRY code triger last. 
			//	Drill right into the form and get the quantity value that user see on the page.
			//				
			// For multiproduct submit.
							
			var inValidQtyMsg = "Please enter valid quantity for item: " + productsTrack.productList[i].productShortDesc;
			
			var addToBagElement = document.getElementsByName(productsTrack.productList[i].styleIdProductId)[0];	
			var dlWrapper = addToBagElement.parentNode.parentNode.getElementsByTagName("dl")[0];
			var ddWrapper = dlWrapper.getElementsByTagName("dd")[0];
			var inputQtyWrapper = ddWrapper.getElementsByTagName("input")[0];
			
			if(inputQtyWrapper.name == "qty"){

				if(!isValidQty(inputQtyWrapper.value)){
				
					alert(inValidQtyMsg);
					return;
					
				}else{
				
					productsTrack.productList[i].buyQty = inputQtyWrapper.value;
				}
			}
			
			
			form.quantity.value = productsTrack.productList[i].buyQty;
		}
	}

	if(!rc){
		alert("Sorry, this item can not be added to the wish list");
	}else{
		
		// Reuse the generic add to wish list function.
		AddToWishList(form, errMsgBadQty, isRegisterUser, styleIdProductId);
	}

}

// This function add item to wish list.
//
function AddToWishList(form, errMsgBadQty, isRegisterUser, styleIdProductId)
{
	// Find the product in the list.
	for (var i = 0; i < productsTrack.productList.length; ++i){
	
		if(productsTrack.productList[i].styleIdProductId == styleIdProductId){
			
			if(isEmpty(form.catEntryId.value)){
			
				alert(errMsgBadQty);
				return false;
			}
			
			if(!checnNumeric(form.quantity.value)){
				alert(errMsgBadQty);
				return false;
			}
			
			// Found the product.
			if(productsTrack.productList[i].lastSelectedSize != null){
			
				form.quantity.value = productsTrack.productList[i].buyQty;
				form.catEntryId.value = productsTrack.productList[i].lastSelectedSize.catentryId;

				if (isRegisterUser == 'true'){
				
					form.action='InterestItemAdd';
					form.URL.value='InterestItemDisplay';
					
				}else{
				
					form.action='LogonForm';
					form.URL.value= getNotLoginWishListUrl(form.storeId.value, form.langId.value, form.catEntryId.value, form.catalogId.value, form.quantity.value);
				}
				
				form.submit();
						
			}else{
			
				alert("Sorry, this item can not be added to the wish list");
				
				return false;
			}
			
		}
	}
}

// This function construct a url for none login user to add item to wish list.
//
function getNotLoginWishListUrl(storeId, langId, catEntryId, catalogId, qty){

	return 'InterestItemAdd?storeId='+storeId+'&langId='+langId+'&catEntryId='+catEntryId+'&catalogId='+catalogId+'&quantity='+qty+'&URL=InterestItemDisplay';
}

//**********************************************************************
//
// Defination of function [x]ToString().
// Mostly use for debug purpose.
//
//**********************************************************************

function productsToString(){

	var s = this.productList.toString() + "\n";
	return s;
}

function productToString(){

	var s = "product: " + this.productShortDesc + ", " + this.styleIdProductId + ", styleId=" + this.styleId + ", userSelectedSizeId=" + this.userSelectedSizeId + ", buyQty=" + this.buyQty + "\n lastSelectedColor=" +this.lastSelectedColor + "\n lastSelectedSize= " + this.lastSelectedSize + "\n " + this.colorList.toString() + "\n";
	return s;
}

function colorToString(){

	var s = "colorId: " + this.colorId + ":\n " + this.sizeList.toString() + "\n";
	return s;
}

function sizeToString(){

	var s = "sizeId: " + this.sizeId + ", isAvailable=" + this.isAvailable + ", catentryId=" + this.catentryId + ", availQty=" + this.availQty 
			+ ", isSelectedSize=" + this.isSelectedSize + "\n";
	return s;
}

function debug(s){

	//alert(s);
}

function toggle(carouselId){
	if (typeof(callToggle) != "undefined" ) {
		toggleArrows(carouselId);
	}				
}

// Code for larger image rollovers

function init_enlargeImage(){

	$(document).ready(function() {
	  $(".item-image-area div").hover(function() {
	    if ( $(".imagePopOver").length > 0 ) {
	       $(".imagePopOver").remove();
	    }
	    var imgTag = $(this).html();
	    imgTag = imgTag.replace("width=\"185\"", "width=\"300\"");
	    imgTag = imgTag.replace("height=\"185\"", "height=\"300\"");
	    imgTag = imgTag.replace("width=185", "width=\"300\"");
	    imgTag = imgTag.replace("height=185", "height=\"300\"");
	    //imgTag = imgTag.replace("_m.jpg", "_l.jpg");
	    imgTag = imgTag.replace("class=\"image\"", "");
	    $(this).parent().parent().before("<div class=\"imagePopOver newImagePopOver\">"+imgTag+"</div>");
	
	    // Create the action on mouseout
	    $(".newImagePopOver").hover(function() {
	    // Do nothing
	    },function(){
	    $(this).fadeOut(300);
	    });
	    // Remove the new Class
	    $(".newImagePopOver").removeClass("newImagePopOver");
	  },function(){
	  });
	});
}
var getIndex = function (elem) {
	var ret = false;
    $(elem).parent().children().each(function (i) {
    	if (this == elem) ret = i;
    });
    return ret;
};

