$(function () {
	$('.order').blur(function () { updateTotals(); });
	$('#butSubmit').click(function () {
		// Clean up any previous validation.
		$('.error').remove()

		failed = false;

		// Validate Each Field
		$('.req').each(function () {
			fail = false

			name = $(this).attr('name');

			// Locate a field that we're validating.
			target = $('*[name^='+name+']');

			if (target.attr('type') == 'radio')
			{
				if ($('*[name^='+name+']:checked').length < 1)
					fail = true;
			}
			else if (target.attr('type') == 'select-one')
			{
				if (target.val() == 'Select') fail = true;
			}
			else if (target.val().length < 1) fail = true;

			if (fail)
			{
				failed = true
				$(this).after(' <span class="error">This field is required.</span> ');
				target.focus();
			}
		});

		// Cancel Submission
		return !failed;
	});

	$('#copyBilling').click(function () {
		$('#shipContact').val($('#BillToContact').val());
		$('#shipTitle').val($('#BillToTitle').val());
		$('#shipAddress').val($('#BillToAddress').val());
		$('#shipCity').val($('#billCity').val());
		$('#shipState').val($('#billState').val());
		$('#shipZip').val($('#billZip').val());
		$('#shipPhoneDay').val($('#billPhoneDay').val());
		$('#shipPhoneEve').val($('#billPhoneEve').val());
		$('#shipLoc').val($('#billLoc').val());
		return false;
	});
});

function updateTotals()
{
	var total = 0;

	dat = $('#OrderForm').serialize().replace(/ca=([^&]+)/, 'ca=gettotals');
	$.post('order.php', dat, function (dat) {
		total = dat.total;
		shipamount = dat.shipamount;

		$('#pProduct').text('Total Product Cost: $'+total);
		$('#pTotalShipping').text('Shipping Charge: $'+shipamount);
		$('#pTotal').text('Total Order Cost: $'+(shipamount+total));
	}, 'json');
}
