var ContextAction = Class.create();
ContextAction.prototype = {
  initialize: function(outerBox, innerBox, options){
    this.options = Object.extend ({
      beforeRequestHandler:null,
      beforeOpenHandler:null,
      afterOpenHandler:null
    }, options || {});
    this.outerBox = $(outerBox);
    this.innerBox = $(innerBox);
    this.visible = false;
    this.onComplete = this._onComplete.bindAsEventListener(this);
    this.onFailure = this._onFailure.bind(this);
    this.onException = this._onException.bind(this);
    this.header = '';
  },

  open: function(url, header)
  {
    if(this.visible)
    {
      if(confirm("Warning. You have not finished with prvious action yet. Continie?"))
      {
        this.close(this._request.bind(this, url));
        return;
      }
      else
      {
        return;
      }
    }
    this._request(url);
  },


  close: function(afterClose)
  {
    Effect.BlindUp(this.outerBox, {duration:0.5, afterFinish:(afterClose || this._clearBox.bind(this))});
  },

  _request: function(url)
  {
    if(this.options.beforeRequestHandler)
      this.options.beforeRequestHandler();
    new Ajax.Request(url, {onComplete:this.onComplete, evalScripts:true, onFailure:this.onFailure, onException:this.onException, method:'get'});
  },

  _onComplete: function(event)
  {
    Element.update(this.innerBox, event.responseText);
    if(this.options.beforeOpenHandler)
      this.options.beforeOpenHandler();
    this.animate();
  },

  _onFailure:function()
  {
    alert("failure on server");
//    Element.show(this.outerBox);
//    this.innerBox.update();
  },

  animate:function()
  {
//    Element.show(this.outerBox);
    setTimeout((function() {Effect.BlindDown(this.outerBox, {duration:0.5, afterFinish:this.options.afterOpenHandler});
    this.visible = true;}).bind(this), 500); //fuck this fuck hack fuck
  },

  _onException: function(ajax, exception)
  {
    throw exception;
  },
  
  _clearBox: function()
  {
    Element.update(this.innerBox, "");
    this.visible = false;
  }
}
