/* Shirts Taste Good's Javascript Utilities, dependent on jQuery */
/* They are pretty handy, feel free to use them yourself */
var utilities = {
  
  sandbox: $(document), 
  
  attachCommonHandlers: function(){
    this.attachAjaxFormHandlers();
    this.attachJsLinkHandlers();
    this.preventDoubleClick();
    this.preventDoubleSubmit();  
  },
  
  /* request header on xhr should accept text/javascript as response */
  /* From here: http://railscasts.com/episodes/136-jquery */
  setAjaxRequestHeader: function(){
    jQuery.ajaxSetup({ 
      'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
    });
  },

  /* Serialize and post forms with ajax */
  /* To make a form an ajax form, add the class 'ajaxForm' */
  attachAjaxFormHandlers: function(){
    this.sandbox.find('.ajaxForm').submit(function(){
      $.post(this.action, $(this).serialize(), null, "script");
      return false;
    });
  },
  
  
  /* Don't let users double click links */
  preventDoubleClick: function(){
    this.sandbox.find('a.single_click').click(function(){
      $(this).replaceWith($(this).clone().removeAttr('href'));
    });
  },
  
  /* Don't let users double submit forms, unless it is an ajax form (class='ajaxForm') */
  preventDoubleSubmit: function(){
    this.sandbox.find('form').submit(function(){
      if(this.className != 'ajaxForm'){
        $(this).find('input:last').attr("disabled", "disabled");
      }
    });
  },
  
  /* Anything marked as a jsLink should not be followed */
  attachJsLinkHandlers: function(){
    this.sandbox.find('.jsLink').click(function(){
      return false;
    }); 
  }
}
