$(document).ready(function(){
	
	// Hide/show sign in window on checkout (only if no errors reported)
	if (!$("#cart .error").length) {
		$("#cart-login").hide();
		// Show extra checkout button if not logged in
		if (!$("#cart_checkout").length) $("#cart").append("<input type=\"button\" value=\"I'm Done! Checkout!\" id=\"cart_checkout\" name=\"cart_checkout\" onclick=\"$('#cart-login').slideDown(); $(this).fadeOut();\"/>");
	}
	
	// Show removal confirmation
	$("a.remove").click(function() {
	
		if (!confirm("Are you sure you want to remove this item from your cart?")) return false;
		
	});
	
	// Replace quantity fields with a nice +/- field
	$("td.quantity").each(function() {
		
		if (!$(this).children("div").length) return;
	
		// Hide current input field
		$(this).children("div").hide();
		
		// Get current quantity
		quantity = $(this).find(".quantity").val();
		
		// Write HTML for nice add/subtract box
		$(this).append("<div class=\"crementor\"><span class=\"decrease\" title=\"Remove one!\" onclick=\"quantityDecrease(this);\">decrease</span><span class=\"quantity\"></span><span class=\"increase\" title=\"Add another!\" onclick=\"quantityIncrease(this);\">increase</span></div>");
		
		// Set quantity
		setQuantity(this, quantity);
		
	});

	// Update the total and send it to the server on quantity change
	$("input.quantity").keyup(function() {
		
		 newQuantity = $(this).val();
		 quantityField = $(this);
		 
		 if (newQuantity && !isNaN(newQuantity) && newQuantity > 0) {
		 	
		 	totalPrice = 0;
		 	totalQuantity = 0;
		 	
		 	// Update cart through AJAX
		 	$.getJSON("/shop/cart/?method=ajax&" + $(this).attr("name") + "=" + newQuantity, function(results) {
		 		
		 		if (newQuantity != quantityField.val()) return false;
		 		
		 		// Modify quantities if necessary
		 		if (results.updatedquantity) {
		 			setQuantity(quantityField.parents("td.quantity"), results.updatedquantity);
		 			updateCartDisplay();
		 		}
		 		
		 		// Display error messages if present
		 		if (results.errors) {
		 			for (var i = 0; i < results.errors.length; i++) {
		 				alert(results.errors[i].message);
		 			}
		 		}
		 			
		 	});
		 	
		 	updateCartDisplay();
		 	
		}
		
	});

});

// Decrease quantity for an item
function quantityDecrease(e) {

	// Find quantity value
	quantity = parseInt($(e).siblings("span.quantity").text());
	
	// Set quantity
	setQuantity($(e).parents("td.quantity"), quantity - 1);
	
	// Call quantity change
	$(e).parents("td.quantity").find("input.quantity").keyup();
	
}

// Increase quantity for an item
function quantityIncrease(e) {

	// Find quantity value
	quantity = parseInt($(e).siblings("span.quantity").text());
	
	// Set quantity
	setQuantity($(e).parents("td.quantity"), quantity + 1);
	
	// Call quantity change
	$(e).parents("td.quantity").find("input.quantity").keyup();
	
}

// Set the quantity for an item
function setQuantity(e, quantity) {

	if (quantity < 0) return false;
	
	$(e).find("span.quantity").text(quantity);
	$(e).find("input.quantity").val(quantity);
	
	// Change decrease to remove for quantities of 1
	if (quantity == 1) {
		$(e).find(".decrease").unbind().attr("onclick", "").text("remove").removeClass("decrease").addClass("remove").attr("title", "Remove this!").click(function() {
			if (confirm("Are you remove you want to remove this item from your cart?")) window.location = $(this).parents("tr").find("a.remove").attr("href");
			
		});
	}
	else {
		$(e).find(".remove").text("decrease").removeClass("remove").addClass("decrease").attr("title", "Remove one!").unbind("click").click(function() {
			quantityDecrease(this);
		});
	}
	
}

// Update cart display
function updateCartDisplay() {
	
	totalPrice = 0;
	totalQuantity = 0;
	
	// Check quantities on each item
 	$("tbody tr").each(function(){
 		
 		itemPrice = parseInt($(this).find(".price").text().replace(/\$|\.|\s/g, ""));
 		
 		if ($(this).find("input.quantity").length) itemQuantity = parseInt($(this).find("input.quantity").attr("value"));
 		else itemQuantity = 1;
 		
 		itemTotal = itemPrice * itemQuantity;
 		totalPrice += itemTotal;
 		totalQuantity += itemQuantity;
 		
 		// Write item total to page
 		itemTotalNumber = new Number(itemTotal / 100);
 		$(this).find(".totalcolumn strong").text("$" + itemTotalNumber.toFixed(2));
 		
 	});
 
 	// Write total price to page
 	totalPrice = new Number(totalPrice / 100);
 	$(".cartamount").text("$" + totalPrice.toFixed(2));
 	
 	// Write new quantity to page
 	$(".numitems").text(totalQuantity);
	
}
