/**
 * Function to be used on the shopping cart page.
 */
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() {
	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 (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);
    }
}

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) {
     	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("alert").style.display="none";

            //alert(DWRUtil.toDescriptiveString(shippingServiceLevels, 4));
            var namePropertyKey = "displayName_" + 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 radioNode, radioTD = document.createElement("td");
                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]));
                nameTD.className='type';
				newRow.appendChild(nameTD);

                var costTD = document.createElement("td");
                costTD.className='rate';
                costTD.appendChild(document.createTextNode(shippingServiceLevel.shippingCost.moneyValueAndSymbol));
                newRow.appendChild(costTD);
                shippingOptionsTable.appendChild(newRow);
            }
        } else {
            document.getElementById("shippingOptionsTable").style.display="none";
            document.getElementById("alert").style.display="block";
        }
}

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++) {
		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.beforeTaxSubTotal.moneyValueAndSymbol;

	document.getElementById("shipping").style.display="";
	var shippingDiv=document.getElementById("cartShippingCostValue");
	shippingDiv.innerHTML=shoppingCart.shippingCost.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\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 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);
}