$(function() {

  $('.jtrb-button-disabled a').live('click', function(e) {
    return false;
  });

  $('.jtrb-button-default a,.jtrb-get-free a').live('click', function(e) {
    e.preventDefault();
    var product_id = $(this).attr('id').replace('product-','');
    var href       = $(this).attr('href');
    $.util.post(
      '/service/cart/add_partial_to_cart',
      { product_id: product_id },
      function(data) {
        top.location.href=href;
      }
    );
  });

  $("select.attr-selector").change(function(e) {
    e.preventDefault();
    resolveProductId(this);  
  });  
 
});


function resolveProductId(o) {
  var row = $(o).parents('tr');
  if ($(o).val() == '' && $(o).children('option').length > 1) {
      row.find('.price').html('');
      row.find('.jtrb-button-default').removeClass('jtrb-button-default').addClass('jtrb-button-disabled').find('a').attr('href', '#');
      return false;    
  }
  
  row.find('.price').html('<img src="/static/images/jtrb_preload.gif"/>');
  $.util.post(
    '/service/product/resolve_product_id',
    row.find(':input').serializeArray(),
    function(product) {
      row.find('.price').html('<span class="strong black">$'+product.price+'</span>');
      
      var book_isbn_param = "";
      if(book_isbn){
        book_isbn_param = '&book_isbn=' + book_isbn
      }
      
      row.find('.add-to-cart-button').removeClass('jtrb-button-disabled').addClass('jtrb-button-default').find('a').attr('href', '/cart/questions?product_id=' + product.product_id + book_isbn_param)
      .attr('id', 'product-'+product.product_id);
      row.find('.short_description').html(product.short_description);
    }
  );  
}

