/**
 * Klasa do generowania tabelek
 * @author Aleksander Smolowik <asmolowik@ispik.pl>
 * @version 1.0.0
 * @example
 *  var table = new MAATTable('identyfikator');
 *  table.prepare(['aaa', 'bbb', 'ccc']);
 *  table.setData([['aaa', 'aaa', 'aaa'], ['bbb','bbb','bbb']]);
 *  table.generate();
 *  table.addRow(['xxx', 'xxx', '<div id="aa" onclick="alert(this.up(1).remove());">usun</div>']);
 */
var MAATTable = Class.create({
  _data: [], // model...
  _ident: null, // identyfikator tabelki
  caption: null, // opis tabelki
  _colls: [], // definicja kolumn
  _generate: true, // flaga okreslajaca czy mozna tabelke generowac (jak nie ma bledow)
  _debug: true, // okresla ze wlaczony jest tryb _debug'u
  _table_prefix: 'table_',
  _footer: [],
  _counter: 1,
  /**
   * Konstruktor. Parametrem jest id div'a do ktorego tabelka ma byc wstawiona
   */
  initialize: function(ident){
    this._footer = [];
    if (ident instanceof String && ident.length <= 0) {
      if (this._debug) alert('Musisz podać identyfikator tabelki!');
      this._generate = false;
    }
    if ($(ident) == null) {
      if (this._debug) alert('Element w który ma być wstawiona tabelka nie istnieje!');
      this._generate = false;
    }
    this._ident = ident;
  },
  /**
   * Metoda zwraca identyfikator tabelki
   */
  getTableId: function () {
    return this._table_prefix + this._ident;
  },
  addFooter: function (data) {
    this._footer.push(data);
  },
  /**
   * Metoda sluzy do przygotowania kolumn naglowka
   */
  prepare: function (colls) {
    //alert(colls);
    if (colls instanceof Array && colls.length <= 0) {
      if (this._debug) alert('Błędna definicja tabeli: ' + this._ident + '!');
      this._generate = false;
    } else {
      this._colls = colls;
    }
  },
  /**
   * Metoda sluzy do dodania kolekcji wierszy
   */
  setData: function (data) {
    if (data instanceof Array) {
      this._data = [];
      for (var i = 0; i < data.length; i++) {
        this._data[i] =  {'id' : i, 'row' : data[i]};
      }
    } else {
      if (this._debug) alert('Błędny format danych!');
    }
  },
  /**
   * Metoda sluzy do budowania wiersza
   * @private
   */
  _buildRow: function (row, _tr) {
    if (this._counter == 1) {
      tr.addClassName('fir');
      this._counter = 0;
    } else {
      tr.addClassName('sec');
      this._counter = 1;
    }
    for (var i = 0; i < row.row.length; i++) {
      if (row.row[i] instanceof Array) {
        var _td = new Element('td', {id : this.getTableId() + '_tbody_tr_td_' + row.id + '_' + i});
        for (var z = 0; z < row.row[i].length; z++) {
          _td.insert(row.row[i][z]);
        }
        _tr.insert(_td);
      } else {
        _tr.insert(new Element('td', {id : this.getTableId() + '_tbody_tr_td_' + row.id + '_' + i}).insert(row.row[i]));
      }
    }
    return _tr;
  },
  /**
   * Metoda sluzy do dodawania nowego wiersza
   * @param array tablica zawierajaca tyle elementow ile jest w naglowku tabeli
   * @return string zwracany jest identyfikator nowego wiersza
   */
  addRow: function (row) {
    if (row.length !== this._colls.length) {
      if (this._debug) alert('Podana liczba kolumn się nie zgadza!');
    } else {
      u_row_id = this._data.length + 1;
      this._data[u_row_id] =  {'id' : u_row_id, 'row' : row};
      tr = new Element('tr', {'id' : this.getTableId() + '_tbody_tr_' + this._data[u_row_id].id});
      tr = this._buildRow(this._data[u_row_id], tr);
      $(this.getTableId() + '_tbody').insert(tr);
      return u_row_id;
    }
    return null;
  },
  /**
   */
  clear: function () {
      $(this.getTableId() + '_tbody').update('');
  },
  /**
   * Metoda aktualizuje wiersz
   * @param string id identyfikator wiersza ktory ma byc aktualizowany
   * @param array row tablica zawierajaca tyle elementow ile jest w naglowku tabeli
   */
  updateRow: function (id, row) {
    if ($(id) == null) {
      if (this._debug) alert('Wiersz o identyfikatorze \'' + id + '\' nie istnieje!');
    } else if (row.length !== this._colls.length) {
      if (this._debug) alert('Podana liczba kolumn się nie zgadza!');
    } else {
      tr = $(id).update();
      var re = /^.*_([0-9]+)$/;
      var u_row_id = re.exec(id);
      u_row_id = u_row_id[1];
      this._data[u_row_id] =  {'id' : u_row_id, 'row' : row};
      this._buildRow(this._data[u_row_id], tr);
    }
    return null;
  },

  /**
   * Metoda generuje tabelke
   */
  generate: function () {
    if (this._generate) {
      _table = new Element('table', {'id' : this.getTableId(), 'class' : 'table'});
      _table.update(this._generateHeader());
      //_table.update(this._generateFooter());
      _tbody = new Element('tbody', {'id' : this.getTableId()+'_tbody'});
      _table.insert(_tbody);
      //if (this._footer.size() != null) {
        var footer = new Element('td', {'colspan' : this._colls.length});
        //alert(this._footer.size());
        for(var i = 0; i < this._footer.size(); i++) {
            footer.insert(this._footer[i]);
        }
        _table.insert(new Element('tfoot', {}).update(new Element('tr', {}).update(footer)));
      //}
      $(this._ident).update(_table);
      if (this._data.length > 0) {
        for (var i = 0; i < this._data.length; i++) {
          tr = new Element('tr', {'id' : this.getTableId() + '_tbody_tr_' + this._data[i].id});
          tr = this._buildRow(this._data[i], tr);
          $(this.getTableId() + '_tbody').insert(tr);
        }
      }
      _hidden = new Element('input', {'type' : 'hidden', 'id': this.getTableId() + '_hidden', 'name': this.getTableId() + '_hidden'});
      $(this._ident).insert(_hidden);
    } else {
      if (this._debug) alert('Błędna definicja tabelki! Tabelka nie może zostać prawidłowo załadowana.');
    }
  },
  /**
   * Metoda generuje naglowki kolumn
   * @private
   */
  _generateHeader: function () {
    thead = new Element('thead', {
      id : this.getTableId() + '_thead'
    });
    thtr = new Element('tr', {
      id : this.getTableId() + '_thead_tr'
    });
    for (var i = 0; i < this._colls.length; i++) {
      thtr.insert(new Element('th', {}).update(this._colls[i]));
    }
    thead.insert(thtr);
    return thead;
  },
  /**
   * Metoda generuje stopkę tabeli
   * @private
   */
  _generateFooter: function () {
    tfoot = new Element('tfoot', {
      id : this.getTableId() + '_tfoot'
    });
    thtr = new Element('tr', {
      id : this.getTableId() + '_tfoot_tr'
    });
    for (var i = 0; i < this._footer.size(); i++) {
      thtr.insert(new Element('td', {}).insert(this._footer[i]));
    }
    tfoot.insert(thtr);
    return tfoot;
  }
});
