$(document).ready(function(){
	// Get product cost
	var amountObjects = $('form[target="paypal"] input[name="amount"]');
	var amounts = amountObjects.map(function(){return $(this).attr("value");});
	var originalAmounts = amounts;
	var descriptionObjects = $("#courses .product-description");
	var originalDescriptions = descriptionObjects.map(function(){return $(this).html();});
	var itemNameObjects = $('form[target="paypal"] input[name="item_name"]');
	var originalItemNames = itemNameObjects.map(function(){return $(this).attr("value");});
	$("#coupon form").bind("submit", function(){
		// Reset current amounts to their original amounts so they are not discounted further if user presses submit button more than once
		amountObjects.map(function(index){$(this).attr("value", originalAmounts[index]);});
		// Reset descriptions
		descriptionObjects.map(function(index){$(this).html(originalDescriptions[index]);});
		// Reset item names
		itemNameObjects.map(function(index){$(this).attr("value", originalItemNames[index]);});
		//amount = amountObject.attr("value");
		//descriptionObject.html(originalDescription);
		//itemNameObject.attr("value", originalItemName);
		$("#coupon .message").text(" ");
		$("#coupon .error").text(" ");
		var coupon = null;
		var code = $("#promocode").attr("value");
		// Only continue if a code was entered
		if (!code) {
			return false;
		} else {
			// Find the coupon
			for (i=0;i<coupons.length;i++) {
				if (coupons[i].code == code) {
					coupon = coupons[i];
				}
			}
			if (coupon) {
				// Loop through products
				for (i=0;i<amountObjects.length;i++) {
					var amount = amountObjects.eq(i).attr("value");
					//alert(amountObjects.eq(i).attr("value"));
					descriptionObjects.eq(i).html('<s>' + originalDescriptions[i] + '</s><br />' + coupon.message);
					if (coupon.discountAmount) {
						// Subtract a fixed dollar amount
						amount = amount - coupon.discountAmount;
						// Append discount to item name
						itemNameObjects.eq(i).attr("value", originalItemNames[i] + "($" + coupon.discountAmount + " Discount)");
					} else if (coupon.discountPercent) {
						// Subtract a percentage
						amount = amount - (amount * coupon.discountPercent);
						// Append discount to item name
						itemNameObjects.eq(i).attr("value", originalItemNames[i] + "(" + (coupon.discountPercent * 100) + "% Discount)");					
					} else if (coupon.discountMultiplier) {
						// Multiply the course amount
						amount = amount * coupon.discountMultiplier;
						// Append coupon message to item name
						itemNameObjects.eq(i).attr("value", originalItemNames[i] + "(" + coupon.message + ")");					
					}
					// Set the new amount
					amountObjects.eq(i).attr("value", amount);
				}
			} else {
				$("#coupon .error").text("Sorry, but that coupon code does not exist.  Please check the code and try again.");
			}
		}
		return false;
	});
});
