var NEF = window.NEF || {};

/*
 * The AjaxEvent class allows you to create DAOs for handling
 * Ajax requests. Upon request success, it fires a custom event
 * that handles subscribed functions.
 *
 * @namespace NEF
 * @class AjaxEvent
 * @constructor
 */
NEF.AjaxEvent = function() {
  return this;
}

NEF.AjaxEvent.prototype = {

  /*
   * Subscribes a function or method to the custom event.
   *
   * @method subscribe
   * @param {Function}  fn          The function to execute
   * @param {Object}    oScope      An object to be passed as scope for the function
   */
  subscribe: function(fn, oScope) {
    if (!this.oEvent) {
      this.oEvent = new YAHOO.util.CustomEvent("ajaxevent", this, false, YAHOO.util.CustomEvent.FLAT);
    }
    if (oScope) {
      this.oEvent.subscribe(fn, oScope, true);
    } else {
      this.oEvent.subscribe(fn);
    }
  },

  /*
   * Performs an asynchronous request using the YUI Connection manager
   * and fires our custom event upon success.
   *
   * @method connect
   * @param {String}    sUri        Fully qualified path of resource
   */
  connect: function(sUri) {
    if (!sUri && !this.sUri) {
      return false;
    } else {
      this.sUri = (!sUri) ? this.sUri : sUri;
      this.dt = new Date().valueOf();
      this.sUri = (this.sUri.indexOf("?") === -1) ? this.sUri + "?yaetime=" + this.dt : ((this.sUri.indexOf("yaetime") === -1) ? this.sUri + "&yaetime=" + this.dt : this.sUri.replace(/yaetime=[0-9]+/i, "yaetime=" + this.dt));
      YAHOO.util.Connect.asyncRequest('GET', this.sUri, {
        success: function (o) {
          var oJSON = eval("(" + o.responseText + ")");
          this.oEvent.fire((typeof oJSON === "object") ? oJSON : null);
        },
        scope: this
      });
    }
  }
}