/*
--------------------------------------------------

Casual Male DXL
Site-Wide Developer Scripts [cm.application.js]

Suresh Medavaram [suresh.medavaram@acquitygroup.com]
11/09/2010

Copyright (c) 2008-2010 Acquity Group LLC

--------------------------------------------------
*/

/*
Shipping page related scripts
*/

var skuAttributesString; // This needs to be a global because it's used in multiple
						// functions (and I don't want to refactor this entire file
						// to pass it as a parameter)
						//
						// skuAttributesString is what gets sent to the server as
						// an ajax call that gets the availability of that particu-
						// lar size/color/etc.

/*

function changeAddressType(radio) {
	document.location.href = "shippingAddress_multiple.jsp?addressType=" + radio.value;
}

*/
function popSpinSet(url){
	popUrl(url, 500, 400);
}

function popUrl(url, width, height){
	var newwindow=window.open(url,'name','height='+height+',width='+width);
	if (window.focus) {newwindow.focus()}
}

function changeCountry(country) {
	document.shippingAddress.reference.value="true";
	//document.shippingAddress.submit();
	$('#checkout-continue').click();
}

function setFormValues(submitVal) {
	document.shippingAddress.nickname.value = document.shippingAddress.address1.value;
	document.shippingAddress.submit();

}

function assignShipToAddressName() {
	var selVal = document.getElementById("selectshipToAddressName");
	var selOption = selVal.options[selVal.selectedIndex].value;
	document.shippingAddress.txtShipToAddressName.value = selOption;
}

function submitOthers(value)
{
	/*
	var cIds = value.split( "," );
	var cId = "";
	for ( var i = 0; i < cIds.length; i++ )
	  {
	    cId = cIds[ i ];
	    document.getElementById(cId).submit();
	  }
	*/
	documentshipAddressMultiple.submit();
	document.multipleShipping.submit();


}

function setCids() {

	var cIds = document.multipleShippingAddr.myCommerceItemIdsToMove;
	var cIds1 = document.multipleShippingAddr.commerceItemIdsToMove;
	//alert("length >> " + cIds.length);
	//alert("addrNames length >> " + cIds1.length);
	for (i=0; i<cIds.length;i++) {
		//alert("before " + cIds[i].value);
		cIds1[i].value=cIds[i].value;
		//alert("after " + cIds1[i].value);
	}
	//document.multipleShippingAddr.submit();
}

/*
END Shipping page related scripts
*/

/*
Billing page related scripts
*/

function changeAddressTypeBilling(radio) {
	document.location.href = "billing.jsp?addressType=" + radio.value;
}


// Toggle Content
$(".giftCard a").click(function() {
	$(this).siblings("div").toggleClass("gCToggleContent");
});

$(".giftCard .typeCheck input").change(function() {
	$(this).parent(".typeCheck").siblings("div").toggleClass("gCToggleContent");
});

function setCouponOnly() {
	var ref= document.getElementById("reference");
	ref.value="true";
	//document.shippingAddress.submit();
}

function removeCouponOnly() {
	var ref= document.getElementById("reference");
	ref.value="true";
	$('#remove-coupon-button').click();
	//document.shippingAddress.submit();
}

function setCouponOnlyInCart(){
	var cartref= document.getElementById("cartreference");
	cartref.value="true";

/*
	var chkform = document.getElementById("checkoutForm");
	chkform.submit();
	*/
}

function removeCouponFromCart() {
	var cartref= document.getElementById("cartreference");
	cartref.value="true";
	$('#remove-coupon-button').click();
}

// Quick Veiw functions
function updateCartDisplay (returnPath) {
	// console.log("return path = " + returnPath);
	// var inlineCartURL  = '<c:url value="/cart/cart_summary.jsp?hasRealOrderTotal=false&returnPath=" />'+ returnPath;
	// var inlineCartURL  = CONTEXT_ROOT + '/cart/cart_summary.jsp?hasRealOrderTotal=false&returnPath='+ returnPath;
	var inlineCartURL  = CONTEXT_ROOT + '/cart/cart_summary.jsp?hasRealOrderTotal=false&returnPath='+ returnPath + '&foo=' + Math.floor(Math.random() * 10000);
	$.get(inlineCartURL, function(data) {
		  $('#persistentCart').html(data);
	});
}

function startCheckout() {
	$('#checkoutHeaderForm').submit();
	return false;
}


function showCartFlyout(divMessage){
	
	var flyoutDiv = $('#popupCart');
	var divMsgHTML = "";
	if ($.isArray( divMessage )) {
		$.each(divMessage, function() {
			divMsgHTML = divMsgHTML + "<div id='calloutMessage'>" + divMessage.html() + "</div>"
			
		});
		
	} else {
		// flyoutDiv.append(divMessage);
		divMsgHTML = divMsgHTML + "<div id='calloutMessage'>" + divMessage.html() + "</div>"

	}
	flyoutDiv.append(divMsgHTML);
	flyoutDiv.attr('id', 'popupCart');
	var callout = flyoutDiv.slideDown("slow");
	setTimeout(function () {
        callout.slideUp('fast');
        // flyoutDiv.attr('id', 'popupCartQV');
	    flyoutDiv.hide();
	    $("div[id='calloutMessage']").remove();
    }, 5000);
    $("#closeCallout").click(function() {
	    flyoutDiv.slideUp("slow");
	    // flyoutDiv.attr('id', 'popupCartQV');
	    flyoutDiv.hide();
		$("div[id='calloutMessage']").remove();
	});

}

/*
Product Page scripts
*/

/*
	Adding function to copy skuAttributes Span Value to Sku Attributes Input field

*/
function updateSkuAttributesInput() {
	//alert ("In updateSkuAttributesInput");
	var selectedSkuAttributes = $('#skuAttributesSpan').text();
	 $('#skuAttributes').val(selectedSkuAttributes);
	 return true;
}

function cmChangeImage(zoomViewerUrl,newColor)
{

	embedSwf(zoomViewerUrl,'');
}


function cmChangeColor(newColor, newZoomViewerUrl, repositoryId)
{
	var oldColor = $("#cartColor").text();

	var unavailableColor = $("a#" + repositoryId).parent().hasClass("unavailable");
	if(unavailableColor != true){
		unavailableColor = ($("a#" + repositoryId).parent().hasClass("preSelect") && $("a#" + repositoryId).parent().hasClass("selected"));
	}
	if (unavailableColor != true) {
		cmChangeImage(newZoomViewerUrl,newColor);

		if($("#selectedColor").text() == newColor) {
			$("#selectedColor").text("");
		} else {
			$("#selectedColor").text(newColor);
		}
		if(oldColor!=null && oldColor.substr(0,newColor.length) === newColor){
			$("#cartColor").text("");
		}else{
			$("#cartColor").text(newColor+",");
		}

		cmChangeSize(repositoryId, "color");
	}
}

function cmChangeColorNew(newColor, repositoryId,obj)
{

	// if the initial "preselect" click has been run (and has applied class="stopselected")
	// then don't allow this color to be deselected if it was preselected.
	if (obj != undefined) {
		if ($(obj).parent(".preSelect").length > 0 && $(obj).parent(".stopselected").length > 0) {
			return false;
		}
	}

	var oldColor = $("#cartColor").text();

	var unavailableColor = $("a#" + repositoryId).parent().hasClass("unavailable");
	if(unavailableColor != true){
		unavailableColor = ($("a#" + repositoryId).parent().hasClass("preSelect") && $("a#" + repositoryId).parent().hasClass("selected"));
	}
	if (unavailableColor != true) {
		// cmChangeImage(newZoomViewerUrl,newColor);
		var newColorHyphenated = newColor.replace(/ /gi,'-');
		$('.color.color'+newColorHyphenated).parent().addClass("stopselected");
		if($("#selectedColor").text() == newColor) {
			$("#selectedColor").text("");
		} else {
			$("#selectedColor").text(newColor);
		}
		if(oldColor!=null && oldColor.substr(0,newColor.length) === newColor) {
			$("#cartColor").text("");
		}else{
			$("#cartColor").text(newColor+",");
		}
		cmChangeSize(repositoryId, "color");
	}
}

function cmChangeThumbnailColor(newThumbURL, indexCount)
{
    var prodImageId = "#productId"+indexCount;
	$(prodImageId).attr('src', newThumbURL);

}

// This function is run any time a size is clicked.
// If this size is not available, return false and
// do not do anything. If it is available, call
// cmChangeSize.
function cmsChangeSize(obj) {

	var attrName = $(obj).attr('class');
	var attrNameParent = $(obj).parent().attr('class');
	var chosenHemmingLength = "#chosenHemmingLength";
	//alert("attrNameParent:" + attrNameParent);
	var attrValue = $(obj).text();
	var attrId = attrName + attrValue;
	var targetChosenHemmingLength = "#" + attrId + " " + chosenHemmingLength;

	// Find if the parent has a class of "unavailable", or its preselected and has already been selected
	// http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery
	//
	if ($(obj).parent(".unavailable").length > 0 || ($(obj).parent(".preSelect").length > 0 && $(obj).parent(".selected").length > 0) ) {
		return false;
	}

	/*If the selected attrName is rise then based on the attrValue(Long,Reg,Short)enable #customHemmingLengths
	and disable #defaultHemmingLengths. (R2 requirement so that users can't select hemmingLengths which are
	not associated with the rise)*/
	/*
	if(attrName == 'rise'){

		// Get the hemming that the user has selected.
		// First see if it's on one of the rise-specific dropdowns -- the first not-hidden one is the selected one.
		var selectedHemming = $('select[id^="select-rise"]:not(:hidden)').val();
		// If we didn't get selected hemming off a rise-specific dropdown, it must be in the default one.
		if (selectedHemming == null) {
			selectedHemming = $('select[id="hemmingLength"]').val();
		}

		// Clear out the selection from the rise-specific and default-dropdowns.
		$('select[id^="select-rise"]').attr("value","");
		$('select[id="hemmingLength"]').attr("value","");

		// We also need to clear the name from the rise-specific drop-downs,
		// as both map to the same bean and otherwise, only the first is read.
		$('select[id^="select-rise"]').attr("name","");

		if(attrNameParent == ""){
			$('ul[id^="rise"]').hide();
			$("#defaultHemmingLengths").hide();
			$(targetChosenHemmingLength).text("");
			$("#"+attrId).show();

			// If the rise we're switching to has the selected hemming, set it on the new drop-down
			if (0 != $("#"+attrId+" option[value='"+selectedHemming+"']").length) {
				$('select[id="select-rise-'+attrValue+'"]').attr("value",selectedHemming);
				$(targetChosenHemmingLength).text(selectedHemming);

			// If it does not, then clear the text from the add to cart area
			} else {
				$("#cartHemmingLength").text("");
			}

			// Also make sure we reset the bean association in the "name" property to whichever rise we've selected.
			$('select[id="select-rise-'+attrValue+'"]').attr("name","/atg/commerce/order/purchase/CartModifierFormHandler.hemmingLength");

		} else if (attrNameParent == "selected"){
			// If we're de-selecting an option, clear everything
			$('ul[id^="rise"]').hide();
			$("#defaultHemmingLengths #chosenHemmingLength").text("");
			$("#defaultHemmingLengths").show();
			$("#cartHemmingLength").text("");
			// We know we have the chosen hemming in the default hemming list, so set it
			$('select[id="hemmingLength"]').attr("value",selectedHemming);
		}
		//alert("attrName:attrValue" + attrName + "-" + attrValue);
		//$('ul[id^="rise"]').hide();
		//$("#defaultHemmingLengths").toggle();
		//$("#chosenHemmingLength").text("");
		//$("#"+attrId).toggle();
		//$("#defaultHemmingLengths").toggle();
	}

	*/

	cmChangeSize($(obj).text(), $(obj).attr('class'));

	//so links don't do anything
	return false;
}

function cmChangeSize(attrValue, attrName)
{

	var sizeId ="#" + attrName;
	var sizeIdIsInput = $(sizeId).is(":input");

	var cartId ='#cart' + attrName;

//	var pantHemmingValue = attrValue;
//	var pantHemmingText = "#pantLength";
//	var cartHemmingText="#cartHemmingLength";
//
//	$(pantHemmingText).text(pantHemmingValue);
//	$(cartHemmingText).text(pantHemmingValue + ",");

	var oldAttrValue = $(cartId).text();

	oldAttrValue = oldAttrValue.replace(",","");
	oldAttrValue = oldAttrValue.replace("/ /g","");

	//if()

	if(oldAttrValue!=null && oldAttrValue == attrValue){
		$(cartId).text("");
		//return;
	}else{
		$(cartId).text(attrValue+",");
	}
	// skuAttributesString = $('#skuAttributes').val();
	skuAttributesString = $('#skuAttributesSpan').text();
	if (skuAttributesString == null) { // for IE bug
		skuAttributesString = '';
	}


	var tempAttrString = "";
	var attrString = attrName + '=';
	if (attrValue) {
		tempAttrString = attrName + '=' + attrValue + '@';
	}

	// var oldvalue = (sizeIdIsInput ? $(sizeId).val() :  $(sizeId).text());
	var oldvalue = (sizeIdIsInput ? oldAttrValue :  $(sizeId).text());
	var oldAttrString = attrName + '=' + oldvalue + '@';

	//if this sku attr has already a value then it should already be in the
	//skuAttributesString and needs to be removed.
	if($("#" + attrName).text() != "" ) {

		skuAttributesString = skuAttributesString.replace(oldAttrString, "");
		//escape the . /  for half sizes.
		var safeString = oldvalue.replace(/\./, "\\.");
		safeString = safeString.replace(" ","\\ ");
		safeString = safeString.replace("/", "\\/");
		safeString = safeString.replace("(", "\\(");
		safeString = safeString.replace(")", "\\)");
		$("#" + attrName + "-" + safeString).parent().removeClass("selected");

		if (!sizeIdIsInput) {
			$(sizeId).text("");
		}


	}

	// debug alert('DEBUG\nskuAttributesString:'+skuAttributesString+'\nattrValue:'+attrValue+'\ntempAttrString:'+tempAttrString+'\noldAttrString:'+oldAttrString);
	if(tempAttrString && oldAttrString != tempAttrString) {
		skuAttributesString = skuAttributesString + tempAttrString;
		var safeString = attrValue.replace(/\./, "\\.");
		safeString = safeString.replace(" ","\\ ");
		safeString = safeString.replace("/", "\\/");
		safeString = safeString.replace("(", "\\(");
		safeString = safeString.replace(")", "\\)");
		$("#" + attrName + "-" + safeString).parent().addClass("selected");
		if (!sizeIdIsInput) {
			$(sizeId).text(attrValue);
		}
	}

//	alert("Setting skuAttributes = " + skuAttributesString);
	//$('#skuAttributes').val(skuAttributesString);
	 $('#skuAttributesSpan').text(skuAttributesString);
	updateSkuAvailability(attrName);

}

function changeHemmingOption(obj){
	var hemmingValue = obj.value;
	var hemmingText = "#chosenHemmingLength";
	var cartHemmingText="#cartHemmingLength";
	var hemmingLengthParent = $(obj).closest("ul").attr("id");
	var hemmingLengthParentId = "#" + hemmingLengthParent + " " + hemmingText;

	//alert("Hemming Length Parent Id:" + hemmingLengthParentId);
	//var hemmingLengthParent = $(obj).closest("ul").attr("id");
	//alert("hemmingLength Parent:" + hemmingLengthParent);
	$(hemmingLengthParentId).text(hemmingValue);
	$(cartHemmingText).text(hemmingValue + ",");

	skuAttributesString = $('#skuAttributesSpan').text();
	//skuAttributesString = $('#skuAttributes').val();
	updateSkuAvailability(skuAttributesString);
}


/**
 * Make a AJAX call to get the new sku availability using a product Id
 * and sku attributes.  Update the sku attributes on the page that are no
 * longer available with the attributes chosen.
 *
 * Update all attributes EXCEPT the selected attribute
 */
function updateSkuAvailability(selectedAttr) {

		//alert("selectedAttr:" + selectedAttr);
		var productId = $("#productId").val();

		// Get the hemming that the user has selected.
		// First see if it's on one of the rise-specific dropdowns -- the first not-hidden one is the selected one.
		var hemmingText = $('select[id^="select-rise"]:not(:hidden)').val();
		// If we didn't get selected hemming off a rise-specific dropdown, it must be in the default one.
		if (hemmingText == null) {
			hemmingText = $('select[id="hemmingLength"]').val();
		}
		/*
		if(selectedAttr.indexOf("rise=Long") > -1){
			hemmingText = $("#select-rise-Long").val();
		} else if (selectedAttr.indexOf("rise=Reg") > -1){
			hemmingText = $("#select-rise-Reg").val();
		} else if (selectedAttr.indexOf("rise=Short") > -1){
			hemmingText = $("#select-rise-Short").val();
		} else {
			hemmingText = $("#hemmingLength").val();
		}*/

		//alert("hemmingText inside updateSkuAvailability:" + hemmingText);
		var quantity = $("#quantity").val();
		var priceRange = $("#priceRange").val();
		var complexPriceId = $("#complexPriceId").val();
//		var pantHemmingText = $("#pantLength").val();
//		alert("pantHemmingText :pantHemmingMessage value: "+pantHemmingText);
//		alert("hemmingLength:" + hemmingText);

		$.post('/mens-big-and-tall-store/catalog/includes/filterSkuOnAttributes.jsp',
				{productId: productId, skuAttributes: skuAttributesString, quantity: quantity, hemmingMessage: hemmingText, priceRange: priceRange, complexPriceId: complexPriceId},
		 function(data) {

			$("#availability").text(data.inventoryMessage);

			$("#cartPrice").text(data.skuPrice);
			$("#hemmingMessage").text(data.hemmingMessage);
			//$("#pantHemmingMessage").text(data.pantHemmingMessage);
			$("#requiredAttributes").val(data.requiredAttributes);
			$("#reqSkuId").val(data.skuId);


			//reset 'size' attribute value elements.
			enableAttributeValueElements("size", data.size);

			//reset 'waistSize' attribute value elements.
			enableAttributeValueElements("waistSize", data.waistSize);

			//reset 'coatSize' attribute value elements.
			enableAttributeValueElements("coatSize", data.coatSize);

			//reset 'coatLength' attribute value elements.
			enableAttributeValueElements("coatLength", data.coatLength);

			//reset 'pantLength' attribute value elements.
			enableAttributeValueElements("pantLength", data.pantLength);
			
			//reset 'miscSize' attribute value elements.
			enableAttributeValueElements("miscSize", data.miscSize);

			var theSelect = $('select[name=pantLength]');
			if (theSelect.length > 0) {
				//var theSelect = $('select[name=hemmingLength]');
				var selectedValue = theSelect.val();

				var firstOption = $(document.createElement("option")).attr("value","").text("Select Inseam"); //theSelect.children().first();
				theSelect.empty();
				theSelect.append(firstOption);
				if (data.pantLength != null) {
					var pantLengths = data.pantLength;
					pantLengths = pantLengths.sort();
					for(var i=0; i < pantLengths.length; i++) {
						theSelect.append($(document.createElement("option")).attr("value",pantLengths[i]).text(pantLengths[i]));

					}
				}
				//alert("selected value:" + selectedValue);
				$('#chosenHemmingLength').text(selectedValue)
				theSelect.val(selectedValue);
			}


			var theSelect = $('#hemmingLength');
			if (theSelect.length > 0)  {
				var selectedValue = theSelect.val();
				var selectedValueStillValid = false;
				if (selectedValue == 'Unfinished') {
					selectedValueStillValid = true;
				}

				var firstHemmingOption = $(document.createElement("option")).attr("value","").text("Select Inseam"); //theSelect.children().first();
				var unfinishedOption =  $(document.createElement("option")).attr("value","Unfinished").text("Unfinished");
				theSelect.empty();
				theSelect.append(firstHemmingOption);
				theSelect.append(unfinishedOption);
				if(data.hemmingLength != null) {
					var hemmingLengths = data.hemmingLength;
					hemmingLengths = hemmingLengths.sort();
					for(var i=0; i < hemmingLengths.length; i++) {
						if (hemmingLengths[i] == selectedValue) {
							selectedValueStillValid = true;
						}
						theSelect.append($(document.createElement("option")).attr("value",hemmingLengths[i]).text(hemmingLengths[i]));

					}
				}
				if (selectedValueStillValid) {
					$('#chosenHemmingLength').text(selectedValue)
					theSelect.val(selectedValue);
				}
			}



			//reset 'shoeSize' attribute value elements.
			enableAttributeValueElements("shoeSize", data.shoeSize);

			//reset 'sleeveSize' attribute value elements.
			enableAttributeValueElements("sleeveSize", data.sleeveSize);

			//reset 'shoeWidth' attribute value elements.
			enableAttributeValueElements("shoeWidth", data.shoeWidth);

			//reset 'rise' attribute value elements.
			enableAttributeValueElements("rise", data.rise);

			//reset 'neckSize' attribute value elements.
			enableAttributeValueElements("neckSize", data.neckSize);

			//reset 'shortLength' attribute value elements.
			enableAttributeValueElements("shortLength", data.shortLength);

			//reset 'pantSize' attribute value elements.
			enableAttributeValueElements("pantSize", data.pantSize);

			//reset 'underwearLength' attribute value elements.
			enableAttributeValueElements("underwearLength", data.underwearLength);
			
			//disable all sizes
			$("a.cuff").parent().addClass("unavailable");
			//re-enable all sizes in list
			if(data.cuff != null) {
				var cuffs = data.cuff;
				for(var i=0; i < cuffs.length; i++) {
					//$("a.cuff:equals(" + cuffs[i] + ")").parent().removeClass("unavailable");
					$("a.cuff").each(function(index, Element){
						if ($(this).text() == cuffs[i]) {
							$(this).parent().removeClass("unavailable");
						}

					});
				}
			}
			//disable all sizes
			$("a.color").parent().addClass("unavailable");
			$("a.color").children("#unavailableColorImage").css('display','inline');
			//re-enable all sizes in list
			if(data.color != null) {
				var colors = data.color;
				for(var i=0; i < colors.length; i++) {
					var colorId = colors[i].split(":")[1];
					$("#" + colorId).parent().removeClass("unavailable");
					$("#" + colorId).find('#unavailableColorImage').css('display','none');
				}
			}

		}, "json");

}

//Reset the product attribute value elements based on its availability
//attributeClass = the class name of the element that is used to represent a particular attribute
//               eg. All size href elements are set with class 'size';
// 				     All shoeWidth href elements are set with class 'shoeWidth';
//attributeValues = the set of values of the attribute that are in-stock
function enableAttributeValueElements(attributeClass, attributeValues){
	// disable everything first
	$("a."+attributeClass).parent().addClass("unavailable");
	if(attributeValues != null) {
		// iterate through in-stock attribute set and selectively enable them based on their elementId
		for(var i=0; i < attributeValues.length; i++) {
			// escape characters that cause jQuery issues when searching for elements based on Id
			var tempString = attributeValues[i];
			tempString = tempString.replace(/\./, "\\.");
			tempString = tempString.replace("/", "\\/");
			tempString = tempString.replace(" ", "\\ ");
			var attribElemId = attributeClass + "-" + tempString;
			// Enable the element that represent the available attribute value. 
			// This is the id associated with the html element that represents an outfit product level attribute value. eg size-XL 
			$("#"+attribElemId).parent().removeClass("unavailable");
		}
	}
}

//Reset the outfit product attribute value elements based on its availability
//productId = the outfit product Id
//attributeClass = the class name of the element that is used to represent a particular attribute
//                 eg. All size href elements are set with class 'size';
//					   All shoeWidth href elements are set with class 'shoeWidth';
//attributeValues = the set of values of the attribute that are in-stock
function enableOutfitAttributeValueElements(productId, attributeClass, attributeValues){
	// This is the class name associated with the html element that represents an outfit product level attribute value. eg prod92838-size 
	var prodAttributeClass = "prod" + productId + "-" + attributeClass;
	// disable everything first
	$("a." + prodAttributeClass).parent().addClass("unavailable");
	if(attributeValues != null) {
		// iterate through in-stock attribute set and selectively enable them based on their elementId
		for(var i=0; i < attributeValues.length; i++) {
			var tempString = attributeValues[i];
			// escape characters that cause jQuery issues when searching for elements based on Id
			tempString = tempString.replace(/\./, "\\.");
			tempString = tempString.replace("/", "\\/");
			tempString = tempString.replace(" ", "\\ ");
			// Enable the element that represent the available attribute value. 
			// This is the id associated with the html element that represents an outfit product level attribute value. eg 92838-size-XL 
			var attribElemId = productId + "-" + attributeClass + "-" + tempString;
			$("#"+attribElemId).parent().removeClass("unavailable");
		}
	}
}

/*
END Product Page scripts
*/
/*
 * Cart Update submit function
 * */
function submitCheckoutForm(skuId) {
	//alert("here" + skuId);
	var sku= document.getElementById(skuId);
	var cartRelationShipId = document.getElementById("cartRelationShipId");
	cartRelationShipId.value = skuId;
	//alert("cartRelationShipId value: "+cartRelationShipId.value);
	//alert("here1 " + sku.value);
	var upQty = document.getElementById("updateQuantity");
	upQty.value = sku.value;

	//alert("here2 " + upQty.value);
	var chkform = document.getElementById("checkoutForm");
	chkform.submit();
}

/*
 * Outfit functions
 *
 * */

 function changeOutfitHemmingOption(obj,prodId){
	var hemmingValue = obj.value;
	var hemmingText = "#chosenHemmingLength-" + prodId;
	var cartHemmingText="#cartHemmingLength";

	$(hemmingText).text(hemmingValue);
	$(cartHemmingText).text(hemmingValue + ",");

	skuAttributesString = $('#skuAttributes').val();
	updateOutfitSkuAvailability(skuAttributesString,prodId);
}

function cmOutfitChangeColor(newColor, newZoomViewerUrl, repositoryId, prodId, obj)
{
	// if the initial "preselect" click has been run (and has applied class="stopselected")
	// then don't allow this color to be deselected if it was preselected.
	if (obj != undefined) {
		if ($(obj).parent(".preSelect").length > 0 && $(obj).parent(".stopselected").length > 0) {
			return false;
		}
	}

	var selectedColor = "#selectedColor" + '-' + prodId;
	var unavailableColor = $("a.prod" + prodId + "-color.color-" + repositoryId).parent().hasClass("unavailable");
	if(unavailableColor){
		unavailableColor = ($("a.prod" + prodId + "-color.color-" + repositoryId).parent().hasClass("preSelect") && $("a.prod" + prodId + "-color.color-" + repositoryId).parent().hasClass("selected"));
	}
	if (unavailableColor != true) {
		//cmChangeImage(newZoomViewerUrl);
		// alert(' change #productId-'+prodId+' into ' + newZoomViewerUrl);

		var newColorHyphenated = newColor.replace(/ /gi,'-');
		$("a.prod" + prodId + "-color.color-" + repositoryId).parent().addClass("stopselected");

		$("#productId-" + prodId).attr('src',newZoomViewerUrl);
		if($(selectedColor).text() == newColor) {
			$(selectedColor).text("");
			//return;
		} else {
			$(selectedColor).text(newColor);
		}
		$("#cartColor").text(newColor+",");
		cmOutfitChangeSize(repositoryId, "color", prodId);
	}
}

function cmOutfitChangeThumbnailColor(newThumbURL, indexCount)
{
    var prodImageId = "#productId"+indexCount;
	$(prodImageId).attr('src', newThumbURL);
}

function cmsOutfitChangeSize(obj, prodId) {
	if ($(obj).parent(".unavailable").length > 0 || ($(obj).parent(".preSelect").length > 0 && $(obj).parent(".selected").length > 0)) {
		return false;
	}

	var attrClass = ($(obj).attr('class').split(' ')[0]);

	cmOutfitChangeSize($(obj).text(), attrClass, prodId);
	return false;
}

function cmOutfitChangeSize(attrValue, attrName, prodId)
{
	var sizeId ="#" + attrName + '-' + prodId;
	var cartId ='#cart' + attrName;

	$(cartId).text(attrValue+",");
	skuAttributesString = $('#skuAttributes').val();

	if(skuAttributesString.match(prodId)) {

	} else {
		if(skuAttributesString.match(":")) {
			skuAttributesString = skuAttributesString + "," + prodId + ":";
		} else {
			skuAttributesString = prodId + ":" + skuAttributesString;
		}
	}

	var attrString = attrName + '=';
	var tempAttrString = attrName + '=' + attrValue + '@';
	var oldvalue = $(sizeId).text();
	var oldAttrString = attrName + '=' + oldvalue + '@';

	//alert("HERE " + skuAttributesString.substring(skuAttributesString.indexOf(prodId, 0), skuAttributesString.length));
	//extract the attributes associated to the product.
	var prodAttrs = skuAttributesString.substring(skuAttributesString.indexOf(prodId, 0), skuAttributesString.length);
	if (prodAttrs == null) {
	} else {
		var idx = prodAttrs.indexOf(",", 0);
		if (idx > -1) {
			prodAttrs = prodAttrs.substring(0, idx);
		}
	}

	//if this sku attr has already been selected then it should already be in the
	//skuAttributesString and needs to be removed.
	//if(skuAttributesString.match(oldAttrString)) {
	//	alert("INSIDE");
	//	skuAttributesString = skuAttributesString.replace(oldAttrString, "");
	//	$("a." + attrName + ":contains(" + oldvalue + ")").parent().removeClass("selected");
	//	$(sizeId).text("");
	//}

	//alert("skuAttributesString BEFORE replace >> " + skuAttributesString);

	var prdIdx = skuAttributesString.indexOf(","+prodAttrs);
	if (prdIdx > -1) {
		//alert("in if");
		skuAttributesString = skuAttributesString.replace("," + prodAttrs,"");
	} else {
		//alert("in else");
		skuAttributesString = skuAttributesString.replace(prodAttrs,"");
	}

	//console.log("skuAttributesString after replace >> " + skuAttributesString);
	//console.log("prodAttrs BBB>> " + prodAttrs);
	//console.log("prodAttrs CCC>> " + oldAttrString);
	//console.log("prodAttrs.match(oldAttrString) >> " + prodAttrs.match(oldAttrString));


	if($("#" + attrName + '-' + prodId).text() != "" ) {
		prodAttrs = prodAttrs.replace(oldAttrString, "");
		//escape the . /  for half sizes.
		var safeString = oldvalue.replace(/\./, "\\.");
		safeString = safeString.replace("/", "\\/");
		safeString = safeString.replace("(", "\\(");
		safeString = safeString.replace(")", "\\)");
		$("a.prod" + prodId + "-" + attrName + "-" + safeString).parent().removeClass("selected");
		$(sizeId).text("");
	}

	//console.log("skuAttributesString after replace 222>> " + skuAttributesString);
	//console.log("Trigger: oldAttrString: "+oldAttrString);
	//console.log("Trigger: tempAttrString: "+tempAttrString);
	//console.log("Trigger: prodAttrs: "+prodAttrs);

	if(oldAttrString != tempAttrString) {
		//skuAttributesString = skuAttributesString + tempAttrString;
		prodAttrs = prodAttrs + tempAttrString;
		var safeString = attrValue.replace(/\./, "\\.");
		safeString = safeString.replace("/", "\\/");
		safeString = safeString.replace("(", "\\(");
		safeString = safeString.replace(")", "\\)");
		$("a.prod" + prodId + "-" + attrName + "-" + safeString).parent().addClass("selected");
		$(sizeId).text(attrValue);
	}

	//console.log("length >> " + skuAttributesString.length);
	if (skuAttributesString.length > 0) {
		skuAttributesString = skuAttributesString + "," + prodAttrs;
	} else {
		skuAttributesString = skuAttributesString + prodAttrs;
	}

	//console.log("skuAttributesString >> " + skuAttributesString);
	$('#skuAttributes').val(skuAttributesString);

	updateOutfitSkuAvailability(attrName, prodId);

}


/**
 * Make a AJAX call to get the new sku availability using a product Id
 * and sku attributes.  Update the sku attributes on the page that are no
 * longer available with the attributes chosen.
 *
 * Update all attributes EXCEPT the selected attribute
 */
function updateOutfitSkuAvailability(selectedAttr, prodId) {

		var productId = prodId; //$("#productId").val();
		var hemmingText = $("#hemmingLength-" + productId).val();
		var quantity = $("#quantity-" + productId).val();
		//console.log("selectedAttr: " + selectedAttr);
		//console.log("productId: " + productId);

		var indexofProductId = skuAttributesString.indexOf(prodId, 0);
		var prodAttrs = "";
		if (indexofProductId > 0) {
			prodAttrs  = skuAttributesString.substring(indexofProductId, skuAttributesString.length);
		}
		skuAttributesString = prodAttrs.replace(productId + ":","");

		$.post('/mens-big-and-tall-store/catalog/includes/filterOutfitSkuOnAttributes.jsp',
				{productId: productId, quantity: quantity, skuAttributes: skuAttributesString, hemmingMessage: hemmingText },
		 function(data) {

			$("#availability-" + prodId).text(data.inventoryMessage);
			$("#hemmingMessage-" + prodId).text(data.hemmingMessage);
			$("#cartPrice").text(data.skuPrice);

			//reset outfit product 'size' attribute value elements.
			enableOutfitAttributeValueElements(productId, "size", data.size);

			//reset outfit product 'waistSize' attribute value elements.
			enableOutfitAttributeValueElements(productId, "waistSize", data.waistSize);

			//reset outfit product 'coatSize' attribute value elements.
			enableOutfitAttributeValueElements(productId, "coatSize", data.coatSize);

			//reset outfit product 'coatLength' attribute value elements.
			enableOutfitAttributeValueElements(productId, "coatLength", data.coatLength);

			//reset outfit product 'pantLength' attribute value elements.
			enableOutfitAttributeValueElements(productId, "pantLength", data.pantLength);
			
			//reset outfit product 'miscSize' attribute value elements.
			enableOutfitAttributeValueElements(productId, "miscSize", data.miscSize);

			var theSelect = $('#' + productId + "-pantLength");
			if (theSelect.length > 0) {
				var selectedValue = theSelect.val();

				var firstOption = $(document.createElement("option")).attr("value","").text("Select Inseam"); //theSelect.children().first();
				theSelect.empty();
				theSelect.append(firstOption);
				if(data.pantLength != null) {
					var pantLengths = data.pantLength;
					pantLengths = pantLengths.sort();
					for(var i=0; i < pantLengths.length; i++) {
						theSelect.append($(document.createElement("option")).attr("value",pantLengths[i]).text(pantLengths[i]));
					}
				}
				theSelect.val(selectedValue);
			}
			// HemmingLength
			var theSelect = $('#' + "hemmingLength-" + productId);
			if (theSelect.length > 0) {
				var selectedValue = theSelect.val();
				var selectedValueStillValid = false;
				if (selectedValue == 'Unfinished') {
					selectedValueStillValid = true;
				}

				var firstOption = $(document.createElement("option")).attr("value","").text("Select Inseam"); //theSelect.children().first();
				var unfinishedOption =  $(document.createElement("option")).attr("value","Unfinished").text("Unfinished");
				theSelect.empty();
				theSelect.append(firstOption);
				theSelect.append(unfinishedOption);
				if(data.hemmingLength != null) {
					var hemmingLengths = data.hemmingLength;
					hemmingLengths = hemmingLengths.sort();
					for(var i=0; i < hemmingLengths.length; i++) {
						if (hemmingLengths[i] == selectedValue) {
							selectedValueStillValid = true;
						}
						theSelect.append($(document.createElement("option")).attr("value",hemmingLengths[i]).text(hemmingLengths[i]));

					}
				}

				if (selectedValueStillValid) {
					$("#chosenHemmingLength-" + prodId).text(selectedValue);
					theSelect.val(selectedValue);
				} else {
					$("#chosenHemmingLength-" + prodId).text("");
				}
			}

			//reset outfit product 'shoeSize' attribute value elements.
			enableOutfitAttributeValueElements(productId, "shoeSize", data.shoeSize);

			//reset outfit product 'sleeveSize' attribute value elements.
			enableOutfitAttributeValueElements(productId, "sleeveSize", data.sleeveSize);

			//reset outfit product 'shoeWidth' attribute value elements.
			enableOutfitAttributeValueElements(productId, "shoeWidth", data.shoeWidth);

			//reset outfit product 'rise' attribute value elements.
			enableOutfitAttributeValueElements(productId, "rise", data.rise);

			//reset outfit product 'neckSize' attribute value elements.
			enableOutfitAttributeValueElements(productId, "neckSize", data.neckSize);

			//reset outfit product 'shortLength' attribute value elements.
			enableOutfitAttributeValueElements(productId, "shortLength", data.shortLength);

			//reset outfit product 'pantSize' attribute value elements.
			enableOutfitAttributeValueElements(productId, "pantSize", data.pantSize);

			//reset outfit product 'underwearLength' attribute value elements.
			enableOutfitAttributeValueElements(productId, "underwearLength", data.underwearLength);

			//disable all sizes
			var prodColor = "prod" + productId + "-color";
			$("a." + prodColor).parent().addClass("unavailable");
			$("a." + prodColor).children("#unavailableColorImage").css('display','inline');
			//$("a.color").parent().addClass("unavailable");
			//re-enable all sizes in list
			if(data.color != null) {
				var colors = data.color;
				for(var i=0; i < colors.length; i++) {
					var colorId = colors[i].split(":")[1];
					$(".color-" + colorId + "." + prodColor).parent().removeClass("unavailable");
					$(".color-" + colorId + "." + prodColor).find('#unavailableColorImage').css('display','none');
				}
			}
		}, "json");

}

var productViewer = function () {
	var replaceId = "",
		width = 0,
		height = 0,
		requiredFlashVersion = "0.0.0",
		mediaSet = [],
		parent = null,
		cachedMedia = {};
		style = "visibility:visible";

	function useCache(key, createNew) {
		if (key in cachedMedia) {
			parent.append(cachedMedia[key]);
		} else {
			cachedMedia[key] = createNew();
		}
	}

	function changeMedia (urlSet) {
		var oldMedia = $("#" + replaceId).detach();
		if ("swf" in urlSet && swfobject.hasFlashPlayerVersion(requiredFlashVersion)) {
			useCache(urlSet["swf"], function () {
				parent.append('<div id="' + replaceId + '"></div>');

				// Work-around for IE bug: add random string to the URL
				var requestUrl = urlSet["swf"];
				requestUrl += (requestUrl.match(/\?/) ? "&amp;" : "?") + Math.floor(Math.random() * 10000);

				// Changing "&amp;" to "&" because scene7 can't handle the "&amp;"s in the URLs
				requestUrl = requestUrl.replace(/&amp;/gi,'&');

				var attributes = {"data":requestUrl, "width":width, "height":height, "style":style};
				var params = {"wmode":"transparent"};
				return swfobject.createSWF(attributes, params, replaceId);
			});
		} else if ("img" in urlSet) {
			useCache(urlSet["img"], function () {
				return $('<div id="' + replaceId + '" style="visibility:visible"></div>')
					.html('<img src="' + urlSet["img"] + '" />')
					.appendTo(parent);
			});
		}
	};

	return {
		initialize: function (replaceIdArg, widthArg, heightArg, requiredFlashVersionArg, mediaSetArg) {
			replaceId = replaceIdArg;
			width = widthArg;
			height = heightArg;
			requiredFlashVersion = requiredFlashVersionArg;
			mediaSet = mediaSetArg;
			parent = $("#" + replaceId).wrap('<div id="' + replaceId + 'Parent" />').parent();
			cachedMedia = {};

			// if (mediaSet.length) {
			//	changeMedia(mediaSet[0]);
			// }
		},
		changeMedia: function (index,obj) {

			// If this swatch is unavailable, do not change the image when it is clicked:
			if (obj != undefined) {
				if ($(obj).parent(".unavailable").length > 0) {
					return false;
				}
			}

			if (index < mediaSet.length) {
				changeMedia(mediaSet[index]);
			}
		}
	}
}();

// Should be used on PO Box fields before calling QAS.
function cleansePOBox(pobox) {
    return "PO BOX " + pobox.replace(/^p(?:\.| ?\.? ?o\.?) ?b(?:\.|ox) ?/i, "");
}

function setAddressValidated(){
	$("#addressValidated").val("false");
}

function setUserAddressInSession(){
	$("#userEditInSession").val("true");
}

