/*
     $Revision$
     $Id$
*/

//ItemTable
var itemListTables = new Array(); // Array met alle itemlists. Per itemlist kolom-parameters en geselecteerde waarden.


function registerItem(p_itemlist_id, newRow, p_next_index)
{
  var v_selectedItems = itemListTables[p_itemlist_id].selectedItems || [];
  var unique_column = uniqueColNr(p_itemlist_id);
  var col = newRow[unique_column];
  var found = false;
  for (var i=0; i<v_selectedItems.length; i++)
  { // Komt de nieuwe waarde voor in de kolom met unieke waarden.
    var selRow = v_selectedItems[i];
    if (col == selRow.values[unique_column]) {
      found = true;
    }
  }
  var isNew = !found;
  if (isNew) {
    v_selectedItems.push( {rowIndex: p_next_index, values: newRow});
  }
  itemListTables[p_itemlist_id].selectedItems = v_selectedItems;
  return isNew;
}

function uniqueColNr(p_itemlist_id)
{
  var unique_column = -1;
  for (var i=0; i<itemListTables[p_itemlist_id].columns.length; i++)
  { // Zoek de kolom die unieke waarden moet bevatten.
    var col = itemListTables[p_itemlist_id].columns[i];
    if (col.unique && unique_column == -1) { // Slechts 1 unieke kolom!
      unique_column = i;
    }
  }
  return unique_column;
}

function addItem(p_itemlist_id, p_row) //, params)
{
  // controleer of verplichte waarden zijn geselecteerd
  var receiveInfo = true;
  var missing_cols = [];
  for (var i=0; i<itemListTables[p_itemlist_id].columns.length; i++)
  {
    var col = itemListTables[p_itemlist_id].columns[i];
    col.required = (col.required ? col.required : false);
    col.hidden = (col.hidden ? col.hidden : false);

    if (col.required && !col.hidden && (!p_row[i] || p_row[i] == "" || p_row[i] == -1)) {
      missing_cols.push(col.caption);
      receiveInfo = false;
    }
  }
  if (!receiveInfo) {
    FcltMgr.alert(L("mgt_validation_error_1").format(missing_cols.join(", ")));
  }
  
  var v_table_id = p_itemlist_id + "_table";
  table = document.getElementById(v_table_id);
  var table = document.getElementById(v_table_id)
  var rows = document.getElementById(v_table_id).getElementsByTagName("tr")
  var tablelength = rows.length;
  var next_rowIndex = rows.length;

  // Om het niet te gek te maken beperken we het aantal regels
  if (itemListTables[p_itemlist_id].params.maxrows) {
    if (tablelength - 1 >= itemListTables[p_itemlist_id].params.maxrows) {
      FcltMgr.alert(L("lcl_max_lines_reached").format(itemListTables[p_itemlist_id].params.maxrows));
      return;
    }
  }

  var registerOK = registerItem(p_itemlist_id, p_row, next_rowIndex);
  if (registerOK) {
    createRow(p_itemlist_id, p_row, next_rowIndex, true, true);
  }
}

function setInnerText(innerObject, innerValue)
{
	if (typeof innerObject.innerText != 'undefined')
	  innerObject.innerText = innerValue
	else
		innerObject.textContent = innerValue;
  return innerObject;
}

function createRow(p_itemlist_id, p_row, rowIndex, addSorted, editable)
{
  // insert white line
  table = document.getElementById(p_itemlist_id + "_table");
  // insert data rows
  var before_rowIndex = rowIndex;
  if (addSorted) {
    // Array sorteren  
    var unique_column = uniqueColNr(p_itemlist_id);
    var v_selectedItems = itemListTables[p_itemlist_id].selectedItems;
    v_selectedItems.sort((a,b) => {
          var x = a.values[unique_column];
          var y = b.values[unique_column];
          if (x < y) { return -1; }
          if (x > y) { return 1; }
          return 0;
        });
    // Bepaal regel op scherm waar het toegevoegd moet worden.
    var before_rowIndex = rowIndex;
    for (var i=0; i<v_selectedItems.length; i++)
    {
      if (rowIndex == v_selectedItems[i].rowIndex)
        before_rowIndex = i+1;
    }
  }
  tr = table.insertRow(before_rowIndex);

  // Create drop button
  cell = tr.insertCell(-1);
  cell.className = "result";
  cell.align = "center";
  cell.innerHTML = "<span title='" + L("lcl_del_row") + "' OnClick='cancelItem(\"" + p_itemlist_id + "\", " + rowIndex + ")' class='default-clickable-icon'>" + I("fa-trash-alt") + "</span>";

  for (var i=0; i<p_row.length; i++)
  {
    var col_params = itemListTables[p_itemlist_id].columns[i];
    var col = p_row[i];
    var cell_value = "";
    switch (col_params.typ)
    {
      case "date": cell_value = (p_row[i] ? toDateString(new Date(parseInt(p_row[i], 10))) : "");
                   break;
      default:     cell_value = p_row[i];
    }
    cell = tr.insertCell(-1);
    cell.className = "result nowrap" + (col_params.hidden ? " hidden" : "");
    // innerHTML opent een htmlparser die overbodige spaties en line breaks verwijderd in IE, daarom met innerText oplossen
    // Input velden moeten wel met innerHTML of outerHTML anders wordt het text
    cell = setInnerText(cell, cell_value);
    cell.title = cell_value;
    cell.align = 'left';
  }

  FcltMgr.resized();
}

function cancelItem(p_itemlist_id, rowIndex)
{
  FcltMgr.confirm(L("lcl_del_row_confirm"), function() {
      var v_selectedItems = itemListTables[p_itemlist_id].selectedItems;
      for (var i=0; i<v_selectedItems.length; i++)
      {
        if (v_selectedItems[i].rowIndex == " " + rowIndex) {
          document.getElementById(p_itemlist_id + "_table").deleteRow(i+1);
          v_selectedItems.splice(i, 1);
          FcltMgr.resized();
        }
      }
      const fnName = itemListTables[p_itemlist_id].params.onDeleteItem;
      const fn = window[fnName];
      if (typeof fn === "function")
      { // Roep de functie aan die in params.onDeleteItem staat.
        fn();
      }
  });
}

function cancelAllItems(p_itemlist_id)
{
  var v_selectedItems = itemListTables[p_itemlist_id].selectedItems;
  if (v_selectedItems.length == 0) {
    FcltMgr.alert(L("lcl_del_norows"));
  }
  else {
    FcltMgr.confirm(L("lcl_del_allrows_confirm"), function() {
        for (var i=v_selectedItems.length; i>0; i--)
      {
          document.getElementById(p_itemlist_id + "_table").deleteRow(i);
          v_selectedItems.splice(i-1, 1);
      }
      FcltMgr.resized();
    });
  }
}
