// Generic namespace for helper functions used across the entire site
Rainbow = {
  ajaxify_forms: function() {
    // requires jQuery.form plugin
    $("form.rjs").ajaxForm({
      dataType: "script",
      beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");},
      resetForm: true
    });
  },

  ajaxify_links: function() {
    $("a.rjs").click( function() {
      $.ajax({
        url: this.href,
        dataType: "script",
        beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");}
      });
      return false;
    });
  },

  init_facebox_links: function() {
    $('a[rel*=facebox]').facebox()
  }
}

// methods for dealing with the credit card payment form
PaymentForm = {

  // we want to hide/show the credit card form when the user changes
  // their payment method
  register_pay_type_clicks: function() {
    $('div#checkout input[type=radio]').click(PaymentForm.toggle_credit_card_form);
  },

  // reverse the current state of the credit card form. 
  //
  // If the form is being changed to show, the focus is changed to
  // the first element of the form.
  //
  toggle_credit_card_form: function() {
    payment_element = $('cart_cctype_input');

    if(payment_element == null)
      return;


    var pay_type = $('div#checkout input[type=radio]:checked').val();

    if (pay_type == 'account') {
      $('fieldset#credit_card_details').hide('fast');
    } else {
      $('fieldset#credit_card_details').show('fast');
      $('input#cart_ccnum').focus();
    }
  }

}

// trigger events when the DOM is finished loading
jQuery(document).ready(function($) {
    Rainbow.ajaxify_forms();
    Rainbow.ajaxify_links();
    Rainbow.init_facebox_links();
    PaymentForm.register_pay_type_clicks();
    PaymentForm.toggle_credit_card_form();
})

// trigger events when a Facebox loads
$(document).bind('reveal.facebox', function() {
    Rainbow.ajaxify_forms();
    Rainbow.ajaxify_links();
})
