// Add event handlers for the page load and the coupon form
Event.observe(window, "load", function(event) {
	// Reset the amount to the original amount in case the amount was changed and the page is being refreshed; this will
	// essentially prevent the browser from being able to cache the amount
	$("amount").value = $("originalAmount").value;
	// Add event handler to coupon form
	Event.observe("coupon", "submit", function(event) {
		Promotion.applyCode();
		Event.stop(event);
	});
});

Event.observe(window, "unload", function(event) {
	$("amount").value = $("originalAmount").value;
});

var Promotion = {
	
	applyCode: function() {
		// Get coupon code entered
		var code = $("coupon").select('[type="text"]')[0].value;
		// Only process request if code is supplied and the amount hasn't already been discounted
		if (code && $("originalAmount").value == $("amount").value) {
			var url = "api.php?action=applyCode&code=" + encodeURIComponent(code);
			new Ajax.Request(url, {
				method: "get",
				onSuccess: function(transport) {
					var promo = transport.responseText.evalJSON();
					// Only process if promo is enabled
					if (promo.isEnabled == "1") {
						var price = $("amount").value;
						var priceHtml = "<s>$" + price + "</s><br />";
						if (promo.discountTypeId == 1) {	// Fixed
							price = price - promo.amount;
						} else {
							price = price - (price * (promo.amount / 100));
						}
						priceHtml += "$" + price.toFixed(2);
						$("amount").value = price.toFixed(2);
						$("priceLabel").innerHTML = priceHtml;
						$("couponWrapper").select('.message')[0].innerHTML = promo.description;
						$("itemName").value += " [Coupon Code: " + code + " - " + promo.description + "]";
					}
				}
			});
		}
	}
}