$(function() {

  // Firefox LOVES to aggressively cache pages so using the back and forward buttons
  // are super quick. The only problem is when a page has been modified with DHTML,
  // there doesn't seem to be a way to tell Firefox the cached page is invalid in
  // order for a fresh version to be requested if needed.
  //
  // Using this hack to update the wines count in the cart block and the cart status
  // of each visible wine.
  $.getJSON("/cart.js", null, function(response) {
    updateCartQuantity(response.wines.length);

    $("ul.wine-list > li").each(function() {
      var $this = $(this),
        wineID = $this.find("input[name=wine_id]").attr("value");

      if (wineID) {
        wineID = parseInt(wineID, 10);

        var inCart = $.inArray(wineID, response.wines) >= 0,
          actions = $this.find("div.actions");

        if (!actions.is(".not-available")) {
          actions.removeClass("default in-cart").addClass(inCart ? "in-cart" : "default");
        }
      }
    });
  });

	// Add to cart
	$("form.add-to-cart").ajaxForm({
		loading: function() {
			this.parent()
				.removeClass("default")
				.addClass("processing");
		},
		success: function(response) {
		  var parent = this.parent().removeClass("default processing");

      if (response.error) {
        parent.addClass("default");

        var cartExpired = $("#cart-expired");
        cartExpired.modal({
          onOpen: modal.open,
          onClose: modal.close
        });

        return;
      }

      var error = response === false;
      parent.addClass(error ? "error" : "in-cart");

      if (!error) {
        // Update the cart quantity in the header.
        updateCartQuantity(response.wines_in_cart);
      }
		},
		error: function() { }
	});

	var changeQuantityTimeout;
	$("form.update-cart input[name=quantity]").each(function() {
		var $this = $(this),
			currentQuantity = $this.val();

		$this.keyup(function(e) {
			var newVal = $this.val().replace(/[^\d]/g, '');

			if (changeQuantityTimeout) {
				clearTimeout(changeQuantityTimeout);
			}

			changeQuantityTimeout = setTimeout(function() {
				// Only change the value if it needs to be like in the case of
				// removing non-digit characters.
				if (newVal != $this.val()) {
					$this.val(newVal);
				}

				if (newVal != currentQuantity && newVal.length > 0 && newVal > 0) {
					currentQuantity = newVal;
					$this.closest("form").submit();
				}
			}, 250);
		});
	});

	// Update cart
	$("form.update-cart, form.remove-cart").ajaxForm({
		loading: function() {
			this.addClass(this.is(".update-cart") ? "loading" : "processing");
		},
		success: function(response) {
			this.removeClass("loading processing error");

			if (response.error) {
        var cartExpired = $("#cart-expired");
        cartExpired.modal({
          onOpen: modal.open,
          onClose: modal.close
        });

        return;
      }


			var tr = this.closest("tr");
			if (this.hasClass("remove-cart")) {
				// Add class if this was the last wine.
				if (tr.siblings().length == 0) {
					$("body").addClass("empty-cart");
				}

				// Remove wine
				tr.remove();
			} else {
				// Update wine price
				tr.children("td.amount").html(response.price_html);
			}

			// Add error message if the update failed.
			var error = response === false;
			this[(error ? "add" : "remove") + "Class"]("error");

			if (!error) {
				// Update subtotal
				$("dl.totals dd").text("$" + response.subtotal.toFixed(2));

				// Update discount message
				$("#message").replaceWith(response.discount_html);

				// Update the cart quantity in the header.
				updateCartQuantity(response.wines_in_cart);
			}
		},
		error: function() { }
	});

	function updateCartQuantity(quantity) {
		$("#shopping-cart span").text(quantity);
	}
});