$(document).ready(function () {
	$('#getCoupon').click(function(){
		Coupon.checkCode();
	});
});

var Coupon = new Object();

Coupon = {
	checkCode: function () {
		var couponCode = $('#couponCode').val();
		
		$.post("logic/coupon_f.php", {couponCode: couponCode, requestType: 'ajax'}, 
		function(data){
			$('#couponErr').remove();
			$('#couponMsg').remove();
			if(data.status == "failure"){
				Coupon.invalidCode(data);
			} else {
				Coupon.updateCart(data);
				$('#getCoupon').unbind('click');
			}
		}, 'json');
	},
	
	invalidCode: function(data) {
		var error = '<p id="couponErr" style="display:none"><span>'+data.msg+'</span></p>'; //coupons has been used, coupon not valid, coupon date expired
		$('#couponMsg').remove();
		$('#getCoupon').after(error);
		$('#couponErr').fadeIn();
	},
	
	updateCart: function (data) {
		var msg = '<p id="couponMsg">'+data.msg+'<span>-$'+data.total_discount.toFixed(2)+'</span></p>';
		$('#getCoupon').after(msg);
				
		if(isNaN($('#shipRate').html()) == false){
			$('#shipRate').hide();
			$('#shipRate').html(parseFloat($('#shipRate').html()) - parseFloat(data.shipping_discount));
			$('#shipRate').html(parseFloat($('#shipRate').html()).toFixed(2)).fadeIn();			
		}
		$('#gTotal').hide();
		$('#gTotal').html(parseFloat($('#gTotal').html()) - parseFloat(data.total_discount));
		$('#gTotal').html(parseFloat($('#gTotal').html()).toFixed(2)).fadeIn();
	}
} 