/* Copyright Grzegorz Kes, ISPiK SA | http://www.ispik.pl | mail: gkes@ispik.pl
 * ---------------------------------------------------------------------------

 * The Dynamic Table
 *
 * Details and latest version at:
 * http://
 *
 * This script is distributed under the GNU Lesser General Public License.
 * Read the entire license text here: http://www.gnu.org/licenses/lgpl.html
 *
 */

// $Id: ExtTable.js,v 1.00 2008/07/07 09:51:33 gkes Exp $

/**
 * Model kolumn
 *
 * @author Grzegorz Kes, ISPiK SA <gkes@ispik.pl>
 */
var ExtColumnModel = Class.create({
  initialize: function(){},
  model: [],
  getModel:function(){
    return this.model;
  },
  setModel:function(model){
    this.model = model;
  },
  addRow:function() {

  }
});

/**
 * Model danych skojarzony z tabelka
 *
 * @author Grzegorz Kes, ISPiK SA <gkes@ispik.pl>
 */
var ExtTableModel = Class.create({
  initialize: function() {
      this.model = [];
  },
  getModel:function(){
    return this.model;
  },
  setModel:function(model){
    if(typeof(model) == "undefined") {
        this.model = [];
        return;
    }
    if(model == '') {
        this.model = [];
        return;
    }
    if(model instanceof Array)
      this.model = model;
    else {
        if(model.isJSON()) {
            this.model = model.evalJSON();
        }
    }
  },
  appendRow:function(model){
    this.model.push(new Hash(model));
  },
  insertRow:function(){

  }
});

/**
 * Dynamicznie generowana tabela.
 * Tabela moze posiadac naglowek tabeli
 *
 *
 * identyfikatory dla tbody = identyfikator tabeli + '_tb_' + indeks wiersza;
 * identyfikatory dla tr = identyfikator tabeli + '_tr_' + kolejny indeks dla tr
 *
 * @author Grzegorz Kes, ISPiK SA <gkes@ispik.pl>
 */
var ExtTable = Class.create({
  initialize: function(id, caption, mode){
    this.m_id = id;
    this.m_caption = caption;
    this.m_mode = mode;
    this.m_switcher = new Array('fir', 'sec');
  },
  m_columnModel:[],
  m_tableModel:[],
  m_switcher:[],
  prepareCaption: function(){
    this.caption = new Element('caption');
    this.caption.update(this.m_caption);
  },
  prepareHeader: function(){
    this.thead = new Element('thead');
    var tr = new Element('tr');
    for (var index = 0, len = this.m_columnModel.length; index < len; ++index) {
      var td = new Element('th');
      td.update((this.m_columnModel[index].evalJSON()).header);
      tr.insert(td);
    }
    this.thead.insert(tr);
  },
  afterPrepareContent:function() {

    if(typeof(this.m_tableModel) != "undefined") {

      for (var rowIdx = 0, rowLen = this.m_tableModel.length; rowIdx < rowLen; ++rowIdx) {
        var myArray = $A(this.m_tableModel[rowIdx]);
        for (var index = 0; index < myArray.length; ++index) {
          var idTd = this.m_id+'_'+rowIdx+'_'+index;
          var iIdTd = 'i'+this.m_id+'_'+rowIdx+'_'+index;
          if(myArray[index] instanceof Array) {
            var extArray = $A(myArray[index]);
          } else {
            var item1 = myArray[index].colIdx;
            var item2 = myArray[index].id;
            var value = null;
            var link = false;
            var onclick = null;
            if(myArray[index].value != null) {
              if(myArray[index].value instanceof Object) {

                  var xx = $A(myArray[index].value);
                  alert(xx);

                  var tbodyIdentTpl = this.m_id+'_tb_'+rowIdx;
                  //alert(myArray[index].value);
                  x = (this.m_columnModel[index].evalJSON()).component+'_'+item1+' (\''+idTd+'\', \''+iIdTd+'\', \''+myArray[index].value.nazwa+'\', {\'url\':\''+myArray[index].value.www+myArray[index].value.nazwa_tmp+'\', \'class\':\''+this.m_id+'_'+index+'\', \'onclick\': \''+onclick+'\', \'onblur\': \''+this.m_id+'.updateModel(\\\''+iIdTd+'\\\');\'});';
                  eval(x);
                  link = true;
              } else {
                  var uv = myArray[index].value.substr(myArray[index].value.indexOf('|')+1, myArray[index].value.length);
                  if(uv.length == 0)
                        uv = '&nbsp';
                  value = uv.unescapeHTML();
              }
            }

            if(!link) {
              var x = null;
              //alert('Sumowanie');
              if((this.m_columnModel[index].evalJSON()).sum) {
                x = (this.m_columnModel[index].evalJSON()).component+'_'+item1+' (\''+idTd+'\', \''+idTd+'\', \''+value+'\', {\'class\':\''+this.m_id+'_'+index+'\',\'onblur\': \' var tab = 0; $$(\\\'input.'+this.m_id+'_'+index+'\\\').each( function(item) { if(!isNaN(parseFloat(item.value))) tab += parseFloat(item.value); });  var display = \\\'suma: \\\'+tab ;$(\\\''+this.m_id+'_sum_'+index+'_div\\\').update(display);\'});';
                eval(x);
              } else {
                var tbodyIdentTpl = this.m_id+'_tb_'+rowIdx;
                var colClass = (this.m_columnModel[index].evalJSON()).colClass;
                //alert(colClass);
                var callFun = (this.m_columnModel[index].evalJSON()).callFunction;
                var onclick;
                if(typeof(callFun) != "undefined") {
                    onclick = this.m_id+'.'+callFun+'(\\\''+tbodyIdentTpl+'\\\');';
                }
                if(typeof(onclick) != "undefined")
                  x = (this.m_columnModel[index].evalJSON()).component+'_'+item1+' (\''+idTd+'\', \''+iIdTd+'\', \''+value+'\', {\'class\':\''+this.m_id+'_'+index+'\', \'onclick\': \''+onclick+'\', \'onblur\': \''+this.m_id+'.updateModel(\\\''+iIdTd+'\\\');\'});';
                else
                  x = (this.m_columnModel[index].evalJSON()).component+'_'+item1+' (\''+idTd+'\', \''+iIdTd+'\', \''+value+'\', {\'class\':\''+this.m_id+'_'+index+'\', \'onblur\': \''+this.m_id+'.updateModel(\\\''+iIdTd+'\\\');\'});';
                //alert(x);
                eval(x);
              }
            }
          }
        }
      }

      for (var i = 0, len = this.m_columnModel.length; i < len; ++i) {
        var sum = (this.m_columnModel[i].evalJSON()).sum;
        if(sum) {
          var y = 'Infofield_'+i+' (\''+this.m_id+'_sum_'+i+'\', \''+this.m_id+'_sum_'+i+'_div\', \'suma: '+i+'\', {\'class\' : \'tableInfoField\'})';
          eval(y);
        }
      }
    }

    var action = null;

    if(this.m_mode == '999') return;

    if(this.m_mode == '1') {
      action = 'Button_'+this.m_id+'_Add (\''+this.m_id+'action\', \''+this.m_id+'_add\', \'Dodaj\', {\'image\':\'web/images/table_row_insert.gif\', \'onclick\': \''+this.m_id+'.addRow();\'});';
    } else if(this.m_mode == '100') {
      action = 'Button_'+this.m_id+'_Add (\''+this.m_id+'action\', \''+this.m_id+'_add\', \'Wstaw\', {\'image\':\'web/images/table_row_insert.gif\', \'onclick\': \'window.open(\\\''+this.getMainUrl()+'\\\', \\\'\\\', \\\'toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=0,resizable=0,height=100,width=350,top=400,left=400\\\');\'})';
    } else if(this.m_mode == '101') {
      action = 'Button_'+this.m_id+'_Add (\''+this.m_id+'action\', \''+this.m_id+'_add\', \'Wstaw\', {\'image\':\'web/images/table_row_insert.gif\', \'onclick\': \'Modalbox.show(\\\''+this.getMainUrl()+'&table='+this.m_id+'\\\', {title: \\\'Pobieranie danych\\\'});\' })';
    } else if(this.m_mode == '103') {
      action = 'Button_'+this.m_id+'_Add (\''+this.m_id+'action\', \''+this.m_id+'_add\', \'Wstaw\', {\'image\':\'web/images/table_row_insert.gif\', \'onclick\': \'Modalbox.show(\\\''+this.getMainUrl()+'&table='+this.m_id+'\\\', {title: \\\'Zgłaszanie rezerwacji\\\'});\' })';
    } else if(this.m_mode == '104') {
      action = 'Button_'+this.m_id+'_Add (\''+this.m_id+'action\', \''+this.m_id+'_add\', \'Wstaw\', {\'image\':\'web/images/table_row_insert.gif\', \'onclick\': \'Modalbox.show(\\\''+this.getMainUrl()+'&table='+this.m_id+'\\\', {title: \\\'Zgłaszanie rezerwacji\\\'});\' });';
      action += 'Button_'+this.m_id+'_Reserve (\''+this.m_id+'action\', \''+this.m_id+'_reserve\', \'Zarezerwuj\', {\'image\':\'web/images/reservation_add.gif\', \'onclick\': \''+this.m_id+'.reservation2();\' });';
      action += 'Button_'+this.m_id+'_Unreserve (\''+this.m_id+'action\', \''+this.m_id+'_unreserve\', \'Usuń rezerwację\', {\'image\':\'web/images/reservation_delete.gif\', \'onclick\': \''+this.m_id+'.unreservation2();\' })';
    } else if(this.m_mode == '105') {
      action = 'Button_'+this.m_id+'_Add (\''+this.m_id+'action\', \''+this.m_id+'_add\', \'Wstaw\', {\'image\':\'web/images/table_row_insert.gif\', \'onclick\': \'Modalbox.show(\\\''+this.getMainUrl()+'&table='+this.m_id+'\\\', {title: \\\'Zgłaszanie rezerwacji\\\'});\' });';
      action += 'Button_'+this.m_id+'_Reserve (\''+this.m_id+'action\', \''+this.m_id+'_reserve\', \'Zarezerwuj\', {\'image\':\'web/images/reservation_add.gif\', \'onclick\': \''+this.m_id+'.reservation3();\' });';
      action += 'Button_'+this.m_id+'_Unreserve (\''+this.m_id+'action\', \''+this.m_id+'_unreserve\', \'Usuń rezerwację\', {\'image\':\'web/images/reservation_delete.gif\', \'onclick\': \''+this.m_id+'.unreservation3();\' })';
    } else if(this.m_mode == '102') {
      action = 'Button_'+this.m_id+'_Add (\''+this.m_id+'action\', \''+this.m_id+'_add\', \'Wstaw\', {\'image\':\'web/images/table_row_insert.gif\', \'onclick\': \'Modalbox.show(\\\''+this.getMainUrl()+'&table='+this.m_id+'\\\', {title: \\\'Przecięcia\\\'});\' })';
    } else if(this.m_mode == '2') {
      action = 'Select_'+this.m_id+'_Add (\''+this.m_id+'action\', \''+this.m_id+'_select\', {}, {});';
      action += 'Button_'+this.m_id+'_Add (\''+this.m_id+'action\', \''+this.m_id+'_add\', \'Wstaw\', {\'image\':\'web/images/table_row_insert.gif\', \'onclick\': \'var val = $F(\\\''+this.m_id+'_select\\\'); $(\\\''+this.m_id+'_person_hidden\\\').value = val; '+this.m_id+'.getRecordForTable(\\\'?module=task&action=getRecordForTable&table='+this.m_id+'\\\', null); \'});';
    } else if(this.m_mode == '3') {
      action = 'Button_'+this.m_id+'_File (\''+this.m_id+'action\', \''+this.m_id+'_add\', \'Wstaw\', {\'image\':\'web/images/table_row_insert.gif\', \'onclick\': \'ajaxData(\\\'?module=files&action=index\\\', {}, this);\'});';
    } else if(this.m_mode == '4') {
      action = 'Button_'+this.m_id+'_Insert (\''+this.m_id+'action\', \''+this.m_id+'_add\', \'Wstaw\', {\'image\':\'web/images/table_row_insert.gif\', \'onclick\': \'Modalbox.show(\\\'?module=popup&action=agk\\\', {title: \\\'tytul\\\'});\'});';
    }

    eval(action);

  },
  prepareContent:function() {

    this.tbody = new Array();

    if(typeof(this.m_tableModel) == "undefined")
      return;


    // iteracja po kolejnych wierszach
    for (var rowIdx = 0, rowLen = this.m_tableModel.length; rowIdx < rowLen; ++rowIdx) {

      // <tbody>
      var tbody = new Element('tbody');
      var tbodyIdentTpl = this.m_id+'_tb_'+rowIdx;
      tbody.writeAttribute('id', tbodyIdentTpl);

      // utworzenie nowego wiersza
      var trIdentTpl = this.m_id+'_tr_'+rowIdx;
      var tr = this.createTr(rowIdx, trIdentTpl);

      // wyznaczenie glebokosci - parametr rowspan w przypadku tabel zlozonych
      var depth = this.getDepth(this.m_tableModel[rowIdx]);

      var rowArray = $A(this.m_tableModel[rowIdx]);

      for (var index = 0; index < rowArray.length; ++index) {
        var trId = trIdentTpl+'_'+index;
        var idTd = this.m_id+'_'+rowIdx+'_'+index;
        if(rowArray[index] instanceof Array) {
          var subRowArray = $A(rowArray[index]);
          var first = true;
          for (var extIndex = 0; extIndex < subRowArray.length; ++extIndex) {
            if(!first)
              tr = this.createTr(rowIdx, trId);

            if(subRowArray[extIndex] instanceof Array) {

              first = false;
            }
          }
        } else {
          // utworzenie nowego elementu <td>
          var td = this.createTd(idTd, null, [this.m_id+'_r_'+rowIdx, this.m_id+'_c_'+index], depth);
          // dodanie elementu <td> do <tr>
          tr.insert(td);
        }
      }
      tbody.insert(tr);
      this.tbody.push(tbody);
      //this.tbody.insert(tr);

    }
  },
  createTr:function(rowIdx, trIdentTpl) {
    var tr = new Element('tr');
    tr.writeAttribute('id', trIdentTpl);
    tr.addClassName(this.m_switcher[rowIdx%2]);
    return tr;
  },
  createTd:function(id, value, classArr, rowspan, colspan) {
    var td = new Element('td');
    td.id = id;
    if(value != null)
      td.update(value);
    if(rowspan > 1) {
      td.writeAttribute('rowspan', rowspan);
    }
    if(colspan > 1) {
      td.writeAttribute('colspan', colspan);
    }
    if(classArr instanceof Array) {
      for (var index = 0; index < classArr.length; ++index) {
        td.addClassName(classArr[index]);
      }
    } else {
      td.addClassName(classArr);
    }
    return td;
  },
  getDepth:function(model, lastResult) {

    if(model instanceof Array) {
      var result = 0;
      var tmp = 0;
      for (var index = 0; index < model.length; ++index) {
        if(model[index] instanceof Array) {
            var submodel = model[index];
            tmp = submodel.size();
            if(!isNaN(this.getDepth(submodel, tmp)))
              result = this.getDepth(submodel, tmp);
        }
      }
      if(!isNaN(result) && !isNaN(lastResult))
        return Math.max(result,lastResult);
      else
        return result;
    } else {
      return 0;
    }

  },
  prepareFooter:function(){
    this.tfoot = new Element('tfoot');
    this.addSummary(this.tfoot);
    this.addPanel(this.tfoot);
    this.addLegend(this.tfoot);
  },
  isSummary:function() {
    for (var i = 0, len = this.m_columnModel.length; i < len; ++i) {
      var sum = (this.m_columnModel[i].evalJSON()).sum;
      if(sum)
        return true;
    }
    return false;
  },
  addSummary:function(tfoot) {
    if(!this.isSummary())
        return;
    var tr = new Element('tr');
    for (var i = 0, len = this.m_columnModel.length; i < len; ++i) {
      var sum = (this.m_columnModel[i].evalJSON()).sum;
      var td = new Element('td');
      if(sum) {
        td.id = this.m_id+'_sum_'+i;
        td.update('suma: ');
      } else {
        td.update('&nbsp;');
      }
      tr.insert(td);
    }
    tfoot.insert(tr);
  },
  addPanel:function(tfoot) {

    var tr = new Element('tr');
    var td = this.createTd(this.m_id+'action', '&nbsp;', null, 0, this.m_columnModel.length);
    tr.insert(td);
    tfoot.insert(tr);
  },
  addLegend:function(tfoot) {
    if(this.m_legend == null)
      return;
    var tr = new Element('tr');
    var td = this.createTd(null, this.m_legend, null, 0, this.m_columnModel.length);
    tr.insert(td);
    tfoot.insert(tr);
  },
  prepare: function(){

    this.prepareCaption();
    this.prepareHeader();
    this.prepareContent();
    this.prepareFooter();

    $(this.m_id).insert(this.caption);
    $(this.m_id).insert(this.thead);

    for (var i = 0, len = this.tbody.length; i < len; ++i) {
      this.tbody[i].style.display = "none";
      //$('debug').insert(this.tbody[i].id + ' | ');
      $(this.m_id).insert(this.tbody[i]);
      Effect.toggle(this.tbody[i].id,'appear');
      //Effect.toggle(this.tbody[i].id,'blind');
      //Effect.toggle(this.tbody[i].id,'slide');
    }
    $(this.m_id).insert(this.tfoot);

    this.afterPrepareContent();
    //this.fillTable(data)

    this.refreshSummarize();

  },
  setColumnModel: function(columnModel){
      this.m_columnModel = columnModel;
  },
  setMainUrl: function(url){
      this.m_mainUrl = url;
  },
  getMainUrl: function(){
      return this.m_mainUrl;
  },
  setTableModel: function(tableModel){
      this.m_tableModel = tableModel;
  },
  getTableModel: function() {
//      for(var i = 0; i < this.m_tableModel.length; i++) {
//          this.m_tableModel[i].value = escape(this.m_tableModel[i].value);
//      }
      return this.m_tableModel;
  },
  clear: function() {
      for(var i = 0; i < this.m_tableModel.length; i++) {
          var tbodyIdx = this.m_id+'_tb_'+i;
          $(tbodyIdx).remove();
      }
      this.m_tableModel = [];
      return this.m_tableModel;
  },
  dropRow: function() {
      for(var i = 0; i < this.m_tableModel.length; i++) {
          var tbodyIdx = this.m_id+'_tb_'+i;
          $(tbodyIdx).remove();
      }
  },
  deleteRow: function(tbodyIdx) {
    if($(tbodyIdx) != null) {
      var trElements = $(tbodyIdx).childElements();
      for (var i = 0, len = trElements.length; i < len; ++i) {
        trElements[i].remove();
       // this.m_tableModel.splice(i, i);
      }
      $(tbodyIdx).remove();
    }
  },
  reservation2: function() {

      if(this.m_tableModel.length < 1)
          return;

      $(this.m_id).hide();

      var el = getSpiner();
      $('div_'+this.m_id).insert(el);
      $('div_'+this.m_id).show();

      var adr = '?module=popup&action=registerNumber';
      adr += '&table='+this.m_id+'&typ=2';

      var sekcje = '';
      var numery = '';
      for(var i = 0, len = this.m_tableModel.length; i < len; ++i) {
          var sTmp = this.m_tableModel[i][0].value.substr(this.m_tableModel[i][0].value.indexOf('|')+1, this.m_tableModel[i][0].value.length);
          var nTmp = this.m_tableModel[i][1].value.substr(this.m_tableModel[i][1].value.indexOf('|')+1, this.m_tableModel[i][1].value.length);

//          sekcje += this.m_tableModel[i][0].value + ',';
//          numery += this.m_tableModel[i][1].value + ',';
          sekcje += sTmp + ',';
          numery += nTmp + ',';

      }
      sekcje = sekcje.substr(0, sekcje.length-1);
      numery = numery.substr(0, numery.length-1);
      var tableIdx  = this.m_id;
      new Ajax.Request(adr, {
        method: 'post',
        parameters: {'sekcje':sekcje, 'numery':numery},
        onSuccess: function(transport) {
            eval(transport.responseText);
            $(tableIdx).show();
            el.hide();
        },
        onException:function() {
            alert('Błąd podczas wypełniania tabeli: '+tableIdx);
            $(tableIdx).show();
            el.hide();
        }
      });
  },
  unreservation2: function() {

      if(this.m_tableModel.length < 1)
          return;

      $(this.m_id).hide();

      var el = getSpiner();
      $('div_'+this.m_id).insert(el);
      $('div_'+this.m_id).show();

      var adr = '?module=popup&action=unregisterNumber';
      adr += '&table='+this.m_id+'&typ=2';

      var sekcje = '';
      var numery = '';
      for(var i = 0, len = this.m_tableModel.length; i < len; ++i) {
          sekcje += this.m_tableModel[i][0].value + ',';
          numery += this.m_tableModel[i][1].value + ',';
      }
      sekcje = sekcje.substr(0, sekcje.length-1);
      numery = numery.substr(0, numery.length-1);
      var tableIdx  = this.m_id;
      new Ajax.Request(adr, {
        method: 'post',
        parameters: {'sekcje':sekcje, 'numery':numery},
        onSuccess: function(transport) {
            eval(transport.responseText);
            $(tableIdx).show();
            el.hide();
        },
        onException:function() {
            alert('Błąd podczas wypełniania tabeli: '+tableIdx);
            $(tableIdx).show();
            el.hide();
        }
      });
  },
  reservation3: function() {

      if(this.m_tableModel.length < 1)
          return;

      $(this.m_id).hide();

      var el = getSpiner();
      $('div_'+this.m_id).insert(el);
      $('div_'+this.m_id).show();

      var adr = '?module=popup&action=registerNumber';
      adr += '&table='+this.m_id+'&typ=3';

      var sekcje = '';
      var numery = '';
      for(var i = 0, len = this.m_tableModel.length; i < len; ++i) {
          var sTmp = this.m_tableModel[i][0].value.substr(this.m_tableModel[i][0].value.indexOf('|')+1, this.m_tableModel[i][0].value.length);
          var nTmp = this.m_tableModel[i][1].value.substr(this.m_tableModel[i][1].value.indexOf('|')+1, this.m_tableModel[i][1].value.length);

//          sekcje += this.m_tableModel[i][0].value + ',';
//          numery += this.m_tableModel[i][1].value + ',';
          sekcje += sTmp + ',';
          numery += nTmp + ',';
      }
      sekcje = sekcje.substr(0, sekcje.length-1);
      numery = numery.substr(0, numery.length-1);
      var tableIdx  = this.m_id;
      new Ajax.Request(adr, {
        method: 'post',
        parameters: {'sekcje':sekcje, 'numery':numery},
        onSuccess: function(transport) {
            eval(transport.responseText);
            $(tableIdx).show();
            el.hide();
        },
        onException:function() {
            alert('Błąd podczas wypełniania tabeli: '+tableIdx);
            $(tableIdx).show();
            el.hide();
        }
      });
  },
  unreservation3: function() {

      if(this.m_tableModel.length < 1)
          return;

      $(this.m_id).hide();

      var el = getSpiner();
      $('div_'+this.m_id).insert(el);
      $('div_'+this.m_id).show();

      var adr = '?module=popup&action=unregisterNumber';
      adr += '&table='+this.m_id+'&typ=3';

      var sekcje = '';
      var numery = '';
      for(var i = 0, len = this.m_tableModel.length; i < len; ++i) {
          sekcje += this.m_tableModel[i][0].value + ',';
          numery += this.m_tableModel[i][1].value + ',';
      }
      sekcje = sekcje.substr(0, sekcje.length-1);
      numery = numery.substr(0, numery.length-1);
      var tableIdx  = this.m_id;
      new Ajax.Request(adr, {
        method: 'post',
        parameters: {'sekcje':sekcje, 'numery':numery},
        onSuccess: function(transport) {
            eval(transport.responseText);
            $(tableIdx).show();
            el.hide();
        },
        onException:function() {
            alert('Błąd podczas wypełniania tabeli: '+tableIdx);
            $(tableIdx).show();
            el.hide();
        }
      });
  },
  addRow: function() {
    var rowIdx = this.m_tableModel.length;
    var tbody = new Element('tbody');
    var tbodyIdentTpl = this.m_id+'_tb_'+rowIdx;
    tbody.writeAttribute('id', tbodyIdentTpl);

    var tr = new Element('tr');
    tr.addClassName(this.m_switcher[rowIdx%2]);
    var rowModel = new Array();
    for (var i = 0, len = this.m_columnModel.length; i < len; ++i) {

      var cell = new Object();
      cell.colIdx = i;
      cell.id = rowIdx + '_' + i;
      cell.value = '';

      var callFun = (this.m_columnModel[i].evalJSON()).callFunction;
      if(typeof(callFun) != "undefined") {
          cell.onClick = this.m_id+'.'+callFun+'('+tbodyIdentTpl+');';
      }

      var td = new Element('td');
      td.id = 'in_'+this.m_id+'_'+rowIdx+'_'+i;
      tr.insert(td);
      rowModel.push(cell);

//      alert('Sumowanie');
//      if((this.m_columnModel[i].evalJSON()).sum) {
//        x = (this.m_columnModel[i].evalJSON()).component+'_'+item1+' (\''+idTd+'\', \''+idTd+'\', \''+value+'\', {\'class\':\''+this.m_id+'_'+index+'\',\'onblur\': \' var tab = 0; $$(\\\'input.'+this.m_id+'_'+index+'\\\').each( function(item) { if(!isNaN(parseFloat(item.value))) tab += parseFloat(item.value); });  var display = \\\'suma: \\\'+tab ;$(\\\''+this.m_id+'_sum_'+i+'_div\\\').update(display);\'});';
//        eval(x);
//      }

    }
    tbody.insert(tr);
    this.tbody.push(tbody);
    $(this.m_id).insert(tbody);

    for (var j = 0, rowLen = rowModel.length; j < rowLen; ++j) {
      var item1 = rowModel[j].colIdx;
      var item2 = 'i'+this.m_id+'_'+rowModel[j].id;
      var value = '';
      if(rowModel[j].value != null)
        rowModel[j].value = rowModel[j].value.escapeHTML();
      var onclick = rowModel[j].onClick;

      if((this.m_columnModel[j].evalJSON()).sum) {
        eval((this.m_columnModel[j].evalJSON()).component+'_'+item1+' (\'in_'+this.m_id+'_'+rowIdx+'_'+j+'\', \''+item2+'\', \''+value+'\', {\'class\':\''+this.m_id+'_'+j+'\', \'onblur\': \''+this.m_id+'.updateModel(\\\''+item2+'\\\'); var tab = 0; $$(\\\'input.'+this.m_id+'_'+j+'\\\').each( function(item) { if(!isNaN(parseFloat(item.value))) tab += parseFloat(item.value); });  var display = \\\'suma: \\\'+tab ;$(\\\''+this.m_id+'_sum_'+j+'_div\\\').update(display);\'});');
      } else {
        if(typeof(onclick) != "undefined") {
          eval((this.m_columnModel[j].evalJSON()).component+'_'+item1+' (\'in_'+this.m_id+'_'+rowIdx+'_'+j+'\', \''+item2+'\', \''+value+'\', {\'class\':\''+this.m_id+'_'+j+'\', \'onclick\': \''+onclick+'\', \'onblur\': \''+this.m_id+'.updateModel(\\\''+item2+'\\\');\'});');
        } else
          eval((this.m_columnModel[j].evalJSON()).component+'_'+item1+' (\'in_'+this.m_id+'_'+rowIdx+'_'+j+'\', \''+item2+'\', \''+value+'\', {\'class\':\''+this.m_id+'_'+j+'\', \'onblur\': \''+this.m_id+'.updateModel(\\\''+item2+'\\\');\'});');
      }

    }

    this.m_tableModel[this.m_tableModel.length] = rowModel;
  },
  addRowF: function(object) {

    if(typeof(object)=="undefined")
        return;

    var rowIdx = this.m_tableModel.length;

    var tbody = new Element('tbody');
    var tbodyIdentTpl = this.m_id+'_tb_'+rowIdx;
    tbody.writeAttribute('id', tbodyIdentTpl);

    var tr = new Element('tr');
    tr.addClassName(this.m_switcher[rowIdx%2]);
    var rowModel = new Array();
    for (var i = 0, len = this.m_columnModel.length; i < len; ++i) {
      var cell = new Object();
      cell.colIdx = i;
      cell.id = rowIdx + '_' + i;
      cell.value = '';

      var callFun = (this.m_columnModel[i].evalJSON()).callFunction;

      //alert(callFun);
      if(typeof(callFun) != "undefined") {
          cell.onClick = this.m_id+'.'+callFun+'('+tbodyIdentTpl+');';
      }

      var td = new Element('td');
      td.id = 'in_'+this.m_id+'_'+rowIdx+'_'+i;
      tr.insert(td);
      rowModel.push(cell);

    }
    tbody.insert(tr);
    this.tbody.push(tbody);
    $(this.m_id).insert(tbody);

    for (var j = 0, rowLen = rowModel.length; j < rowLen; ++j) {
      var item1 = rowModel[j].colIdx;
      var item2 = 'i'+this.m_id+'_'+rowModel[j].id;
      var objKeys = Object.keys(object);
      var objValues = Object.values(object);

      var value = '';
      if(typeof(objValues[j]) != "undefined")
          value = objValues[j];
      rowModel[j].value = value;
      var onclick = rowModel[j].onClick;

      var colClass = (this.m_columnModel[j].evalJSON()).colClass;
      if((this.m_columnModel[j].evalJSON()).sum) {
        if(typeof(colClass) != "undefined") {
            eval((this.m_columnModel[j].evalJSON()).component+'_'+item1+' (\'in_'+this.m_id+'_'+rowIdx+'_'+j+'\', \''+item2+'\', \''+value+'\', {\'className\':\''+colClass+' r'+rowIdx+'\', \'onblur\': \''+this.m_id+'.updateModel(\\\''+item2+'\\\'); var tab = 0; alert(getElementById(\\\'itableInvoice_0_3\\\')); $$(\\\''+colClass+'\\\').each( function(item) { if(!isNaN(parseFloat(item.value))) tab += parseFloat(item.value); });  var display = \\\'suma: \\\'+tab ;$(\\\''+this.m_id+'_sum_'+j+'_div\\\').update(display);\'});');
        } else {
            eval((this.m_columnModel[j].evalJSON()).component+'_'+item1+' (\'in_'+this.m_id+'_'+rowIdx+'_'+j+'\', \''+item2+'\', \''+value+'\', {\'className\':\''+this.m_id+'_'+j+' r'+rowIdx+'\', \'onblur\': \''+this.m_id+'.updateModel(\\\''+item2+'\\\'); var tab = 0; $$(\\\''+this.m_id+'_'+j+'\\\').each( function(item) { if(!isNaN(parseFloat(item.value))) tab += parseFloat(item.value); });  var display = \\\'suma: \\\'+tab ;$(\\\''+this.m_id+'_sum_'+j+'_div\\\').update(display);\'});');
        }
      } else {
        if(typeof(onclick) != "undefined") {
          if(typeof(colClass) != "undefined") {
            eval((this.m_columnModel[j].evalJSON()).component+'_'+item1+' (\'in_'+this.m_id+'_'+rowIdx+'_'+j+'\', \''+item2+'\', \''+value+'\', {\'className\':\''+colClass+' r'+rowIdx+'\', \'onclick\': \''+onclick+'\', \'onblur\': \''+this.m_id+'.updateModel(\\\''+item2+'\\\');\'});');
          } else {
            eval((this.m_columnModel[j].evalJSON()).component+'_'+item1+' (\'in_'+this.m_id+'_'+rowIdx+'_'+j+'\', \''+item2+'\', \''+value+'\', {\'className\':\''+this.m_id+'_'+j+' r'+rowIdx+'\', \'onclick\': \''+onclick+'\', \'onblur\': \''+this.m_id+'.updateModel(\\\''+item2+'\\\');\'});');
          }
        } else {
          if(typeof(colClass) != "undefined") {
            eval((this.m_columnModel[j].evalJSON()).component+'_'+item1+' (\'in_'+this.m_id+'_'+rowIdx+'_'+j+'\', \''+item2+'\', \''+value+'\', {\'className\':\''+colClass+' r'+rowIdx+'\', \'onblur\': \''+this.m_id+'.updateModel(\\\''+item2+'\\\');\'});');
          } else {
            eval((this.m_columnModel[j].evalJSON()).component+'_'+item1+' (\'in_'+this.m_id+'_'+rowIdx+'_'+j+'\', \''+item2+'\', \''+value+'\', {\'className\':\''+this.m_id+'_'+j+' r'+rowIdx+'\', \'onblur\': \''+this.m_id+'.updateModel(\\\''+item2+'\\\');\'});');
          }
        }
      }

    }

    this.m_tableModel[this.m_tableModel.length] = rowModel;
  },
  addSubRow: function(rowIdx, colIdx) {

    var tbody = $(this.m_id+'_tb_'+rowIdx);
    var tr = $(this.m_id+'_'+rowIdx);
    var tdArr = tr.childElements();
    for (var i = 0, len = tdArr.length; i < len; ++i) {
      var td = tdArr[i];
      if(colIdx == i) {
          var struct = this.subRecordCount(rowIdx, colIdx);
          var tdId = struct.ident+'_'+struct.counter;
          var trId = struct.ident+'_'+struct.counter;
          var trTmp = this.createTr(rowIdx, trId);
          var tdTmp = this.createTd(tdId, null, [this.m_id+'_r_'+rowIdx, this.m_id+'_c_'+colIdx]);
          //var td = this.createTd(idTd, null, [this.m_id+'_'+rowIdx, this.m_id+'_'+index], depth);
          trTmp.insert(tdTmp);
          tbody.insert(trTmp);

          if((this.m_columnModel[colIdx].evalJSON()).sum) {
            eval((this.m_columnModel[colIdx].evalJSON()).component+'_'+colIdx+' (\''+tdId+'\', \'in_'+tdId+'\', null, {\'class\':\''+this.m_id+'_'+colIdx+'\',\'onblur\': \' var tab = 0; $$(\\\'input.'+this.m_id+'_'+colIdx+'\\\').each( function(item) { if(!isNaN(parseFloat(item.value))) tab += parseFloat(item.value); });  var display = \\\'suma: \\\'+tab ;$(\\\''+this.m_id+'_sum_'+colIdx+'_div\\\').update(display);\'});');
          } else {
            eval((this.m_columnModel[colIdx].evalJSON()).component+'_'+colIdx+' (\''+tdId+'\', \'in_'+tdId+'\', null, {\'class\':\''+this.m_id+'_'+colIdx+'\'});');
          }

          continue;
      }

      var res = td.readAttribute('rowspan');
      var rowspan = 0;
      if(res == null)
        rowspan = 1;
      else
        rowspan = res;

      td.writeAttribute('rowspan', ++rowspan);
    }
  },
  subRecordCount:function(rowIdx, colIdx) {
    var tab = 0;
    var tmp = new String();
    var last = new Object();
    var rowClass = this.m_id+'_r_'+rowIdx;
    var colClass = this.m_id+'_c_'+colIdx;
    var condition = 'td[class="'+rowClass+' '+colClass+'"]';
    $$(condition).each(
      function(item)
        {
          tmp = item.id;
          ++tab;
        });
    last.counter = tab;
    last.ident = tmp.substr(0, tmp.lastIndexOf('_'));
    return last;
  },
  refreshSummarize:function() {
    for (var index = 0, len = this.m_columnModel.length; index < len; ++index) {
      var tab = 0;
      $$('input.'+this.m_id+'_'+index).each(
        function(item) {
          if(!isNaN(parseFloat(item.value)))
            tab += parseFloat(item.value);
        });
        var display = 'suma: '+tab;
        if($(this.m_id+'_sum_'+index+'_div') != null)
          $(this.m_id+'_sum_'+index+'_div').update(display);
    }
  },
  setLegend:function(source) {
    this.m_legend = source;
  },
  updateModel:function(id) {
    if(id == '') return;
    var idTmp = id;
    var template = new RegExp('i'+this.m_id+'_');
    var result = id.replace(template, "");
    id = result;
    var tab = id.split("_");
    var expr = 'this.m_tableModel';
    for(var idx=0; idx < tab.length; idx++) {
      expr += '['+tab[idx]+']';
    }
    expr += '.value=\''+$(idTmp).value+'\'';
    eval(expr);
  },
  clearAndfillTable:function(data) {
      this.setTableModel(this.clear());
      this.fillTable(data);
  },
  fillTable:function(data) {

    for(var idx=0; idx < data.length; idx++) {
        var tab = new Object();
        for(var c = 0; c < this.m_columnModel.length; c++) {
            tab[(this.m_columnModel[c].evalJSON()).bindValue] = data[idx][(this.m_columnModel[c].evalJSON()).bindValue];
        }
        this.addRowF(tab);
    }
  },
  goMap: function(tbodyIdx) {
      window.open('http://bytom-plan.atena.ispik.pl/geoportal/map/index.php?IdProfil=interKERG1');
  },
  addWarp: function(row) {
      window.open('?module=files&action=index&table='+this.m_id+'&row='+row, '', 'toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=0,resizable=0,height=100,width=350,top=400,left=400');
  },
  updateField: function (row, value) {

    var tableIdx  = this.m_id;
    $(tableIdx).remove();
    //$(tableIdx).hide();
    var el = getSpiner();
    $('div_'+this.m_id).insert(el);
    $('div_'+this.m_id).show();

    for (var idx = 0, rowLen = this.m_tableModel.length; idx < rowLen; ++idx) {
        if(idx == row) {
            o = new Object();
            o.dir = value[0].dir;
            o.www = value[0].www;
            o.nazwa = value[0].nazwa;
            o.nazwa_tmp = value[0].nazwa_tmp;
            o.rozmiar = value[0].rozmiar;
            o.data = value[0].data;

            this.m_tableModel[idx][9].value = o;
        }
    }
    this.setTableModel(this.m_tableModel);
    $('div_'+this.m_id).insert(new Element('table', {'id' : this.m_id, 'class' : 'table'}));
    $('div_'+this.m_id).insert(new Element('hidden', {'id' : this.m_id+'_hidden'}));
    this.prepare();
    $(tableIdx).show();
    el.hide();

  },
  calculate: function (row) {
    alert(this.m_tableModel[row]);
  },
  getRecordForTable: function(AjaxUrl, params) {
    new Ajax.Request(AjaxUrl, {
        method: 'get',
        parameters: params,
        onSuccess: function(transport) {
            eval(transport.responseText);
        }
    });
}
});
