jQuery(function($) {
  
  function load_shopping_cart() {
    $('div#shoppingcart.sitetoolbox').load('/cart')
  }
  load_shopping_cart();
  var ajax_add_to_order_options = {
    success: function() {
      facebox_alert("Thank You.<br/> This Product Has Been Added to Your Cart.");
      load_shopping_cart();
    },
    processData: false,
    error: function(xml_http_request,text_status,error_thrown) {
      if (xml_http_request.status == 403) {
        facebox_alert("Your account is not authorized to place orders.");
      } else if (xml_http_request.status == 401) {
        facebox_alert("Please login to your account to begin shopping.");
      } else {
        // unlikely that we'll get here
        facebox_alert("An error has prevented your action from completing. Please Call to Place Your Order.");
      }
    }
    
  };
  $('form.inline_cart').ajaxForm(ajax_add_to_order_options);
  
  $('span.cart_remove').click(function() {
    item_id = this.id.replace(/cart_remove_/, '');
    token = $(this).parents('form').find('input[name="authenticity_token"]');

    form = $('<form action="/cart" method="post"><input type="hidden" name="_method" value="put"></form>');
    form.append(token);
    input_name_prefix = 'cart[cart_items_attributes][0]'
    form.append('<input type="hidden" name="' + input_name_prefix + '[id]" value="' + item_id + '">');
    form.append('<input type="hidden" name="' + input_name_prefix + '[quantity]" value="0">');
    
    form.appendTo($('body'));  // submit doesn't do anything unless the form is actually on the page
    form.submit();
  }).css('cursor', 'pointer');
  
  function show_checkout_kind(kind) {
    k_id  = '#' + kind + '_info'
    kinds = $('form.order :radio[name=kind]').map(function() { return this.value; });
    // only care about the divs that match up to kinds
    divs  = $('form.order div').filter(function() { return kinds.index(this.id.replace(/_info/, '')) != -1; })
    
    // the divs for other kinds
    divs.not(k_id).hide().children('input').enable(false);
    
    // the div for this kind
    divs.filter(k_id).show().children('input').enable(true);
  }
  $('form.order :radio[name=kind]').click(function() { show_checkout_kind(this.value); });
  if (checked_order_kind = $('form.order :radio[name=kind]:checked')[0]) {
    show_checkout_kind(checked_order_kind.value);
  }
  
  
  // visual niceties
  $('table.related_products tr td.normal_related_tr:first-child').removeClass('normal_related_tr').addClass('first_related_tr');
  $('table.related_products tr td.normal_related_tr').each(function() {
    var td = $(this);
    if (! $.trim(td.text()) ) {
      td.removeClass('normal_related_tr').addClass('first_related_tr');
    }
  });
  $('table.related_products tr:last-child').remove();

  // print links
  $('a.printlink').click(function(event) {
    event.preventDefault(); // prevent the anchor tag from sending the user off to the link  
     window.print(); 
  });
  
  // bookmark links
  // add a "rel" attrib if Opera 7+  
  if(window.opera) {  
      if ($("a.bookmarklink").attr("rel") != ""){ // don't overwrite the rel attrib if already set  
          $("a.bookmarklink").attr("rel","sidebar");  
      }  
  }  
  $("a.bookmarklink").click(function(event){  
      event.preventDefault(); // prevent the anchor tag from sending the user off to the link  
      var url = this.href;  
      var title = this.title;  

      if (window.sidebar) { // Mozilla Firefox Bookmark  
          window.sidebar.addPanel(title, url,"");  
      } else if( window.external ) { // IE Favorite  
          window.external.AddFavorite( url, title);  
      } else if(window.opera) { // Opera 7+  
          return false; // do nothing - the rel="sidebar" should do the trick  
      } else { // for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)  
           alert('Unfortunately, this browser does not support automatic bookmarking, please bookmark this page manually.');  
      }  
  });
  
  $('a.emaillink').facebox();
  
  $('form#emailForm').livequery(function() {
    $(this).ajaxForm(function(data) {
      facebox_alert(data);
    });
  });
  
  if ($('#aup_terms')[0]) {
    $('#aup_terms').load('/acceptable_use_policy #maincontentwrapper');
  }
  
  // forgotten password interface
  $('a.forgotlink').livequery(function() { $(this).facebox(); });
  
  $('form#forgotForm').livequery(function() {
    $(this).ajaxForm(function(data) {
      facebox_alert(data);
    });
  });

  // Handle hidden drop ship address.  First, hide it unless there's no
  // value chosen in the shipping_address_id dropdown.
  function set_visibility_of_drop_ship_address() {
    if ($('#order_shipping_address_id').val()=='') {
      $('div#drop_ship_address').show();
    } else {
      $('div#drop_ship_address').hide();
    }
  }
  set_visibility_of_drop_ship_address();
  // Now, when the user clicks the dropdown, show/hide the form.
  $('#order_shipping_address_id').change(set_visibility_of_drop_ship_address);

  // bulk order form dropdown
  $('input.bulk_order_product_id').autocomplete('/carts/auto_complete_for_backend_item_number', {'minChars':3, 'formatItem': function(row,i,max) { return row[0] + "<br /><i>" + row[1] + " &gt; " + row[2] + "</i>" }, 'formatResult': function(row,i,max) { return row[1]; }, 'formatMatch': function(row,i,max) { return row[0]; } });
  $('#SearchSite').autocomplete('/carts/auto_complete_for_backend_item_number', {'minChars':3, 'formatItem': function(row,i,max) { return row[0] + "<br /><i>" + row[1] + " &gt; " + row[2] + "</i>" }, 'formatResult': function(row,i,max) { return row[1]; }, 'formatMatch': function(row,i,max) { return row[0]; } , 'width': '200px' });
  $('input.quick_order_product_id').autocomplete('/carts/auto_complete_for_backend_item_number', {'minChars':3, 'formatItem': function(row,i,max) { return row[0] + "<br /><i>" + row[1] + " &gt; " + row[2] + "</i>" }, 'formatResult': function(row,i,max) { return row[1]; }, 'formatMatch': function(row,i,max) { return row[0]; }, 'width': '198px' });
  
  $("div.alternate_product_number").click(function(event) { 
    event.preventDefault();
    new_number = $(this).find("span.item_number").text();
    $(this).parents('tr').find('.ac_input').attr("value", new_number);
  });
});
