$(function() {
  function getData() {
    var cart = getCartContents();
    var quantities = [];
    var keys = [];
    for (var id in cart.items) {
      keys.push(id);
      quantities.push(cart.items[id].quantity);
    }
    return {keys: keys, quantities: quantities};
  }
  var data = getData();
  var cart_url = '/cart/';
  var url = '/cart/?quantities=' + encodeURIComponent(data.quantities.join(','));
  if (typeof country !== 'undefined') url += '&country=' + encodeURIComponent(country);
  if (typeof SHIPPING !== 'undefined') url += '&shipping=' + encodeURIComponent(SHIPPING);
  $('input.checkout').click(function() {
    var is_valid = true;
    $('table.cart tbody tr').each(function() {
      var tds = $('td', this);
      if (parseInt($('input', tds.eq(1)).val()) > parseInt(tds.eq(4).text().match(/(\d+)[\d+]*/)[1])) {
        is_valid = false;
      }
    });
    if (!is_valid) {
      alert("There are insufficient items in stock for one or more items in your cart.  Please adjust and try again.");
      return false;
    }
    var data = getData();
    //setUrchinInputCode(pageTracker);
    var type = $(this).hasClass('google') ? 'gcheckout' : 'paypal';
    var url = cart_url + type + '/?action=checkout&quantities=' + encodeURIComponent(data.quantities.join(',')) + '&shipping=' + encodeURIComponent($('select[name=shipping] option:selected').text().split(/:/)[0]);
    if (type == 'gcheckout') {
      url += '&analyticsdata=' + encodeURIComponent($('#analyticsdata').val());
    }
    $.ajax({
      type: 'POST',
      url: url,
      data: JSON.stringify(data.keys),
      dataType: 'xml',
      processData: false,
      contentType: 'text/json',
      success: function(data, textStatus) {
        location.href = $('redirect-url', data).text();
      }
    });
  });
  $('input.pay').click(function() {
    var is_valid = true;
    $('table.cart tbody tr').each(function() {
      var tds = $('td', this);
      if (parseInt($('input', tds.eq(1)).val()) > parseInt(tds.eq(4).text().match(/(\d+)[\d+]*/)[1])) {
        is_valid = false;
      }
    });
    if (!is_valid) {
      alert("There are insufficient items in stock for one or more items in your cart.  Please adjust and try again.");
      return false;
    }
    var data = getData();
    var type = $(this).hasClass('google') ? 'google' : 'paypal';
    $.ajax({
      type: 'POST',
      url: '/cart/' + type + '/confirm/?action=confirm&quantities=' + encodeURIComponent(data.quantities.join(',')) + '&token=' + encodeURIComponent(TOKEN) + '&PayerID=' + encodeURIComponent(PAYERID) + '&country=' + country + '&shipping=' + encodeURIComponent($('select[name=shipping] option:selected').text().split(/:/)[0]),
      data: JSON.stringify(data.keys),
      processData: false,
      contentType: 'text/json',
      success: function(data) {
        $('#content').empty().html(data);
      }
    });
  });
  var updateTotals = function() {
    var total = 0.0;
    $('table.cart tbody tr').each(function() {
      var tds = $('td', this);
      var line_total = parseInt($('input', tds.eq(1)).val()) * tds.eq(5).data('price');
      tds.eq(6).data('price', line_total).trigger('pricesChanged');
      total += line_total;
    });
    $('#cart_total').data('price', total).trigger('pricesChanged');
    var grand_total = total + parseFloat($('select[name=shipping]').val());
    $('#cart_grand_total').data('price', grand_total).trigger('pricesChanged');
  };
  $('input[name=quantity]').blur(updateTotals).blur(function() {
    var id = $(this).parents('tr').attr('id').match(/cartitem_(.+)/)[1];
    updateCartItem(id, this, $(this).val());
  });
  $('table.cart tbody tr a.remove').click(function() {
    var id = $(this).parents('tr').attr('id').match(/cartitem_(.+)/)[1];
    removeItemFromCart(id, this);
    updateTotals();
    return false;
  });
  $('select[name=shipping]').change(updateTotals);
});

