function checkKeyPress(e, qty){
    var keyPressed
    
    if (window.event) // IE
    {
    	keyPressed = e.keyCode;
    } 
    else if(e.which) // Netscape/Firefox/Opera
    {
    	keyPressed = e.which;
    }
	if (keyPressed==13) {
		return CheckQuantity(qty, true);
	} 
}
	
function CheckQuantity(InventoryQty, isKeyPress) {
	var inputQty = document.addSkuToCartForm.qty.value;

	if (document.addSkuToCartForm.qty.options != null) {
			var index = document.addSkuToCartForm.qty.selectedIndex;
			inputQty = document.addSkuToCartForm.qty.options[index].text;
	}

	if ((inputQty != '') && (isNaN(inputQty) != true)
		&& (inputQty > 0) && (inputQty.indexOf(".") == -1)) {
		if ((inputQty <= parseInt(InventoryQty)) || (parseInt(InventoryQty) == -1)) {
			document.addSkuToCartForm.submit();
		}
		else {
			alert('We are sorry but there are not enough items in stock. Please contact us to check on availability.');
			document.addSkuToCartForm.qty.focus();
		}
	}	
	else {
		alert ('Please enter a non-decimal numeric value that is greater than 0.');
		document.addSkuToCartForm.qty.focus();
	}
	if (isKeyPress) {
			return false;
	}
}

function estimateProductShippingAndTaxes(countryCode, skuCode) {
    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.estimateProductShippingAndTaxes(countryCode, subCountryCode, zipOrPostalCode,skuCode, estimateProductShippingAndTaxesCallBack);
			DWREngine.endBatch({verb:"GET", ordered:true});
	    } else {
	    	alert("Please specify the shipping destination.");
	    }
	 } else {
	 	alert("Please specify a valid 5-digit zip code.");
	 }
}

function estimateProductShippingAndTaxesCallBack(shoppingCart) {
    if (shoppingCart.selectedShippingServiceLevel) {
    	selectedShippingServiceLevelId = shoppingCart.selectedShippingServiceLevel.uidPk;
    	//alert(DWRUtil.toDescriptiveString(shoppingCart.shippingAddress, 2));
    	if (shoppingCart.shippingServiceLevelList.length > 0) {
        	document.getElementById("product-calculate-shipping").style.display="none";
        	document.getElementById("product-shipping-rates").style.display="block";
       	 	showDeliveryOptions(shoppingCart);
        }
    } else {
    	alert("No delivery options available for the selected region. Please refine your selection.");
    }
}

function showDeliveryOptions(shoppingCart) {	
 	var shippingServiceLevels = shoppingCart.shippingServiceLevelList
 	var shipByFreight = shoppingCart.shipByFreight;
 	var dropShipped = shoppingCart.dropShipped;
	var shippingOptionsTable = document.getElementById("productShippingRateOptionsBody");
    while(shippingOptionsTable.hasChildNodes()){ shippingOptionsTable.removeChild(shippingOptionsTable.firstChild); }
    if (shipByFreight) {
    	var handlingOptionsTable = document.getElementById("productHandlingOptionsBody");
    	while(handlingOptionsTable.hasChildNodes()){ handlingOptionsTable.removeChild(handlingOptionsTable.firstChild); }
    }
    if (shippingServiceLevels && shippingServiceLevels.length > 0) {
                document.getElementById("productShippingRateOptions").style.display="";
        if (shipByFreight && !dropShipped && shippingServiceLevels[0].carrier != "N/A") {
        	document.getElementById("")
        	document.getElementById("productHandlingOptions").style.display="";
        	document.getElementById("productHandlingOptionsDiv").style.display="";
        } else {
        	document.getElementById("productHandlingOptionsDiv").style.display="none";
        }
        //document.getElementById("estimatenoservicealert").style.display="none";
        showShippingLevels(shoppingCart, shippingOptionsTable);
        if (shipByFreight) {
        	showFreightShippingOptions(shoppingCart, handlingOptionsTable);
        }
        //alert(DWRUtil.toDescriptiveString(shippingServiceLevels, 4));

    } else {
        document.getElementById("productShippingRateOptions").style.display="none";
        document.getElementById("productHandlingOptions").style.display="none";
        //document.getElementById("estimatenoservicealert").style.display="block";
    }
}

function showFreightShippingOptions(shoppingCart, shippingOptionsTable) {
	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;
	var messageRow = document.createElement("tr");
	var messageTd = document.createElement("td");
	messageTd.className="productType";
	var messageLabel = document.createElement("label");
	messageLabel.appendChild(document.createTextNode("The following handling options for this item will be available at checkout."));
	messageTd.appendChild(messageLabel);
	messageRow.appendChild(document.createElement("td"));
	messageRow.appendChild(messageTd);
	messageRow.appendChild(document.createElement("td"));
	shippingOptionsTable.appendChild(messageRow);	
	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 = "productType";
		priceTD.className ="productRate";
		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);
		shippingOptionsTable.appendChild(newRow);
	}
}

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 shippingName = shippingServiceLevel.localizedProperties.localizedPropertiesMap[namePropertyKey].value;
	    if (shippingName == "Shipment Quote Pending") {
	    	shippingName = "Rates to this destination unavailable. "
	    	+ "Shipping quote will be sent for your approval after order is placed. "
	    	+ "Contact us for further assistance.";
	    } 
	    
	    newRow.appendChild(createNameTD(shippingName));
	    	    	
	    var costTD = document.createElement("td");
	    costTD.className='productRate';
	    costTD.appendChild(document.createTextNode(shippingServiceLevel.shippingCost.moneyValueAndSymbol));
	    newRow.appendChild(costTD);
	    shippingOptionsTable.appendChild(newRow);
	}
}

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

function changeEstimationAddress() {
	document.getElementById("product-calculate-shipping").style.display="block";
    document.getElementById("product-shipping-rates").style.display="none";
}

function createNameTD(shippingName) {
    var nameTD = document.createElement("td");
    
    if (requiresSplit(shippingName)) {
	var splitIndex = getSplitIndex(shippingName);
	var shippingName1 = shippingName.slice(0, splitIndex);
	var shippingName2 = shippingName.slice(splitIndex);
	nameTD.appendChild(document.createTextNode(shippingName1));
	nameTD.appendChild(document.createElement("br"));
	nameTD.appendChild(document.createTextNode(shippingName2));
    } else {
	nameTD.appendChild(document.createTextNode(shippingName));
    }

    nameTD.className='productType';
    
    return nameTD;
}

function requiresSplit(shippingName) {
    return shippingName.indexOf('(') != -1;
}

function getSplitIndex(shippingName) {
    return shippingName.indexOf('(');
}
