$(document).ready(function(){

  // remove checkbox column from table - we're going to add ajax links instead
  $("#cart tr th:last-child, #cart tr td:last-child").hide();

  // add in ajax remove links
  $("#cart tr.item td.product").find("p:first").after("<p class=\"remove\"><a href=\"\" class=\"remove\">Remove</a></p>");

  /* add click handler to remove links */
  $("a.remove").click(function(event){

    // show "are you sure?" message
    $(this).parents("td.product").find("p:first").after("<p class=\"are-you-sure\">Are you sure? <a href=\"\" class=\"yes\">Yes</a> <a href=\"\" class=\"no\">No</a></p>");

    // get the product id to remove from the checbox we've just hidden
    var product_id = $(this).parents("tr").find(":checkbox").val();

    // bind "yes" click handler
    $(this).parents("td.product").find("p.are-you-sure a.yes").click(function(event){

      // hide the "are you sure?" links
      $(this).parent().hide();

      // setup ajax call
      $.ajax({
        type: 'POST',
        url: '/cart/' + product_id+ '/remove',
        data: 'id=' + product_id,
        dataType: 'json',
        beforeSend: function(xhr){
          xhr.setRequestHeader("Accept", "text/javascript"); // for respond_to block
          $("#cart-item-" + product_id).find("td.product").append("<p><img src=\"/images/progress.gif\" /> Removing</p>");
        },
        success: function(cart){
          if(cart.item_count == 0) {
            window.location = "/cart"
          } else {
            $("#cart-item-" + product_id).fadeOut();
            updateCart(cart);
            discountCodeRemoved(cart);
          }
        },
        error: function(){
          $(this).parents("td.product").find("a.remove").show();
        }
      });
      return false;
    });

    // bind "no" click handler - just revert back
    $(this).parents("td.product").find("p.are-you-sure a.no").click(function(event){
      $(this).parent().hide();
      $(this).parents("td.product").find("a.remove").show();
      return false;
    });

    // hide remove link
    $(this).hide();
    return false;
  });

  /* update postage via ajax on radio button click */
  $("#postage-methods input").click(function(event){
    $.ajax({
      type: 'POST',
      url: '/cart/postage',
      data: 'postage_method_id=' + this.value,
      dataType: 'json',
      beforeSend: function(){
        $("#options").append("<p class=\"progress working\"><img src=\"/images/progress.gif\" /> Updating Postage</p>");
      },
      success: function(cart){
        postageUpdated(cart);
      }
    });
  });

  // Clear the discount code box when selected
  $("#discount_code").focus(function(event){
    $("#discount_code").val("");
  });

  // Hide another message
  hideCartAddedNewItem();

  // Hide any notices
  hideNotices();

  // Hide any out of stock notices
  hideOutOfStockNotices();
});

function hideCartAddedNewItem(){
  setTimeout(function(){
    $("#continue-shopping").fadeOut("slow");
  }, 9000);
}

function hideNotices(){
  setTimeout(function(){
    $(".notice").fadeOut("slow");
  }, 5000);
}

function hideOutOfStockNotices(){
  setTimeout(function(){
    $("#cart-error").fadeOut("slow");
    $("p.available").remove();
    $("td.out-of-stock").removeClass("out-of-stock").width("100px");
  }, 5000);
}

function postageUpdated(cart){

  // Update the cart totals
  updateCart(cart);

  // Tell the user the postage was updated
  if(cart.postage_changed) {
    showCartError("Sorry, you can't use Second Class post as your cart is too heavy");
    $("#cart_postage_method_id_1").attr("checked", "checked").blur();
  }

  // Highlight the postage total <td>'s to show it's changed
  $("#postage").parents("tr").find(".total, #postage").highlightFade({ speed: 2000 }).width("100px");

  // Hide the progress
  hideProgress();
}

function discountCodeRemoved(cart){
  if(cart.discount_code_removed) {
    showCartError("Sorry, your discount code was removed because your cart doesn't qualify anymore");

    // Remove discount row from cart
    $(".discount-total").fadeOut();
  }
}

function showCartError(message){

  // Add a new <p> and...
  $("h2.title").after("<p id=\"cart-error\">" + message + "</p>");

  // ...fade it out after 5 seconds
  setTimeout(function(){
    $("#cart-error").fadeOut("slow");
  }, 5000);
}

function updateCart(cart){

  // Update the items in cart text in the header
  $("#total-items-in-cart").html(cart.items_in_cart);

  // Update "there are 1 items" in your cart text
  $("#items-in-cart").html("You have <strong>" + cart.items_in_cart + "</strong> in your cart");

  // Update cart totals
  $("#sub-total").html(cart.sub_total);
  $("#postage").html(cart.postage);
  $("#total").html(cart.total);
}

function hideProgress(){
  $(".progress").slideUp();
}
