function addItemToCart(id, q) {
  var cart = getCartContents();
  if (cart.items[id]) {
    cart.items[id].quantity += parseInt(q);
  } else {
    cart.items_order.push(id);
    cart.items[id] = {product: id, quantity: parseInt(q)};
  }
  setCartContents(cart);
  window.location.href = '/cart/';
}

function getCartContents() {
  var cart_json = $.cookie('cart');

  return cart_json ? JSON.parse(cart_json) : {
    items: {},
    items_order: []
  };
}

function setCartContents(cart) {
  $.cookie('cart', JSON.stringify(cart), {path: '/', expires: 7});
}

function removeItemFromCart(id, el) {
  var cart = getCartContents();
  if (cart.items[id]) {
    delete cart.items[id];
  }
  setCartContents(cart);
  $(el).parents("tr").remove();
}

function updateCartItem(id, el, quantity) {
  var cart = getCartContents();
  if (quantity <= 0 && cart.items[id]) {
    delete cart.items[id];
  } else if (cart.items[id]) {
    cart.items[id].quantity = parseInt(quantity);
  }
  setCartContents(cart);
}

