ns('Carib.Order.Data');

/**
 * Recordset
 * 
 * @version $Id: recordset.js 385 2009-06-26 15:26:37Z  $
 */
Carib.Order.Data.Recordset = function(config) {
  this.data = [];
  
  this.addEvents({
    update: true,
    datachanged: true,
    add: true,
    remove: true
  });
  
  Carib.Order.Data.Recordset.superclass.constructor.call(this, config);
}

utils.extend(Carib.Order.Data.Recordset, utils.Observable, {
  add: function(record) {
    var num = this.data.push(record) - 1;
    record._setRecordset(this);

    this.onAdd(record, num);    
    this.onDataChanged();
  },
  
  remove: function(id) {
    var num = this.findRecord(id);
    if(num !== false)
      this.removeAt(num);
  },
  
  removeAt: function(num) {
    if(this.data[num] === undefined)
      return false;
    
    var record = this.data[num];
    this.data.splice(num, 1);
    record._unsetRecordset();

    this.onRemove(record, num);    
    this.onDataChanged();
    return true;
  },
  
  removeAll: function() {
    while(this.removeAt(0));
  },
  
  findRecord: function(id) {
    var num = false;
    this.each(function(i, record) {
      if(record.getId() == id) {
        num = i;
        return false;
      }
    });
    return num;
  },
  
  getAt: function(num) {
    return this.data[num];
  },
  
  getCount: function() {
    return this.data.length;
  },
  
  each: function(func, scope) {
    $.each(this.data, function(i, record) {
      return func.call(scope ? scope : window, i, record);
    });
  },
  
  _commitRecord: function(record) {
    this.onUpdate(record, this.findRecord(record.getId()));
    this.onDataChanged();
  },
  
  commitChanges: function() {
    var changed = false;
    this.each(function(i, record) {
      if(record.isDirty()) {
        changed = true;
        record.commit(true);
        this.onUpdate(record, i);
      }
    });
    if(changed)
      this.onDataChanged();
  },
  
  getClone: function() {
    var recordset = new Carib.Order.Data.Recordset();
    this.cloneTo(recordset);
    return recordset;
  },
  
  cloneTo: function(recordset) {
    this.each(function(num, record) {
      var new_record = new record.constructor();
      new_record.importValues(record.data);
      new_record.setId(record.getId());
      recordset.add(new_record);
    });
  },
  
  onDataChanged: function() {
    this.fireEvent('datachanged', [this]);
  },
  
  onAdd: function(record, num) {
    this.fireEvent('add', [this, record, num]);
  },
  
  onUpdate: function(record, num) {
    this.fireEvent('update', [this, record, num]);
  },
  
  onRemove: function(record, num) {
    this.fireEvent('remove', [this, record, num]);
  }
  
});
