/*
     $Revision$
     $Id$

     File:        cnt_edit_scope.js
*/

var highlitedRowObj = -1;
var highlitedRowObjSort = -1;
var highlitedRowLoc = -1;

async function cnt_submit()
{
  document.activeElement.blur(); // trigger laatste onChanges
  if (!await validateForm("u2"))
      return false;

  $.post( $("form[name=u2]")[0].action
        , $("[name=u2]").serialize()
        , FcltCallbackClose
        , "json"
        );
}

function cnt_cancel()
{
  FcltMgr.closeDetail(window, { cancel: true } );
}

function updateBld(autlevel)
{
  var locatie_key_arr = new Array();
  $('#locs :selected').each(function(i, selected)
                            {
                              locatie_key_arr[i] = $(selected).val();
                            });
  $("#blds").closest("td").load("../Shared/loadGebouw.asp",
                          {
                            autlevel: autlevel,
                            startmulti: $('#select#blds[multiple]').length,
                            terrein: 1,
                            locatie_key_arr: (locatie_key_arr.length != 0 ? locatie_key_arr : [-1])  // -1 is ook een geldige waarde
                          }, function() { $('#blds').multiSelectToggle(); updateFlr(autlevel)});
}
function updateFlr(autlevel)
{
  var gebouw_key_arr = new Array();
  $('#blds :selected').each(function(i, selected)
                            {
                              gebouw_key_arr[i] = $(selected).val();
                            });
  $("#flrs").closest("td").load("../Shared/loadVerdieping.asp",
                          {
                            autlevel: autlevel,
                            startmulti: $('select#flrs[multiple]').length,
                            gebouw_key_arr: (gebouw_key_arr.length != 0 ? gebouw_key_arr : [-1])  // -1 is ook een geldige waarde
                          }, function() { $('#flrs').multiSelectToggle(); updateRoo(autlevel)});
}
function updateRoo(autlevel)
{
  var verdieping_key_arr = new Array();
  $('#flrs :selected').each(function(i, selected)
                            {
                              verdieping_key_arr[i] = $(selected).val();
                            });
  $("#rooms").closest("td").load("../Shared/loadRuimte.asp",
                          {
                            autlevel: autlevel,
                            startmulti: $('#select#rooms[multiple]').length,
                            verdieping_key_arr: (verdieping_key_arr.length != 0 ? verdieping_key_arr : [-1])  // -1 is ook een geldige waarde
                          }, function() { $('#rooms').multiSelectToggle(); FcltMgr.resized(); });
}

function showObjDetail(evt)
{
  evt = evt || window.event;
  var obj = evt.srcElement || evt.target;
  var obj_str = "";
  var obj_key = obj.value;
  if (obj_key && obj_key > 0 && $("#objs").length)
  {
    var url = "appl/INS/ins_show_deel.asp?ins_key=" + obj_key + "&urole=bo";
    $('#objs :selected').each(function(i, selected)
                              {
                                if ($(selected).val() == obj_key)
                                  obj_str = $(selected).text();
                              });
    FcltMgr.openDetail(url, L("lcl_cnt_object") + " " + obj_str);
  }
}

function updateRoomObj()
{
  $("#objs").load("../cnt/loadRuimteObjecten.asp",
                  { locatiekey: $("#locatiekey").val(),
                    gebouwkey: $("#gebouwkey").val(),
                    bttype: $("#bttype").val(),
                    verdiepingkey: $("#verdiepingkey").val(),
                    ruimtekey: $("#ruimtekey").val(),
                    prs_key: $("#sName_key").val(),
                    dept_key: $("#sDept_key").val(),
                    disc_key: $("#disc").val(),
                    srtgrp_key: $("#srtgroep").val(),
                    grp_key: $("#srtdeel").val()
                  });
}

function onAfdelingChange()
{ // on change of select box persons or organisation it empties place select boxes
  emptyPlace();
  if ($("#sDept_key").val() > 0 && $("#sDept_key").val() != $("#prsafd_key").val())
    emptyPersoon();
}

function process_afdeling(data, textStatus)
{
    if (data)
    {
      // setValue(key, txt, doonChange, checkExist, extraParam, lastTry)
      sgDept.setValue(data.afd_key, data.afdeling, false, true);
      updateRoomObj();
    }
}

function onPersoonChange()
{ // on change of select box persons or organisation it empties place select boxes
  emptyPlace();

  if ($("#prsafd_key").val() > 0)
    $.getJSON("./get_cnt_info_ajax.asp",
              { req_info: "afdeling",
                afd_key: $("#prsafd_key").val() },
              process_afdeling);
}

function onPlaatsChange()
{ // on change of place select boxes it empties person and organisation select box
  emptyAfdeling();
  emptyPersoon();
  updateRoomObj();
}

function emptyPersoon()
{
  sgPerson.setValue(-1, "");
}

function emptyAfdeling()
{
  sgDept.setValue(-1, "");
}

function emptyPlace()
{ // on change of select box persons or organisation it empties place select boxes
  if ($("#locatie").length)
  {
    // setValue(key, txt, doonChange, checkExist, extraParam, lastTry)
    sgLoc.setValue(-1, "");
    sgBld.setValue(-1, "");
    sgFlr.setValue(-1, "");
    sgRoom.setValue(-1, "");
  }

  updateRoomObj();
}

function updateGroup(pautfunction)
{
  var disc_key_arr = new Array();
  $('#disc :selected').each(function(i, selected)
                            {
                              disc_key_arr[i] = $(selected).val();
                            });
  if (disc_key_arr.length != 0)
    $("#srtgroup").load("../Shared/loadGroup.asp?" + serializeObj(
                        { autfunction: pautfunction,
                          disc_key_arr: (disc_key_arr.length != 0 ? disc_key_arr.join(",") : ""),
                          module: "ins",
                          multi: 1,
                          size: 10,
                          selectfirstone: 1 }),
                        function ()
                        { // Laad de items
                          updateSrtDeel(pautfunction);
                        });
  else
    $("#srtgroup").empty();
}

function updateSrtDeel(pautfunction)
{
  var group_key_arr = new Array();
  $('#srtgroup :selected').each(function(i, selected)
                             {
                               group_key_arr[i] = $(selected).val();
                             });
  if (group_key_arr.length != 0)
    $("#srtdeelmulti").load("../Shared/loadSrtDeel.asp?" + serializeObj(
      { autfunction: pautfunction,
        srtgroup_key_arr: (group_key_arr != 0 ? group_key_arr.join(",") : ""),
        module: "ins",
        multi: 1,
        size: 10,
        selectfirstone: 1
      })
    );
  else
    $("#srtdeelmulti").empty();
}

function removeObj()
{
  if (highlitedRowObj > 0)
  {
    deletingRow = "row" + highlitedRowObj;
    index = document.getElementById(deletingRow).rowIndex;
    document.getElementById("cntobjscope_list").deleteRow(index);
    highlitedRowObj = -1;
  }
}

function removeObjSort()
{
  if (highlitedRowObjSort > 0)
  {
    deletingRow = "row" + highlitedRowObjSort;
    index = document.getElementById(deletingRow).rowIndex;
    document.getElementById("cntobjsortscope_list").deleteRow(index);
    highlitedRowObjSort = -1;
  }
}

function removeLoc()
{
  if (highlitedRowLoc > 0)
  {
    deletingRow = "row" + highlitedRowLoc;
    index = document.getElementById(deletingRow).rowIndex;
    document.getElementById("cntlocscope_list").deleteRow(index);
    highlitedRowLoc = -1;
  }
}

function removeAllObj()
{
  document.getElementById("cntobjscope_list").innerHTML = "";
  document.getElementById("objcnt").value = 0;
}

function removeAllObjSort()
{
  document.getElementById("cntobjsortscope_list").innerHTML = "";
  document.getElementById("oscnt").value = 0;
}

function removeAllLoc()
{
  document.getElementById("cntlocscope_list").innerHTML = "";
  document.getElementById("loccnt").value = 0;
}

function addObj()
{
  var object_key_str = new Array();
  var object_text_str = new Array();
  $('#objs :selected').each(function(i, selected)
                            {
                              object_key_str[i] = $(selected).val();
                              object_text_str[i] = $(selected).text();
                            });

  for (var i = 0; i < object_key_str.length; i++)
  {
    if (!itemObjExist( document.getElementById("cntobjscope_list"), object_key_str[i])) // && object_key_str[i] != -1)
    {
      insertObjRow(object_text_str[i], object_key_str[i]);
    }
  }
}

function addObjSort()
{
  var sorts_key_str = new Array();
  var sorts_text_str = new Array();
  $('#srtdeelmulti :selected').each(function(i, selected)
                             {
                               sorts_key_str[i] = $(selected).val();
                               sorts_text_str[i] = $(selected).text();
                             });
  for (var i = 0; i < sorts_key_str.length; i++)
  {
    if (!itemObjSortExist(document.getElementById("cntobjsortscope_list"), sorts_key_str[i]))
    {
      insertObjSortRow(sorts_text_str[i], sorts_key_str[i]);
    }
  }
}

function addLoc()
{
  var level;
  var key_str_arr = new Array();
  var text_arr = new Array();
  var type_arr = new Array();

  if ($('#rooms :selected[value!=-1]').length)     level = 5; // Ruimte
  else if ($('#flrs :selected[value!=-1]').length) level = 4; // Verdieping
  else if ($('#blds :selected[value!=-1]').length) level = 3; // Gebouw & Terrein
  else if ($('#locs :selected[value!=-1]').length) level = 2; // Locatie

  switch (level) {
    case 5: // Ruimte
        $('#rooms :selected[value!=-1]').each(function(i, selected)
                                         {
                                           key_str_arr[i] = $(selected).val();
                                           text_arr[i] = $(selected)[0].getAttribute("text");
                                           type_arr[i] = 'R';
                                         });
        break;
    case 4: // Verdieping
        $('#flrs :selected[value!=-1]').each(function(i, selected)
                                        {
                                          key_str_arr[i] = $(selected).val();
                                          text_arr[i] = $(selected)[0].getAttribute("text");
                                          type_arr[i] = 'V';
                                        });
        break;
    case 3: // Gebouw & Terrein
        $('#blds :selected[value!=-1]').each(function(i, selected)
                                        {
                                          key_str_arr[i] = $(selected).val();
                                          text_arr[i] = $(selected)[0].getAttribute("text");
                                          type_arr[i] = $(selected)[0].getAttribute("bttype");
                                        });
        break;
    case 2: // Locatie
        $('#locs :selected[value!=-1]').each(function(i, selected)
                                              {
                                                key_str_arr[i] = $(selected).val();
                                                text_arr[i] = $(selected).text();
                                                type_arr[i] = 'L';
                                              });
        break;
    default: // Empty
        return false; // Nothing selected
  }
  for (var i = 0; i < key_str_arr.length; i++)
  {
    if (!itemExist(document.getElementById("cntlocscope_list"), key_str_arr[i], type_arr[i]))
    {
        insertLocRow(text_arr[i], key_str_arr[i], type_arr[i]);
    }
  }
}

function itemObjExist(tbl, key)
{
  if (!tbl.rows)
    return true;

  for (var i = 0; i < tbl.rows.length; i++)
  {
    var j = parseInt(tbl.rows[i].id.substr(3), 10) - 1000;
    var objkey = $("#kd" + j).val();
    if (objkey == key)
      return true;
  }
  return false;
}

function itemObjSortExist(tbl, key)
{
  if (!tbl.rows)
    return true;

  for (var i = 0; i < tbl.rows.length; i++)
  {
    var j = parseInt(tbl.rows[i].id.substr(3), 10) - 1000;
    var srtkey = $("#skd" + j).val();
    if (srtkey == key)
      return true;
  }
  return false;
}

function itemExist(tbl, key, type)
{
  if (!tbl.rows)
    return true;

  for (var i = 0; i < tbl.rows.length; i++)
  {
    var j = tbl.rows[i].id.substr(3);
    var rowKey = $("#akd" + j).val();
    var rowType = $("#akt" + j).val();
    if (key == rowKey && type == rowType)
        return true;
  }
  return false;
}

function selectObjRow(rownr)
{
  if (highlitedRowObj > 0)
    $("#row" + highlitedRowObj).removeClass("highlite");
  $("#row" + rownr).addClass("highlite");
  highlitedRowObj = rownr;
}

function selectObjSortRow(rownr)
{
  if (highlitedRowObjSort > 0)
    $("#row" + highlitedRowObjSort).removeClass("highlite");
  $("#row" + rownr).addClass("highlite");
  highlitedRowObjSort = rownr;
}

function selectLocRow(rownr)
{
  if (highlitedRowLoc > 0)
    $("#row" + highlitedRowLoc).removeClass("highlite");
  $("#row" + rownr).addClass("highlite");
  highlitedRowLoc = rownr;
}

function insertObjRow(name, key)
{
  var j = parseInt($("#objcnt").val(), 10) + 1;
  html = "<tr id='row" + (j + 1000) + "' OnClick='javascript:selectObjRow(" + (j + 1000) + ");'>"
       + "<td class=selectable align=left id=obj>" + name + "</td>"
       + "<td><input type=hidden id=k" + j + " name=k" + j + " value=-1>"
       + "<input type=hidden id=kd" + j + " name=kd" + j + " value='" + key  + "'>"
       + "<input type=hidden id=ks" + j + " name=ks" + j + " value='" + name + "'>"
       + "</td></tr>";
  $("#cntobjscope_list").append(html);
  $("#objcnt").val(j);
}

function insertObjSortRow(name, key)
{
  var j = parseInt($("#oscnt").val(), 10) + 1;
  var html = "<tr id='row" + (j + 1000) + "' OnClick='javascript:selectObjSortRow(" + (j + 1000) + ");'>"
           + "<td class=selectable align=left id=obsort>" + name + "</td>"
           + "<td><input type=hidden id=sk" + j + " name=sk" + j + " value=-1>"
           + "<input type=hidden id=skd" + j + " name=skd" + j + " value='" + key  + "'>"
           + "<input type=hidden id=sks" + j + " name=sks" + j + " value='" + name + "'>"
           + "</td></tr>";
  $("#cntobjsortscope_list").append(html);
  $("#oscnt").val(j);
}

function insertLocRow(name, key, type)
{
  var j = parseInt($("#loccnt").val(), 10) + 1;
  var html = "<tr id='row" + j+ "' OnClick='javascript:selectLocRow(" + j + ");'>"
           + "<td class='selectable' align='left' id='loc'>" + name + "</td>"
           + "<td class='selectable'>"
           + "<input type='text' class='fldshort' size='10' maxlength='12' id='akn" + j + "' name='akn" + j + "' onBlur='checkWeight(event);'>"
           + "<input type='hidden' id='ak"  + j + "' name='ak"  + j + "' value='-1'>"
           + "<input type='hidden' id='akd" + j + "' name='akd" + j + "' value='" + key  + "'>"
           + "<input type='hidden' id='aks" + j + "' name='aks" + j + "' value='" + name + "'>"
           + "<input type='hidden' id='akt" + j + "' name='akt" + j + "' value='" + type + "'>"
           + "</td></tr>";
  $("#cntlocscope_list").append(html);
  $("#loccnt").val(j);
}

function checkWeight(evt)
{
  evt = evt || window.event;
  var obj = evt.srcElement || evt.target;
  var ival = parseInt(obj.value,10);
  var retVal = false;
  if (( !isNaN(ival) && Math.abs(ival) < 1000000000) || obj.value =="")
    retVal = true;
  validateField(obj, retVal, L("lcl_cnt_invalid_kenmerk_value"));
  return retVal;
}

function RowData(cokey, sdkey)
{
  this.cokey = cokey;
  this.sdkey = sdkey; // soortdeel
}

function RowDataLoc(cpkey, lkey)
{
  this.cpkey = cpkey;
  this.lkey = lkey;
}

function onChangeDiscipline()
{
  sgSrtgroep.setValue(-1, "", true, false, null, true);
  sgSrtgroep.CheckJustOne();
  sgSrtdeel.setValue(-1, "", true, false, null, true);
  sgSrtdeel.CheckJustOne();
  $("#desc").val("");
  updateRoomObj();
}
function onChangeSrtgroep(srtgroep_key)
{ // Zet de discipline indien niet ingevuld i.v.m. de afhankelijkheid van de suggestvelden.
  if (srtgroep_key > 0 && $("#disc").val() <= 0 && typeof sgDisc != "undefined")
  {
    $.getJSON("../Shared/get_ins_info.asp",
              { srtgroep_key: srtgroep_key },
                callback_ins_info);
  }
  sgSrtdeel.setValue(-1, "", true, false, null, true);
  sgSrtdeel.CheckJustOne();
  $("#desc").val("");
  updateRoomObj();
}
function onChangeSrtdeel(srtdeel_key)
{
  if (srtdeel_key > 0 && $("#srtgroep").val() <= 0 && typeof sgSrtgroep != "undefined")
  {
    $.getJSON("../Shared/get_ins_info.asp",
              { srtdeel_key: srtdeel_key },
                callback_ins_info);
  }
  $("#desc").val("");
  updateRoomObj();
}
function callback_ins_info(data, textStatus, jqXHR)
{ // Zet de discipline indien niet ingevuld
  // setValue(key, txt, doonChange, checkExist, extraParam, lastTry)
  if ($("#disc").val() == -1)
  {
    sgDisc.setValue(data.disc_key, data.disc_omschr, false /*doonChange*/, true /*checkExist*/);
  }
  if ($("#srtgroep").val() == -1)
    sgSrtgroep.setValue(data.srtgroep_key, data.srtgroep_omschr, false /*doonChange*/, true /*checkExist*/);
}
