
var AjaxClient = Class.create();
Object.extend(Object.extend(AjaxClient.prototype, Ajax.Request.prototype), {
  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, object) {
      this.onComplete();
      onComplete(transport, object);
    }).bind(this);
    // this.options.onComplete = this.onComplete.bind(this);
  },

  onComplete: function() {
    var response = this.transport.responseText;
    try {
      var instructions = $A(eval(response));
    } catch (e) { 
      return; 
    }

    instructions.each(this.dispatchInstruction.bind(this));
  },

  dispatchInstruction: function(instruction) {
    var action = instruction.action;
    this['handle'+action](instruction.context);
  },

  handleEval: function(context) {
    eval(context);
  },

  handleUpdate: function(context) {
    if (context.insertion) {
      insertion = eval(context.insertion);
      new insertion(context.receiver, context.text);
    } else {
      Element.update(context.receiver, context.text);
    }
  },
  
  handleReplace: function(context) 
  {
      $(context.receiver).replace(context.text);
  }
  

});

var handlers = {
    onCreate: function() {
        Element.show('loading');
    },
    onComplete: function() {
        if(Ajax.activeRequestCount == 0){
	    Element.hide('loading');
	}
    }
}

Ajax.Responders.register(handlers);

function reportError() {
  alert("Server failure, please try again");
}

function sendAjaxRequest(href)
{
    var pairs = href.split('\?');
    var r = new AjaxClient(pairs[0],
                         {method: "post",
			  onFailure: reportError,
			  parameters: pairs[1],
			  evalScripts: true});
}

function ajaxFormSubmit(e) 
{
    Event.stop(e);
    form = Event.element(e);
    ajaxFormSubmit2(form);
}

function ajaxFormSubmit2(form) 
{
    var r = new AjaxClient(form.attributes['action'].value,
                         {method: "post",
                          parameters: Form.serialize(form),
                          onFailure: reportError,
                          evalScripts: true});
}
