/**************************************************
 * 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(selectedDropDownObj) {
    document.getElementById("selectedShippingServiceLevel").disabled=false;
    if (selectedDropDownObj.value == "") {
        var shippingOptionsDropDown = document.getElementById("selectedShippingServiceLevel");
        while(shippingOptionsDropDown.hasChildNodes()){ shippingOptionsDropDown.removeChild(shippingOptionsDropDown.firstChild); }
        document.getElementById("selectedShippingServiceLevel").disabled=true;
        return;
    }
    var cartItemQtyArray = getCartItemQty();
    var countryCode=document.getElementById("country").value;
    var subCountryCode="";
    if (countryCode) {
          subCountryCode = document.getElementById("subCountry_"+countryCode).value;
    }
    if (countryCode) {
        DWREngine.beginBatch();
        shoppingCartAjaxController.estimateShippingAndTaxes(countryCode, subCountryCode, "",cartItemQtyArray, estimateShippingAndTaxesCallBack);
        shoppingCartAjaxController.getCartItemPrices(updateCartItemPrice)
        DWREngine.endBatch({verb:"GET", ordered:true});
    } else {
        alert(specifyShippingStr);
    }
}

function estimateShippingAndTaxesCallBack(shoppingCart) {
    if (shoppingCart.selectedShippingServiceLevel) {
        selectedShippingServiceLevelId = shoppingCart.selectedShippingServiceLevel.uidPk;
        //alert(DWRUtil.toDescriptiveString(shoppingCart.shippingAddress, 2));
        if (shoppingCart.shippingServiceLevelList.length > 0) {
            updateCartSummary(shoppingCart);
            showDeliveryOptions(shoppingCart);
        }
    } else {
        alert(noDeliveryOptionStr);
    }
}

function showDeliveryOptions(shoppingCart) {
        var shippingServiceLevels = shoppingCart.shippingServiceLevelList
        var shippingOptionsDropDown = document.getElementById("selectedShippingServiceLevel");
        while(shippingOptionsDropDown.hasChildNodes()){ shippingOptionsDropDown.removeChild(shippingOptionsDropDown.firstChild); }
        if (shippingServiceLevels && shippingServiceLevels.length > 0) {

            //alert(DWRUtil.toDescriptiveString(shippingServiceLevels, 4));
            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 = " selected";
                            }
                        } else {
                            if (isFirst) {
                                        checkedStr = " selected";
                                isFirst = false;
                            }
                        }
                var newRow = document.createElement("option");
                newRow.value=shippingServiceLevel.uidPk;
                newRow.name="selectedShippingServiceLevel";
                newRow.onclick="onShippingServiceLevelSelect(this);";
                newRow.appendChild(document.createTextNode(shippingServiceLevel.localizedProperties.localizedPropertiesMap[namePropertyKey].value));
                if (checkedStr.length > 0) {
                    newRow.selected = true;
                }
                newRow.id=shippingServiceLevel.uidPk;
                shippingOptionsDropDown.appendChild(newRow);
            }
        } else {
               document.getElementById("selectedShippingServiceLevel").disabled=true;
        }
}

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.beforeTaxShippingCost.moneyValueAndSymbol;

    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\w+/)) {
             rows[i].parentNode.deleteRow(i);
            i--;
        }
    }
    var naTaxNode = document.getElementById("listTax");
    naTaxNode.style.display="none";
    var count = 1;
    if (shoppingCart.localizedTaxMap) {
        for (var taxCategoryName in shoppingCart.localizedTaxMap) {
            var newRow = cartSummaryTable.tBodies[0].insertRow(naTaxNode.sectionRowIndex);
            newRow.id = "tax_" + taxCategoryName;
            count++;
            var tcTD = newRow.insertCell(0);
            tcTD.className = 'label';
            tcTD.appendChild(document.createTextNode(taxCategoryName + ":"));
            var valueTD = newRow.insertCell(1);
            valueTD.className = 'total';
            valueTD.appendChild(document.createTextNode(shoppingCart.localizedTaxMap[taxCategoryName].moneyValueAndSymbol));
        }
    }
    
    
    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;
    
    var cartSummaryTable = document.getElementById("cart-summary-table");
}

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);
}

function roundNumber(number,decimals) {
        var newString;// The new rounded number
        decimals = Number(decimals);
        if (decimals < 1) {
               newString = (Math.round(number)).toString();
        } else {
               var numString = number.toString();
               if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
                       numString += ".";// give it one at the end
               }
               var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
               var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with
               var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want
               if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
                       if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
                               while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
                                      if (d1 != ".") {
                                              cutoff -= 1;
                                              d1 = Number(numString.substring(cutoff,cutoff+1));
                                      } else {
                                              cutoff -= 1;
                                      }
                               }
                       }
                       d1 += 1;
               } 
               newString = numString.substring(0,cutoff) + d1.toString();
        }
        if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
               newString += ".";
        }
        var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;
        for(var i=0;i<decimals-decs;i++) newString += "0";
        //var newNumber = Number(newString);// make it a number if you like
        return newString; // Output the result to the form field (change for your purposes)
}