var highlight = false;

function checkCart() {
  if (! $('#remoteSite').length) return;

  $.getJSON($('#remoteSite').attr('href') + '/cart/CartInfo.html?callback=?', function(cart) {
    $('#items').empty();
    $('#uniqueId').text(cart.uniqueId);
    $('#subTotal').text(cart.subtotal);
    var count = 0;
    $.each(cart.items, function(i, item) {
      count = count + 1;
      iHtml = $('#itemTemplate .item').clone();

      $('span.plu',   iHtml).text(item.plu);
      $('span.name',  iHtml).text(item.name);
      $('span.qty',   iHtml).text(item.qty);
      $('span.price', iHtml).text(item.price);
      $('img.image',  iHtml).attr({
        alt: item.name,
        title: item.name,
        src: item.image
      });

      $('a.remove', iHtml)
        .attr('href', item.cartId)
        .click(function() {
          $.getJSON($('#remoteSite').attr('href') + '/cart/RemoveItem.html?cartId=' + $(this).attr('href') + "&callback=?");
          $(this).parent().parent().hide("blind", {}, 500, checkCart);
          return false;
        });

      var item = iHtml.appendTo('#items');
      if (highlight) {
        item.effect('highlight');
        highlight = false;
      }
    });

    if (count == 0) {
      $('#cartSummary .cartControls').hide();
      $('#cartSummary .emptyMessage').show();

    } else {
      $('#cartSummary .cartControls').show();
      $('#cartSummary .emptyMessage').hide();
    }
  });
}

$(document).ready(function() {
  checkCart();
  
  $('.addToCartLink').click(function() {
    $.getJSON($(this).attr('href') + "&callback=?", function(data) {
      if (data.result == 'yes') {
        highlight = true;
      }

      checkCart();
    });
    return false;
  });
  			
  $('.removeItem').click(function() {
    $.getJSON($('#remoteSite').attr('href') + '/cart/RemoveItem.html?cartId=' + $(this).attr('href') + "&callback=?");
    $(this).parent().parent().hide("blind", {}, 500, checkCart);
    return false;
  });
  
  $('#addToCartSubmit').removeAttr('onclick');
  $('#addToCartForm').submit(function() {
    $.getJSON($(this).attr('action') + '?callback=?', $(this).serializeArray(), function(data) {
      if (data.result == 'yes') {
        highlight = true;
      }

      checkCart();
    });
    return false;
  });
});
