/**************************************************
 * Cart Item quantity change functions.
 */
	function updateCartItemQuantity() {
	  document.shoppingCart.cartAction.value = "updateCartItemQuantity";
      document.shoppingCart.submit();
    }

/**************************************************
 * Promotion/gift certificate code functions.
 */

	function applyCupomCPF() {
	 	document.shoppingCart.cartAction.value = "applyCode";
	 	var vCupom = document.shoppingCart.cupom.value;
	 	if (vCupom.length > 0) {
	 		var firstChar = vCupom.charAt(0);
	 		if (ehDigito(firstChar)) {
	 		 	var vCpf = document.shoppingCart.cpf_titular.value;
	 		 	if (vCpf.length >= 5) {
	 		 		var part = vCpf.substr((vCpf.length)-5,5)
		 		 	document.shoppingCart.code.value = vCupom.concat(part);
				 	document.shoppingCart.submit();
	 		 	} else {
	 		 		alert("Por favor, digite os 5 dígitos!!!");
	 		 	}
	 		} else {
	 		 	document.shoppingCart.code.value = vCupom;
	 			document.shoppingCart.submit();
	 		}
	 	}
    }

 	function ehDigito(pStr){
 		var reDigits = /^\d+$/;
 		if (reDigits.test(pStr)) {
 			return true; 
 		} else if (pStr != null && pStr != "") {
 			return false;        
 		}
 	}
	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 formatShippingCost(shippingCost) {
	if (shippingCost.amount == 0) {
		return "Grátis";
	}
	return shippingCost.moneyValueAndSymbol;
}

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;
    zipOrPostalCode = zipOrPostalCode.replace(/-/gi, "");
    if (zipOrPostalCode) {
    	DWREngine.beginBatch();
		shoppingCartAjaxController.estimateShippingForNetshoes(zipOrPostalCode, cartItemQtyArray, estimateShippingAndTaxesCallBack);
		//shoppingCartAjaxController.getEstimateAddressStr(updateEstimateAddress); LAYOUT QUANDO HOUVER MAIS DE UM SERVICO
		shoppingCartAjaxController.getCartItemPrices(updateCartItemPrice)
		DWREngine.endBatch({verb:"GET", ordered:true});
    } else {
    	alert(specifyShippingStr);
    }
}

function estimateShippingAndTaxesCallBack(shoppingCart) {
    if (shoppingCart.selectedShippingOption) {
    	//selectedShippingOptionId = shoppingCart.selectedShippingOption.uidPk; RETIRADO POIS SO VAI USAR QUANDO HOUVER MAIS DE UM SERVICO
    	//alert(DWRUtil.toDescriptiveString(shoppingCart.shippingAddress, 2)); // JA ESTAVA COMENTADO
    	if (shoppingCart.shippingOptionsList.length > 0) {
        	//document.getElementById("calculate-shipping").style.display="none"; LAYOUT QUANDO HOUVER MAIS DE UM SERVICO
        	//document.getElementById("shipping-rates").style.display="block"; LAYOUT QUANDO HOUVER MAIS DE UM SERVICO
        	//showDeliveryOptionsForNetshoes(shoppingCart); RETIRADO POIS SO VAI USAR QUANDO HOUVER MAIS DE UM SERVICO
        	updateCartSummary(shoppingCart);
    	}
    } else {
    	alert('CEP fora da área de entrega');
    	updateDeliveryTime(deliveryTimeUndefined);
    }
}

function showDeliveryOptionsForNetshoes(shoppingCart) {
 	var shippingOptions = shoppingCart.shippingOptionsList
	var shippingOptionsTable = document.getElementById("shippingOptionsTableBody");
    while(shippingOptionsTable.hasChildNodes()){ shippingOptionsTable.removeChild(shippingOptionsTable.firstChild); }
    if (shippingOptions && shippingOptions.length > 0) {
        document.getElementById("shippingOptionsTable").style.display="";
        document.getElementById("estimatenoservicealert").style.display="none";

        //alert(DWRUtil.toDescriptiveString(shippingServiceLevels, 4));
        var namePropertyKey = "shippingServiceLevelDisplayName_" + localeStr;
        var isFirst = true;
        for (var i=0; i < shippingOptions.length; i++){
    	    var currShippingOption = shippingOptions[i];
            var checkedStr = "";
            if (selectedShippingOptionId > 0) {
	                    if (selectedShippingOptionId == currShippingOption.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=\"onShippingOptionSelect(this);\" " + checkedStr
            	                + "name=\"selectedShippingOption\">");
            	} catch (err){
                radioNode = document.createElement("input");
                radioNode.type="radio";
                radioNode.name="selectedShippingOption";
                radioNode.onclick=function(e){
                          shoppingCartAjaxController.calculateForSelectedShippingOption(e.target.id, updateCartSummary);
                }
                if (checkedStr.length > 0)
                		    radioNode.checked = true;
            }
            radioNode.id=currShippingOption.uidPk;
		                	radioNode.value=currShippingOption.uidPk;
            radioTD.appendChild(radioNode);
		                newRow.appendChild(radioTD);

            var nameTD = document.createElement("td");
            nameTD.appendChild(document.createTextNode(currShippingOption.shippingServiceDomain.description));
            nameTD.className='type';
			newRow.appendChild(nameTD);

            var costTD = document.createElement("td");
            costTD.className='rate';
            costTD.appendChild(document.createTextNode(formatShippingCost(currShippingOption.shippingCostMoney )));
            newRow.appendChild(costTD);
            shippingOptionsTable.appendChild(newRow);
        }
    } else {
        document.getElementById("shippingOptionsTable").style.display="none";
        document.getElementById("estimatenoservicealert").style.display="block";
    }
}

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("estimatenoservicealert").style.display="none";

            //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 = "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){
                              nsShoppingCartAjaxController.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';
                costTD.appendChild(document.createTextNode(shippingServiceLevel.shippingCost.moneyValueAndSymbol));
                newRow.appendChild(costTD);
                shippingOptionsTable.appendChild(newRow);
            }
        } else {
            document.getElementById("shippingOptionsTable").style.display="none";
            document.getElementById("estimatenoservicealert").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++) {
		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=formatShippingCost(shoppingCart.beforeTaxShippingCost );
/*
	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 giftDiv=document.getElementById("giftValue"); 
	if (giftDiv != null) {
		giftDiv.innerHTML=shoppingCart.giftCertificateDiscountMoney.moneyValueAndSymbol;
	}
	
	var crowdMemberDiscountDiv=document.getElementById("cartCrowdMemberDiscountValue");
	if (crowdMemberDiscountDiv != null) {
		crowdMemberDiscountDiv.innerHTML=shoppingCart.crowdMemberDiscountMoney.moneyValueAndSymbol;
	}
	
	var totalDiv=document.getElementById("cartTotalValue");
	if (totalDiv != null) {
		totalDiv.innerHTML=shoppingCart.totalMoney.moneyValueAndSymbol;
	}

	// DELIVERY TIME
	var deliveryTime = shoppingCart.deliveryTimeNS;
	var deliveryTimeL= deliveryTime.toString().replace(".", ",");
	var textoDeliveryTime='';
	if( deliveryTime <= 0 ){
		textoDeliveryTime = deliveryTimeUndefined;
	}
	else if( deliveryTime == 1 ){
		textoDeliveryTime = deliveryTimeL + ' ' + deliveryTimeSufix;
	}
	else if( deliveryTime > 1 ){
		textoDeliveryTime = deliveryTimeL + ' ' + deliveryTimeSufixPlural;
	}
	else if( deliveryTime > 0 && deliveryTime < 1 ){
		if( deliveryTime == fracao1Hora ){
			textoDeliveryTime = deliveryTimeL + ' ' + deliveryTimeHour;
		}
		else{
			textoDeliveryTime = deliveryTimeL + ' ' + deliveryTimeHours;
		}
	}
	updateDeliveryTime(textoDeliveryTime);
}

function updateDeliveryTime(textoDeliveryTime){
	var deliveryTimeDiv = document.getElementById("cartDeliveryTime");
	deliveryTimeDiv.innerHTML = textoDeliveryTime;
}

function onShippingServiceLevelSelect(selectedRadionObj) {
    shoppingCartAjaxController.calculateForSelectedShippingServiceLevel(selectedRadionObj.value, updateCartSummary);
    selectedRadionObj.checked =true;
}

function onShippingOptionSelect(selectedRadionObj) {
    shoppingCartAjaxController.calculateForSelectedShippingOption(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);
}
