var Modal = Class.create();

Object.extend(Modal, {
  instance: function() {
    return $('modal');
  },
  
  close: function() {
    if (this.instance()) this.instance().remove();
  }
});

Modal.addMethods({
  initialize: function(class_name, options) {
    this.class_name = class_name;
    this.options = options;
    
    document.observe('click', function(event) {
      var element = event.element();
      if (!this.matches(element)) return;
      event.stop();
      Modal.close();
      this.clicked(event);
      new Ajax.Request(element.href, Object.extend({
        method: 'get',
        onSuccess: this.success.bind(this)
      }, this.options));
    }.bindAsEventListener(this));
  },
  
  clicked: function(event) {
  },
  
  matches: function(element) {
    return element.hasClassName(this.class_name);
  },
  
  success: function(res) {
    this.container = $(document.createElement('div')).update(res.responseText).down().hide();
    this.container.setStyle({zIndex: 101});
    document.body.appendChild(this.container);
    this.container.appear({duration: .25});
    $('modal-close').observe('click', this.close.bind(this));
    if (this.options.after_load) this.options.after_load(this);
  },
  
  close: function() {
    this.container.fade({
      duration: .25,
      afterFinish: function() {
        this.container.remove();
      }.bind(this)
    });
  }
});
