$(document).ready(function() {
	$("input.char").each(function() {
		$(this).keyup(function(e) {
			if (e.keyCode != 9 && e.keyCode != 13) {
				var qty = parseInt($(this).val());
				if ($(this).val() != '' && qty != $(this).val()) {
					alert('Please enter an integer value.');
					$(this).focus();
					$(this).val("");
				}
				calculateTotal();
			}
		});
	});
	$("input#NZ").bind("click", updateDeliveryCost);
	$("input#Submit").bind("click", submitForm);
	$("input#Cancel").bind("click", cancelForm);
});

function tallyQuantities() {
	var total = 0;
	$("input.char").each(function() {
		var qty = parseInt($(this).val());
		if (qty > 0) {
			total += qty;
		}
	});
	return total;
}

function calculateTotal() {
	var qty = tallyQuantities();
	var delivery = $("input#NZ:checked").length ? deliveryCostNZ : deliveryCost;
	var total = qty * costPerChar;
	if (qty > 0) total += delivery;
	
	$("input#Number").val(qty);
	$("input#total").val(currencyFormatted(total));
}

function updateDeliveryCost() {
	var target = $("span#deliveryFee"); 
	if ($("input#NZ:checked").length) {
		target.text(currencyFormatted(deliveryCostNZ));
	} else {
		target.text(currencyFormatted(deliveryCost));
	}
	calculateTotal();
}

function submitForm() {
	var errors = new Array();
	var name = $("input#Name").val();
	var email = $("input#Email").val();
	var phone = $("input#Phone").val();
	var address = $("textarea#Address").val();
	var qty = tallyQuantities();
	
	if ( name == '' ) { errors.push("Please enter your Name."); }
	if ( email == '' ) { errors.push("Please enter your Email."); }
	if ( phone == '' ) { errors.push("Please enter your Phone."); }
	if ( address == '' ) { errors.push("Please enter your Address."); }
	if ( qty == 0 ) { errors.push('You must purchase at least 1 item.'); }
	
	if (errors.length) {
		alert(errors.join("\n"));
		return false;
	}
	return true;
}

function cancelForm() {
	history.go(-1);
}

function currencyFormatted(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}