/**************************************************
 * Cart Item quantity change functions.
 */
	function updateCartItemQuantity() {
	  document.shoppingCart.cartAction.value = "updateCartItemQuantity";
      document.shoppingCart.submit();
    }

/**************************************************
 * Promotion/gift certificate code functions.
 */

	function applyCode() {
	  document.shoppingCart.cartAction.value = "applyCode";
      document.shoppingCart.submit();
    }

	function removePromoCode(promoCode) {
	  var shoppingCartForm = document.shoppingCart;
	  shoppingCartForm.cartAction.value = "removePromoCode";
	  shoppingCartForm.promoCodeToDelete.value = promoCode;
      shoppingCartForm.submit();
    }

/**************************************************
 * Shipping and tax estimation functions.
 */

function onShippingCountryChange(newSelectedCountryCode) {
    document.getElementById("subCountry_"+curSelectedShippingCountry).style.display="none";
    curSelectedShippingCountry = newSelectedCountryCode;
    document.getElementById("subCountry_"+newSelectedCountryCode).style.display="block";
}

function getCartItemQty() {
	var cartItemQtyArray = new Array();
	var index = 0;
	var cartItemId = "cartItems[INDEX].quantity";
	var curCartItemNode = document.getElementById(cartItemId.replace("INDEX", index));
	while (curCartItemNode != null) {
		cartItemQtyArray[cartItemQtyArray.length] = curCartItemNode.value;
		index ++;
		curCartItemNode = document.getElementById(cartItemId.replace("INDEX", index));
	}
	//alert(DWRUtil.toDescriptiveString(cartItemQtyArray, 2));
	return cartItemQtyArray;
}

function estimateShippingAndTaxes(countryCode) {
	var cartItemQtyArray = getCartItemQty();
//    var countryCode=document.getElementById("country").value;
    var subCountryCode="";
    if (countryCode) {
	subCountryCode = document.getElementById("subCountry_"+countryCode).value;
    }
    var zipOrPostalCode = document.getElementById("zipOrPostalCode").value;

    if(zipOrPostalCode != "" && isNaN(zipOrPostalCode) != true && zipOrPostalCode.length == 5 && zipOrPostalCode.indexOf(".") == -1) {
        if (countryCode) {
	    	DWREngine.beginBatch();
			shoppingCartAjaxController.estimateShippingAndTaxes(countryCode, subCountryCode, zipOrPostalCode,cartItemQtyArray, estimateShippingAndTaxesCallBack);
			shoppingCartAjaxController.getEstimateAddressStr(updateEstimateAddress);
			shoppingCartAjaxController.getCartItemPrices(updateCartItemPrice)
			DWREngine.endBatch({verb:"GET", ordered:true});
	    } else {
	    	alert(specifyShippingStr);
	    }
    } else {
	    alert("Please specify a valid 5-digit zip code.");
    }
}

function estimateShippingAndTaxesCallBack(shoppingCart) {
    if (shoppingCart.selectedShippingServiceLevel) {
    	selectedShippingServiceLevelId = shoppingCart.selectedShippingServiceLevel.uidPk;
    	//alert(DWRUtil.toDescriptiveString(shoppingCart.shippingAddress, 2));
    	if (shoppingCart.shippingServiceLevelList.length > 0) {
        	document.getElementById("calculate-shipping").style.display="none";
        	document.getElementById("shipping-rates").style.display="block";
       	 	showDeliveryOptions(shoppingCart);
        	updateCartSummary(shoppingCart);
    	}
    } else {
    	alert(noDeliveryOptionStr);
    }
}

function showDeliveryOptions(shoppingCart) {
     	//show shipping service level options
     	var shippingServiceLevels = shoppingCart.shippingServiceLevelList
		var shippingOptionsTable = document.getElementById("shippingOptionsTableBody");
        while(shippingOptionsTable.hasChildNodes()){ shippingOptionsTable.removeChild(shippingOptionsTable.firstChild); }
		
        if (shippingServiceLevels && shippingServiceLevels.length > 0) {
            document.getElementById("shippingOptionsTable").style.display="";
            document.getElementById("estimatenoservicealert").style.display="none";
	    
	    
	    showShippingLevels(shoppingCart, shippingOptionsTable);
    	
    	// show handling options
    	var dropShipped = shoppingCart.dropShipped;
    	var shipByFreight = shoppingCart.shipByFreight;
		if (shipByFreight) {
    	    var handlingOptionsTable = document.getElementById("handlingOptionsBody");
    	    while(handlingOptionsTable.hasChildNodes()){ handlingOptionsTable.removeChild(handlingOptionsTable.firstChild); }
        }
	    if (shipByFreight && !dropShipped && shippingServiceLevels[0].carrier != "N/A") {
        	document.getElementById("")
        	document.getElementById("handlingOptions").style.display="";
        	document.getElementById("handlingOptionsDiv").style.display="";
    	} else {
        	if(document.getElementById("handlingOptionsDiv")) {
        		document.getElementById("handlingOptionsDiv").style.display="none";
        	}
    	}
    	if (shipByFreight) {
        	showFreightShippingOptions(shoppingCart, handlingOptionsTable);
    	}
	    //alert(DWRUtil.toDescriptiveString(shippingServiceLevels, 4));
        } else {
            document.getElementById("shippingOptionsTable").style.display="none";
	   		document.getElementById("handlingOptions").style.display="none";
            document.getElementById("estimatenoservicealert").style.display="block";
        }
}

function showShippingLevels(shoppingCart, shippingOptionsTable) {
	var shippingServiceLevels = shoppingCart.shippingServiceLevelList
	var namePropertyKey = "shippingServiceLevelDisplayName_" + localeStr;
	var isFirst = true;
	for (var i=0; i < shippingServiceLevels.length; i++){
		var shippingServiceLevel = shippingServiceLevels[i];
	    var checkedStr = "";
	    if (selectedShippingServiceLevelId > 0) {
            if (selectedShippingServiceLevelId == shippingServiceLevel.uidPk) {
                checkedStr = "checked=\"checked\"";
            }
        } else {
            if (isFirst) {
                checkedStr = "checked=\"checked\"";
                isFirst = false;
            }
        }
	
	    var newRow = document.createElement("tr");
	    var radioTD = document.createElement("td");
        var radioNode;
        try {
            radioNode = document.createElement("<input type=\"radio\" onclick=\"onShippingServiceLevelSelect(this);\" " + checkedStr
        	                + "name=\"selectedShippingServiceLevel\">");
        	} catch (err){
            radioNode = document.createElement("input");
            radioNode.type="radio";
            radioNode.name="selectedShippingServiceLevel";
            radioNode.onclick=function(e){
            	shoppingCartAjaxController.calculateForSelectedShippingServiceLevel(e.target.id, updateCartSummary);
            }
            if (checkedStr.length > 0)
                radioNode.checked = true;
		}
        radioNode.id=shippingServiceLevel.uidPk;
	    radioNode.value=shippingServiceLevel.uidPk;
        radioTD.appendChild(radioNode);
       	newRow.appendChild(radioTD);
		var nameTD = document.createElement("td");
	    nameTD.appendChild(document.createTextNode(shippingServiceLevel.localizedProperties.localizedPropertiesMap[namePropertyKey].value));
	    nameTD.className='type';
		newRow.appendChild(nameTD);
	
	    var costTD = document.createElement("td");
	    costTD.className='rate';

	    // check for undefined shipping cost
	    var shippingCost = "N/A";
	    if (shoppingCart.shipByFreight && shoppingCart.baseShippingCost) {
	    	shippingCost = shoppingCart.baseShippingCost.moneyValueAndSymbol;
	    } else if (shippingServiceLevel.shippingCost) {
	    	shippingCost = shippingServiceLevel.shippingCost.moneyValueAndSymbol;
	    }
	    
	    costTD.appendChild(document.createTextNode(shippingCost));
	    newRow.appendChild(costTD);
	    shippingOptionsTable.appendChild(newRow);
	}
}

function showFreightShippingOptions(shoppingCart, handlingOptionsTable) {
	if (!shoppingCart.shipByFreight) {
		return;
	}
	var handlingOptions = shoppingCart.selectedShippingServiceLevel.freightHandlingOptions;
	var enabledHandlingOptions = shoppingCart.selectedShippingServiceLevel.enabledHandlingOptions;
	var selectedHandlingOptions = shoppingCart.selectedShippingServiceLevel.selectedHandlingOptionsBitmap;
	var currency = shoppingCart.subtotalDiscountMoney.currency.symbol;
	for (i = 0; i < handlingOptions.length; i++) {
		var option = handlingOptions[i];
		if (!isOptionInMap(option.bitMask, enabledHandlingOptions)) {
			continue;
		}
		var newRow = document.createElement("tr");
		var newTd = document.createElement("td");
		var nameTD = document.createElement("td");
		var priceTD = document.createElement("td");
		nameTD.className = "type";
		priceTD.className ="rate";
		var checkNode = document.createElement("input");
	    checkNode.type = "checkbox";
	    checkNode.name = "freightShippingOption";
	    checkNode.id = "freightShippingOption" + i;
	    checkNode.value = option.bitMask;
	    checkNode.onclick = function(e) {
            onFreightShippingOptionSelect();			
		}
		newTd.appendChild(checkNode);
   	    checkNode.checked = isOptionInMap(option.bitMask, selectedHandlingOptions);
		var labelNode = document.createElement("label");
		labelNode.setAttribute("for", "freightShippingOption" + i);
		labelNode.appendChild(document.createTextNode(option.name));
		nameTD.appendChild(labelNode);
		priceTD.appendChild(document.createTextNode(currency + option.cost));
		newRow.appendChild(newTd);
		newRow.appendChild(nameTD);
		newRow.appendChild(priceTD);
		handlingOptionsTable.appendChild(newRow);
	}
}

function isOptionInMap(option, map) {
	return ((option & map) != 0);
}

function updateEstimateAddress(addressStr) {
        var estimationAddress, estimationAddressNode = document.getElementById("estimationAddressNode");
        estimationAddressNode.innerHTML = addressStr;
}

function updateCartItemPrice(cartItemPrices) {
	var cartItemPriceId = "cartItems[INDEX].price";
	for (var i = 0; i < cartItemPrices.length; i++) {
		var priceNode = document.getElementById(cartItemPriceId.replace("INDEX", i));
		if (priceNode) {
			document.getElementById(cartItemPriceId.replace("INDEX", i)).innerHTML = cartItemPrices[i].moneyValueAndSymbol;
		}
	}
}

function updateCartSummary (shoppingCart) {
	if (shoppingCart.inclusiveTaxCalculationInUse == false
		&& shoppingCart.subtotalDiscountMoney != null && shoppingCart.subtotalDiscountMoney.amount > 0) {
	    document.getElementById("promotion-exclusive").style.display="";
	    var discountDiv=document.getElementById("exclusive-discount-value");
	    discountDiv.innerHTML= shoppingCart.subtotalDiscountMoney.moneyValueAndSymbol;
	} else {
	    document.getElementById("promotion-exclusive").style.display="none";
	}

	var subtotalDiv=document.getElementById("subTotalValue");
	subtotalDiv.innerHTML=shoppingCart.subtotalMoney.moneyValueAndSymbol;

	document.getElementById("shipping").style.display="";
	var shippingDiv=document.getElementById("cartShippingCostValue");
	shippingDiv.innerHTML=shoppingCart.baseShippingCost.moneyValueAndSymbol;
	
	if (shoppingCart.shipByFreight) {
		document.getElementById("handling").style.display="";
	} else {
		document.getElementById("handling").style.display="none";
	}

	var handlingDiv=document.getElementById("cartHandlingCostValue");
	
	if (shoppingCart.selectedShippingServiceLevel) {
		handlingDiv.innerHTML=shoppingCart.selectedShippingServiceLevel.totalHandlingCost.moneyValueAndSymbol;
	} else {
		handlingDiv.innerHTML = "$0.00";
	}

	var cartSummaryTable = document.getElementById("cart-summary-table");
   	var rows = cartSummaryTable.getElementsByTagName("tr");
   	var taxRows = new Array();
   	for (var i = 0; i < rows.length; i++){
     	    if(rows[i].id && rows[i].id.match(/tax\d+/)) {
      		rows[i].parentNode.deleteRow(i);
      		i--;
     	    }
     	}
		var hasTax = false;
		var naTaxNode = document.getElementById("tax-na");
		var count = 1;
		if (shoppingCart.localizedTaxMap) {
	    for (var taxCategoryName in shoppingCart.localizedTaxMap) {
	    	hasTax = true;
		    var newRow = cartSummaryTable.tBodies[0].insertRow(naTaxNode.sectionRowIndex);
		    newRow.className = "tax";
		    newRow.id = "tax" + count;
		    count++;

		    var tcTD = newRow.insertCell(0);
	    	    tcTD.setAttribute("class", "title");
	    	    tcTD.appendChild(document.createTextNode(taxCategoryName + ":"));

	    	    var valueTD = newRow.insertCell(1);
	    	    valueTD.setAttribute("class", "value");
	    	    valueTD.appendChild(document.createTextNode(shoppingCart.localizedTaxMap[taxCategoryName].moneyValueAndSymbol));
	    }
	}
	if (hasTax) {
	    document.getElementById("tax-na").style.display="none";
	} else {
	    document.getElementById("tax-na").style.display="";
	}

	if (shoppingCart.inclusiveTaxCalculationInUse == true
		&& shoppingCart.subtotalDiscountMoney != null && shoppingCart.subtotalDiscountMoney.amount > 0)  {
	    document.getElementById("promotion-inclusive").style.display="";
	    var discountDiv=document.getElementById("inclusive-discount-value");
	    discountDiv.innerHTML=shoppingCart.subtotalDiscountMoney.moneyValueAndSymbol;
	} else {
	    document.getElementById("promotion-inclusive").style.display="none";
	}

	var giftCertificateRedeemDiv=document.getElementById("gift-certificate-value");
	if (giftCertificateRedeemDiv) {
		giftCertificateRedeemDiv.innerHTML=shoppingCart.giftCertificateDiscountMoney.moneyValueAndSymbol;
	}

	var totalBeforeTaxDiv=document.getElementById("totalBeforeTaxValue");
	totalBeforeTaxDiv.innerHTML=shoppingCart.beforeTaxTotal.moneyValueAndSymbol;

	var totalDiv=document.getElementById("cartTotalValue");
	totalDiv.innerHTML=shoppingCart.totalMoney.moneyValueAndSymbol;
}

function onShippingServiceLevelSelect(selectedRadionObj) {
    shoppingCartAjaxController.calculateForSelectedShippingServiceLevel(selectedRadionObj.value, updateCartSummary);
    selectedRadionObj.checked =true;
}

function changeEstimationAddress() {
	shoppingCartAjaxController.changeEstimationAddress(changeEstimationAddressCallBack);
}

function changeEstimationAddressCallBack(shoppingCart) {
	document.getElementById("calculate-shipping").style.display="block";
        document.getElementById("shipping-rates").style.display="none";
        updateCartSummary(shoppingCart);
}

// used to override the incorrectly behaving IE version
document.getElementsByName = function(name) {
	name = new String(name);
	var matches = new Array();
	var elements = document.getElementsByTagName("*");
	var size = elements.length;
	for (var i = 0; i < size; i++) {
		if (elements[i].name == name || elements[i].getAttribute("name") == name) {
			matches[matches.length] = elements[i];
		}
	}
	return matches;
}

function onFreightShippingOptionSelect() {
	var shippingOptions = document.getElementsByName("freightShippingOption");
	var parameters = 0;
	for (i = 0; i < shippingOptions.length; i++) {
		if (shippingOptions[i].checked) {
			parameters |= shippingOptions[i].value;
		}
	}
	shoppingCartAjaxController.calculateForSelectedFreightShipping(parameters, updateCartSummary);
}

// [ACELABEX-184] Begin
/**************************************************
 * Miscellaneous functions
 */
	function clearCart() {
	  document.shoppingCart.cartAction.value = "clearAceMartCart.x";
      document.shoppingCart.submit();
    }
// [ACELABEX-184] End
