ns('Carib.Order.Data');

/**
 * Loader
 * 
 * @version $Id: loader.js 384 2009-06-25 14:17:42Z  $
 */
Carib.Order.Data.Loader = function(config) {
  this.request = null;
  this.recordset = null;
  this.params = null;
  
  // configurable {
  this.url = ''; 
  this.reader = null; // required
  // }
  
  this.addEvents({
    load: true,
    beforeload: true
  });
  
  Carib.Order.Data.Loader.superclass.constructor.call(this, config);
}

utils.extend(Carib.Order.Data.Loader, utils.Observable, {
  /**
   * Load.
   * options it's object like this:
   * {
   *    url: if url was not passed then will be used configured url
   *    params: an object contains properties to pass as HTTP parameters to a remote data source,
   *    recordset: recordset to save loaded data
   * }
   * @param {Object} options
   */
  load: function(options) {
    this.abort();
    
    this.params = options.params ? options.params : {};
    this.recordset = options.recordset ? options.recordset : new Carib.Order.Data.Recordset();
    var url = options.url ? options.url : this.url;
    if(this.onBeforeLoad(options))
      this.request = $.post(url, this.params, this._requestComplete.createDelegate(this));
  },
  
  abort: function() {
    if(this.request) {
      this.request.abort();
      this.request = null;
    }
  },
  
  _readData: function(data) {
    this.recordset.removeAll();
    this.reader.read(data, this.recordset);
  },
  
  _requestComplete: function(data) {
    this._readData(data);
    this.onLoad();
  },
  
  onLoad: function() {
    this.fireEvent('load', [this, this.recordset]);
  },
  
  onBeforeLoad: function(options) {
    return this.fireEvent('beforeload', [this, options]);
  }  
});
