// Counter for each item added. Needed, as we have to pass unique item names to PayPal
var counter = 0;
var promo;
var total=0;

// Strip any leading dollar signs
function clean_price(price) {
	if (price.charAt(0) == "$") {
		return price.slice(1)
	} else {
		return price
	}
}

function calc_price() {
	// Hide the cart if we have zero items, otherwise, show it
	if ( $('#shopping_cart ul li').length > 0 ) {
		$('#submit_button').fadeIn('fast')
	} else {
		$('#submit_button').fadeOut('fast')
	}
	// Grab each "price" field in the shopping cart, strip any leading dollar signs, and add them to the total
	$('#shopping_cart ul li input[name$="price]"]').each(function() {
		price = $(this).val();
		
		if (promo == "5CRAB" || promo=="5crab"){
		price -= price * .15;	
		}	
		
	})
	total += parseFloat(price);
	// Replace the displayed total
	$('#total span').text('$' + total)
}

// This takes all the items, and on submisson, orders them numerically
// Not particularly required, but if the first item isn't numbered "1", PayPal barfs out
function reorder_items(form) {
	$(form).find('li').each(function(i) { 
		item_pattern = /_(\d+)$/; // Matches an underscore and trailing digits at the end of a string
		i = i + 1; // Our counter starts at zero, and we need it to start at one, so we increment
	
		// Grab all input elements in our list item
		$(this).find('input').each(function() {
			// If this input has a name with a trailing underscore and digits (like amount_1, or item_name_1)...
			if ( item_pattern.test( $(this).attr('name')) ) {
				// Take the name, replace the matched segment with "_i", and set it as the input's new name attribute
				$(this).attr({ name: $(this).attr('name').replace(item_pattern, "_" + i ) }) 
			}
		})
	})
}

// Add the handler to remove items from the cart
function add_remove_link(item) {
	$(item).append("<a href='#' class='remove' title='Remove from cart'>Remove</a>")

	$(item + ' .remove').click(function() { // Add our on_click handler to all "remove" links on the page
		$(item).fadeOut('fast', function() {
			$(item).remove();
			calc_price(); // Update the total
		})
		
		return false; // Stop the link from acting like a jump link
	})
}

// Adds a single item to the cart, extracts all its variables from the alt tag on the item's "Add to cart" button
function add_item(item) {
	// Break the alt tag down into useful variables, and strip any leading dollar signs from the values
	var item_info = $(item).attr('alt').split(' - ')
	var item_id = "item_" + counter
	var name = item_info[0]
	var price = clean_price(item_info[1])

	counter++; // Increment our global item counter so we can pass a unique amount_x, and item_name_x to PayPal

	// Create a new li in the shopping cart with the item's name, price, hidden variables, and a link to remove the item
	$('#shopping_cart ul').append("<li id='" + item_id + "'><strong>" + name + "</strong><span class='price'>$" + price + "</span></li>")
	$('#shopping_cart ul #' + item_id)
		.append("<input name='items[" + item_id + "_name]' value='" + name + "' type='hidden'>")
		.append("<input name='items[" + item_id + "_price]' value='" + price + "' type='hidden'>")
		.append("<input name='items[" + item_id + "_promo]' value='" + promo + "' type='hidden'>")

	add_remove_link("#shopping_cart ul #" + item_id) // Add a way to remove the item
	calc_price(); // Retally the cart
}

// Adds a single item to the cart, gets called from the form validation function
function add_giftcard(form) {
	var price =		clean_price($("#card_value").val());
	var to =		$("#card_name").val();
	var from =		$("#card_from").val();
	var message =	$("#card_message").val();
	promo =			$("#card_promo").val();
	var item_id =	"item_" + counter;
	
	counter++; // Increment our global item counter so we can pass a unique amount_x, and item_name_x to PayPal

	// Create a new li in the shopping cart with the item's name, price, hidden variables, and a link to remove the item
	$('#shopping_cart ul').append("<li id='" + item_id + "'><strong>Gift Certificate for:<br /> " + '"' + to + '"' + "</strong><span class='price'>$" + price + "</span></li>")
	$('#shopping_cart ul #' + item_id)
		.append("<input name='items[" + item_id +"_name]' value='Gift Certificate for <em>" + '"' + to + '"' + "</em> from <em>" + '"' + from + '"' + "</em>' type='hidden'>")
		.append("<input name='items[" + item_id +"_price]' value='" + price + "' type='hidden'>")
		.append("<input name='items[" + item_id +"_to]' value='" + to + "' type='hidden'>")
		.append("<input name='items[" + item_id +"_from]' value='" + from + "' type='hidden'>")
		.append("<input name='items[" + item_id +"_message]' value='" + message + "' type='hidden'>")
		.append("<input name='items[" + item_id +"_promo]' value='" + promo + "' type='hidden'>")

	$("#gift_card input[value], #gift_card textarea").val("") // Clean out the form once we're done with it

	add_remove_link("#shopping_cart ul #" + item_id) // Add a way to remove the item
	calc_price(); // Retally the cart
}

// Draw and prep our shopping cart
function init() {
	// Cart listing
	$("#shopping_cart")
	  .append('<ul></ul>')
	  .append('<div id="submit_button"></div>')

	// Total and check-out button 
	$("#submit_button")
	  .append('<h5 id="total">Total: <span>$0</span></h5>')
	  .append('<input type="image" src="images/button_checkout.gif" border="0" name="submit" alt="Checkout" />')

	// Hide the shopping cart initally, as it has no items
	$('#shopping_cart #submit_button').fadeOut(0);	

	// Submit event handler
	$("#shopping_cart").submit(function() { reorder_items( this ) });
}

$(function() {
// =======================================================================
// Runtime code
// =======================================================================
	init();	// Prep the HTML environment

// =======================================================================
// Gift cards are handled here
// =======================================================================

	// Intercept submissions on the gift card form and have add_giftcard() handle the form instead
	$.validator.setDefaults({
		onsubmit: true,
		submitHandler: function() {
			add_giftcard();
			return false;
		}
	});

	// Lets add some default values to help the users
	$('#gift_card input, #gift_card textarea').each(function() {
		$(this).val( $(this).attr('title') )
		$(this).css({ color: '#999' })
		$(this).focus(function() {
			// Switch back to black on focus, kill our default value, and remove the bound function
			if( $(this).is('#card_value') ) {			
				$(this).val('$').css({ color: '' }).unbind() // Stuff a dollar sign on the front for the card value
			} else {
				$(this).val('').css({ color: '' }).unbind()
			}
		})
	})
		
		
	// Add a method to jQuery validate to test for a valid price
	jQuery.validator.addMethod("validprice", function(value, element) {
		var price = clean_price(value) // Strip that meddlesome "$"
			
		// Test for a string comprised of digits and optional commas and trailing decimal point and 2 following digits
		if ( /^\d+(\.?\d{2})?$/i.test(price) && (parseInt(price) > 0) ) {
			return value
		} else {
			return false
		}
	}, "Please enter a valid amount");
	
	// Check to make sure we're not looking at the default values for these elements
	jQuery.validator.addMethod("updated_value", function(value, element) {
		if ( $(element).val() == $(element).attr('title') ) {
			return false;
		} else {
			return value
		}
	});

	
	// Gift Card form validation rules, all form validation is handled by the jQuery validate library
	$('#gift_card').validate({
		rules: {
			card_value: {
				required:true,
				validprice:true,
				updated_value:true
			},
			card_name: {
				required:true,
				updated_value:true,
				maxlength: 50
			},
			card_from: {
				required:true,
				updated_value:true,
				maxlength: 50
			},
			card_message: {
				required:true
			}
		},
		messages: {
			card_value:	"Please enter a dollar amount for your gift certificate",
			card_name: "Please tell us who the gift certificate is being sent to",
			card_from: "Please tell us who the gift certificate is being sent by",
			card_message: "Please enter a message to go along with your gift certificate"
		}
	});

// =======================================================================
// All other items get added here
// =======================================================================

	$('img[src$="button_add_to_cart.gif"]').each(function(i) {	// Add a click handler to images, based on the image name
		$(this).css({ cursor: "pointer" }) // Make the image look like a link
		$(this).click(function() { add_item(this) })
	})
});

