/**
 * @author Justin
 */

function addCheckoutHandlers() {
	$('input#apply_promo').click(function () {
		promo = $('#OrderPromoCode').val();
		$("#price_after_promo").load('/quoter/promos/apply/' + promo + '/' + subtotal, null, calculate_total);
	});
	
	$('input#OrderZip').keyup(update_rates);
	$('input#OrderZip').blur(update_rates);
	
	update_rates();
}

function addShippingHandlers() {
	$("input[name='data[Order][shipping]']").click(function () {
		label = $("label[for='" + this.id + "']");
		rate = parseFloat(label.text().substr(label.text().indexOf('$') + 1));
		
		if ($("#new_subtotal").length) {
			$('#total').html('$' + (parseFloat($("#new_subtotal").html()) + rate).toFixed(2));
		} else if ($("#shipping_discount").length) {
			rate = rate * parseFloat($("#shipping_discount").html()) / 100;
			$('#total').html('$' + (subtotal + rate).toFixed(2));
		} else {
			$('#total').html('$' + (subtotal + rate).toFixed(2));
		}
	});
	
	calculate_total();
}

function calculate_total() {
	if ($("input:checked[name='data[Order][shipping]']").length) {
		label = $("label[for='" + $("input:checked[name='data[Order][shipping]']").attr('id') + "']");
		rate = parseFloat(label.text().substr(label.text().indexOf('$') + 1));
		
		if ($("#new_subtotal").length) {
			$('#total').html('$' + (parseFloat($("#new_subtotal").html()) + rate).toFixed(2));
		} else if ($("#shipping_discount").length) {
			rate = rate * parseFloat($("#shipping_discount").html()) / 100;
			$('#total').html('$' + (subtotal + rate).toFixed(2));
		} else {
			$('#total').html('$' + (subtotal + rate).toFixed(2));
		}
	}
}

function update_rates() {
	if ($('input#OrderZip').val().length == 5) {
		$('#checkout_form, #project_form').ajaxSubmit({
			beforeSend:function(request) {
				request.setRequestHeader('X-Update', 'shipping_rates'); 
				$('#shipping_rates').html("");
				$('#shipping_rates').addClass("loading");
				$('#zip_message, #forOrderZip').fadeTo(250, 0.3); },
			success:function(data, textStatus) {
				$('#shipping_rates').removeClass("loading");
				$('#submit').attr('disabled', false);
				addShippingHandlers(); }, 
			async:true,
			target:'#shipping_rates',
			type:'post',
			url:'/quoter/projects/shipping_rates'
		});
	} else {
		$('#zip_message, #forOrderZip').fadeTo(250, 1);
		$('#shipping_rates').html('');
		$('#submit').attr('disabled', 'disabled');
		$('#total').html('?');
	}
}

$(document).ready(addCheckoutHandlers);