var AjaxHandlers = {};

/*
This behavior is intended to provide default functionality for any element that contains
data-method=post|delete and data-remote=true attributes. It will submit AJAX requests 
that accept json data back. 

To apply the default behavior to anchor tags with the class "foo" you would do something similar to:
   Event.addBehavior({
     'a.foo[data-method][data-remote=true]': AjaxHandlers.RemoteOnClick
   });

Here's an example of subclassing and overriding what happens when the request is handled successfully:
  var MySpecialClick = Behavior.create(AjaxHandlers.RemoteOnClick, {
    handleSuccess: function(data){
      // do unique thing here
    }
  });

If your anchor tag has a data-confirm attribute that will be used to prompt the user with 
a confirm dialog before executing the click.
*/
AjaxHandlers.RemoteOnClick = Behavior.create({
  initialize: function(){
    this.link = this.element;
    this.link.observe("click", this.handleClick.bind(this));
  },
  
  parameters: function(){
    return Application.authenticityTokenParameter();
  },
  
  processClick: function(){
    return true;
  },

  handleClick: function(event){
    event.stop();
    if( !this.processClick() )
      return;
    var msg = this.link.getAttribute("data-confirm");
    if(!msg || confirm(msg)){
      new Ajax.Request(this.link.href, {
        parameters: this.parameters(),
        method: this.link.getAttribute("data-method"),
        requestHeaders: { 'Accept': 'application/json' },
        onCreate: function(){
          this.spinner = Application.addSpinnerTo(this.link, { position: "center" });
        }.bind(this),
        onComplete: function(){
          this.spinner.remove();
        }.bind(this),
        onSuccess: this.handleSuccess.bindAsJSONResponse(this)
      });
    }
  },

  handleSuccess: function(data){
    if(data.redirectTo){
      window.location = data.redirectTo;
    }
  }
});
