<% /*
     $Revision$
     $Id$

    File:               INS/ins_list.inc
    Description:        Show an overview of objects in list-form.
                        which meets with the given requirements
                        User can select on or more lines and edit/delete them
                        FE ->verbruiksregistratie
                        BO ->object registratie
                        FO ->uitleenmodule

    Parameters:
        urole           user role (fe, fo, bo, mi)
        outputmode      behave in an output mode, print to 0 = screen, 1 = printer, 2 = excel, etc.
        showall         show all objects which meets with the given requirements
        inspect         Toon ook inspectie kolommen (implies actief=1)
        inspClosed      search for objects inspections wich are verwerkt
        inspDone        search for objects inspections wich are done
        inspBusy        search for objects inspections wich are in progress
        inspSoon        search for objects inspections wich are soon
        inspClosed, inspDone, inspBusy, inspSoon: de vinkjes
        inspsoonfrom    search for objects with inspections between inspsoonfrom and inspsoonto
        inspsoonto      search for objects with inspections between inspsoonfrom and inspsoonto
        donedatefrom    search for objects with inspections between donedatefrom and donedateto
        donedateto      search for objects with inspections between donedatefrom and donedateto
        reg_key         search for objects with the given regio key
        dist_key        search for objects with the given district key
        loc_key         search for objects with the given location key
        bld_key         search for objects with the given building key
        flr_key         search for objects with the given floor key
        room_key        search for objects with the given room key
        wpl_key         search for objects with the given workplace key
        deel            search for objects with the given identification
        disc_key        search for objects with the given discipline key
        insgroup_key    search for objects with the given groep key (srtgroup key)
        objsrt_key      search for objects with the given objectsoort (srtdeel key) as intArray
        objsrt_oms      search for srtobjects with the given code or description
        groep           search for group with the given code or description
        dep_key         search for objects with the given department key
        persoon_key     search for objects with the given persoon key
        beh_key         search for objects manaed by the given beh (persoon) key
        cpersoon_key    search for objects with the given contactpersoon key
        cnt_bedrijf_key search for objects waar het desbetreffende bedrijf contractueel onderhoud kan doen
        ins_key_arr     search for objects with the given ins key array
        parent_key      search for subobjects of the given ins parent_key
        koppel_key      search for related objects of the given koppel_key
        terr_key        search for objects with the given terrein key
        room_key_arr    search for objects with the given room keys (room key array)
        comp_key        search for objects with the given companie key
        insObjIncl      search also for objects wich is a part from another object
        insLentOut      search for objects wich are lent out
        insAvail        search for objects wich are available
        insSuccessY     search for inspections which are a success
        insSuccessN     search for inspections which are not active
        fgraph          search for objects for a fgraph search
    Context:            - INS/ins_search.asp (Search action from bes_search.asp form)
                        - FGraph (<cust>_Report.asp)
                        - Self (when printing)
    Note:               For FGraph-selectable objects 'owner' selection is never applicable
                        as the objects will be place-bound
                        Als parent_key of koppel_key, dan worden geen bulkacties getoond (tiny)

*/ %>

<!-- #include file="../Shared/json2.js" -->
<!-- #include file="../Shared/resultset_table_v2.inc" -->
<!-- #include file="./ins.inc" -->

<%
FCLTHeader.Requires({ plugins:["jQuery", "suggest"],
                      js: ["jquery-ui.js", "../ins/ins_list.js", "num2curr.js"]
                    });
function ins_list (pautfunction, params)
{
 var buttons = [];
  // De functie checkAutorisation(autfunction) geeft een Response.End indien er geen autorisatie voor autfunction wordt gevonden
  var authparams = user.checkAutorisation(pautfunction);
  var authparamsINSMAN = user.checkAutorisation("WEB_INSMAN", true);
  var hasWriteINSMAN = (authparamsINSMAN && authparamsINSMAN.ALGwritelevel < 9 && authparamsINSMAN.PRSwritelevel < 9)

  var urole = params.urole;
  var fronto = (urole == "fo");
  var backo = (urole == "bo");
  var minfo = (urole == "mi"); // NOT APPLICABLE?
  var frontend = (urole == "fe" || (!fronto & !backo & !minfo));

  var canAdd = (authparams.PRSwritelevel < 9 && urole != "fo");

  // Voor resulttable de globalen zetten; zou ng anders moeten.
  var outputmode = params.outputmode; // print to 0 = screen, 1 = printer, 2 = excel, etc.
  var print = (outputmode == 1 || outputmode == 5);
  var excel = (outputmode == 2 || outputmode == 6);
  var showall = params.showall;

  var reg_key = params.reg_key;
  var dist_key = params.dist_key;
  var loc_key = params.loc_key;
  var disc_key = params.disc_key;
  var insgroup_key = params.insgroup_key;
  var objsrt_key = params.objsrt_key;
  var ctrdisc_key = params.ctrdisc_key;
  var dep_key = params.dep_key;
  var persoon_key = params.persoon_key;
  var cpersoon_key = params.cpersoon_key;
  var fgraph = params.fgraph;
  var parent_key = params.parent_key;
  var koppel_key = params.koppel_key;
  var embedded = params.embedded;
  var tiny = params.tiny || parent_key || koppel_key;
  var inspect = params.inspect;
  var inacObjIncl = params.inacObjIncl;
  var inspDone = params.inspDone;
%>

  <html>
    <head>
<%
      FCLTHeader.Generate({ outputmode: outputmode });
%>
    <script type="text/javascript">
     var urole = "<%=urole%>";
        function ins_deelkoppeling()
        {
          FcltMgr.openModalDetail("../ins/ins_deelkoppeling.asp?urole=<%=urole%>&ins_keys=<%=koppel_key%>",
                                  L("lcl_ins_koppelobjects"),
                                  { callback: FcltMgr.reload });
        }
     </script>
    </head>
    <body id="listbody">

<%
      if (frontend)
      { %>
        <form action="ins_search_list.asp" method="get" id="inslist" name="inslist">
          <input type="hidden" name="urole" value="<%=urole%>">
          <% /* filter velden voor frontend. Nodig voor reload na oplaan nieuw waarden. */ %>
          <input type="hidden" name="locatiekey" value="<%=loc_key%>">
          <input type="hidden" name="srtdeel" value="<%=objsrt_key%>">
<%
          var sql_loc = "";
          var sql_obj_sort = "";

          if (loc_key)
          {
            sql_loc = " AND l.alg_locatie_key = " + loc_key;
          }
          else if (dist_key)
          {
            sql_loc = " AND l.alg_district_key = " + dist_key;
          }
          else if (reg_key)
          {
            sql_loc = " AND di.alg_regio_key = " + reg_key;
          }
          else
          {
            // Note: we do not support alg-scope  per discipline (yet)
            sql_loc = (authparams.ALGreadlevel >= 0
                      ? " AND d.ins_alg_locatie_key IN"
                        + " (SELECT alg_locatie_key FROM fac_v_my_locations"
                        + " WHERE prs_perslid_key = " + user_key
                        + " AND niveau = " + authparams.ALGreadlevel + ")"
                      : "");
          }

          if (objsrt_key)
          {
            sql_obj_sort = " AND sk.INS_SRTDEEL_KEY IN (" + objsrt_key.join(",") + ")";
          }
          else
          {
            sql_obj_sort = " AND sk.ins_discipline_key IN (SELECT gb.ins_discipline_key"
                         + "   FROM fac_v_webgebruiker gb, fac_functie f"
                         + "  WHERE prs_perslid_key = " + user_key
                         + "    AND fac_functie_code = " + safe.quoted_sql(pautfunction)
                         + "    AND f.fac_functie_key = gb.fac_functie_key"
                         + "    and gb.fac_gebruiker_alg_level_read < 9)";
          }

          sql = " SELECT "+lcl.xsqla('sd.ins_srtdeel_omschrijving', 'sd.ins_srtdeel_key')
              + ", d.ins_deel_omschrijving || ' (' || d.ins_deel_key || ')' object_omschrijving" // object omschrijving
              + ", d.ins_deel_opmerking"
              + ", (SELECT akd.ins_kenmerkdeel_aanmaak"
                + " FROM ins_v_aanwezigkenmerkdeel akd"
                + " WHERE akd.ins_deel_key = d.ins_deel_key"
                + " AND akd.ins_kenmerk_key = sk.ins_kenmerk_key) last_change_date" // vorige invoerdatum
              + ", (SELECT akd.ins_kenmerkdeel_waarde"
                + " FROM ins_v_aanwezigkenmerkdeel akd"
                + " WHERE akd.ins_deel_key = d.ins_deel_key"
                + " AND akd.ins_kenmerk_key = sk.ins_kenmerk_key) last_value"       // huidige (laatste) waarde
              + ", sk.ins_srtdeel_key"                                              // objectsoort deel key
              + ", d.ins_deel_key"                                                  // onderdeel key
              + ", sk.ins_kenmerk_key"                                              // objectkenmerk key
              + ", d.ins_alg_ruimte_key"                                            // alg ruimte key
              + ", sk.ins_srtkenmerk_key"                                           // bibliotheek kenmerk key
              + ", sk.ins_srtkenmerk_kenmerktype"                                   // bibliotheek type
              + ", sk.ins_srtkenmerk_lengte"                                        // bibliotheek lengte
              + ", sk.ins_srtkenmerk_nmin"                                          // bibliotheek maximum waarde
              + ", sk.ins_srtkenmerk_nmax"                                          // bibliotheek minimum waarde
              + ", l.alg_locatie_omschrijving"                                      // locatie omschrijving
              + ", "+lcl.xsqla('sd.ins_srtdeel_eenheid', 'sd.ins_srtdeel_key')      // eenheid van het verbruik
              + ", sk.ins_kenmerk_volgnummer"                                       // kenmerk volgnummer
              + ", COALESCE("
                + " (SELECT akd.ins_kenmerkdeel_key"
                + " FROM ins_v_aanwezigkenmerkdeel akd"
                + " WHERE akd.ins_deel_key = d.ins_deel_key"
                + " AND akd.ins_kenmerk_key = sk.ins_kenmerk_key)"
                + ", -1) ins_kenmerkdeel_key"                                       // ins_kenmerkdeel_key
              + ", rd.res_deel_key"
              + ", rd.res_deel_opmerking"
              + " FROM ins_v_srtdeel_kenmerk sk"
              + ", ins_v_aanwezigdeel d"
              + ", ins_srtdeel sd"
              + ", alg_locatie l"
              + (!loc_key && !dist_key && reg_key
                ? ", alg_district di"
                : "")
              + ", (SELECT res_deel_key"
              + "        , res_ins_deel_key"
              + "        , " + lcl.xsqla('res_deel_opmerking', 'res_deel_key')
              + "    FROM res_deel"
              + "   WHERE res_deel_verwijder IS NULL"
              + "     AND res_deel_vervaldatum IS NULL"
              + "   UNION ALL"
              + "   SELECT res_deel_key"
              + "        , res_ins_deel_key"
              + "        , " + lcl.xsqla('res_deel_opmerking', 'res_deel_key')
              + "    FROM res_deel"
              + "   WHERE res_deel_verwijder IS NULL"
              + "     AND res_deel_vervaldatum > SYSDATE) rd"
              + " WHERE sk.ins_srtdeel_key = sd.ins_srtdeel_key"
              + " AND d.ins_srtdeel_key = sd.ins_srtdeel_key"
              + " AND d.ins_alg_locatie_key = l.alg_locatie_key"
              + (!loc_key && !dist_key && reg_key
                ? " AND l.alg_district_key = di.alg_district_key"
                : "")
              + " AND d.ins_deel_key =  rd.res_ins_deel_key(+)"
              + " AND sd.ins_srtgroep_key NOT IN (" + S("sle_ins_srt_groep_key") + ", " + S("cil_ins_srt_groep_key") + ")"
              + sql_loc
              + sql_obj_sort
              + " AND sk.ins_kenmerk_meetwaarde = 1"
              + " AND sk.ins_srtkenmerk_kenmerktype = 'N'"
              + " AND (d.ins_deel_vervaldatum IS NULL OR d.ins_deel_vervaldatum > TRUNC(SYSDATE))"
              + " ORDER BY alg_locatie_omschrijving"            // overweeg uppers?
              + ", "+lcl.xsql('sd.ins_srtdeel_omschrijving', 'sd.ins_srtdeel_key')
              + ", d.ins_deel_omschrijving || ' (' || d.ins_deel_key || ')'"
              + ", "+ lcl.xsql('sd.ins_srtdeel_eenheid','sd.ins_srtdeel_key');

          /****************************************
          * Callback functies ResultsetTable for FE
          ****************************************/

          function fnrowDataFE(oRs)
          {
            var insDeelKey = oRs("ins_deel_key").value;
            var insDeelDescr = oRs("object_omschrijving").value;
            var insKenmerkDeelKey = oRs("ins_kenmerkdeel_key").value;
            var insKenmerkKey = oRs("ins_kenmerk_key").value;

            var data = {insDeelKey:insDeelKey, insDeelDescr:insDeelDescr, insKenmerkDeelKey:insKenmerkDeelKey, insKenmerkKey:insKenmerkKey};
            return JSON.stringify(data);
          }

          function fnInput(oRs)
          { // input nieuwe waarde d.m.v. input box
            newInput = "<NOBR>"

            var write_ok
            if (authparams.ALGwritelevel >= 0)
            {
              sql2 = "SELECT alg_ruimte_key FROM fac_v_my_rooms"
                   + " WHERE prs_perslid_key = " + user_key
                   + " AND niveau = " + authparams.ALGwritelevel
                   + " AND alg_ruimte_key = " + oRs("ins_alg_ruimte_key").value;
              oRs2 = Oracle.Execute(sql2);
              if (!oRs2.eof)
                write_ok = true;
              else
                write_ok = false;
            }
            else
            {
              write_ok = true;
            }

            newInput += '<input type="text" maxlength="10" style="width:100;text-align:right"'
                      + ' onBlur="checkInput(event);" onKeyPress="return checkEnter(event);"'
                      + ' id="cnt' + rst.rowNum + '" name="cnt' + rst.rowNum + '" value=""'
                      + ' value1="' + oRs("ins_srtkenmerk_kenmerktype").value + '"'
                      + ' value2="' + oRs("ins_srtkenmerk_lengte").value + '"'
                      + ' value3="' + oRs("ins_srtkenmerk_nmin").value + '"'
                      + ' value4="' + oRs("ins_srtkenmerk_nmax").value + '"'
                      + (!write_ok || oRs("ins_srtkenmerk_kenmerktype").value != 'N'
                        ? ' readonly'
                        : '')
                      + '>'
                      + '<input type="hidden" id="last_val' + rst.rowNum + '" name="last_val' + rst.rowNum + '" value="' + (oRs("last_value").value? oRs("last_value").value : 0) + '">'
                      + '<input type="hidden" id="deel_key' + rst.rowNum + '" name="deel_key' + rst.rowNum + '" value="' + oRs("ins_deel_key").value + '">'
                      + '<input type="hidden" id="kenmerk_key' + rst.rowNum + '" name="kenmerk_key' + rst.rowNum + '" value="' + oRs("ins_kenmerk_key").value + '">';

            return newInput;
          }

          /*********************************************
           * End callback functies ResultsetTable for FE
           ********************************************/
          var rst = new ResultsetTable({ keyColumn: "ins_deel_key",
                                         sql: sql,
                                         ID: "instable",
                                         //rowClass: fnrowClass,
                                         rowData: fnrowDataFE,
                                         filterParams: params,
                                         outputmode: outputmode,
                                         title: L("lcl_ins_objects"),
                                         showAll: showall
                                       });

          rst.addColumn(new Column({caption: L("lcl_location"), content: "alg_locatie_omschrijving"}));
          rst.addColumn(new Column({caption: L("lcl_obj_sort"), content: "ins_srtdeel_omschrijving"}));
          rst.addColumn(new Column({caption: L("lcl_obj_inf_name"), content: "object_omschrijving"}));
          rst.addColumn(new Column({caption: L("lcl_last_date"), content: "last_change_date", datatype: "date"}));
          rst.addColumn(new Column({caption: L("lcl_last_value"), content: "last_value"}));
          rst.addColumn(new Column({caption: L("lcl_obj_cons_value"), content: fnInput}));
          rst.addColumn(new Column({caption: L("lcl_obj_unit"), content: "ins_srtdeel_eenheid"}));

          // Acties
          if (!embedded) {
              rst.addAction({action: "insHistory", caption: L("lcl_history")});
              rst.addAction({action: "insSave", caption: L("lcl_save_value"), multi: true, multiOnce: true});
          }
          var count = rst.processResultset();
%>
          <input type='hidden' id='count' name='count' value='<%=count%>'>
        </form>
<%
      }
      else
      { // !frontend
        if (!excel)
        {
%>        <script type="text/javascript">

            function openFG(evt, insKey, room, INS_ALG_RUIMTE_TYPE, pxyknown)
            {
              FcltMgr.stopPropagation(evt);
<%            if (S("ins_fg_remote_maps") != "")
              { %>
                if (pxyknown == 1)
                {
                  fwnd = window.open('../cad/ShowGoogleMap.asp?obj_key=' + insKey, 'FGShow',
                                     "width=640, height=480, directories=no, location=no, menubar=no,"
                                   + "resizable=yes, status=no, titlebar=yes, toolbar=no");
                  fwnd.focus()
                  return;
                }
<%            } %>
              if (INS_ALG_RUIMTE_TYPE == 'T')
              {
                var url = '../cad/ShowTerrain.asp?tKey=' + (room||-1) + '&obj_key=' + insKey;
                FcltMgr.openModalDetail(url);
              }
              else
              {
                var url = '../cad/ShowRoom.asp?rKey=' + (room||-1) + '&ins_key='+insKey;
                FcltMgr.openModalDetail(url);
              }
            }
          </script>
<%
        } // !excel
%>
<%      // =======================================================
        // All header information been emitted. Now start building
        // the SQL-queries to do actual data retrieval
        // =======================================================

        var ErisUitleenbaar = false;
        var ErisReserveerbaar = false;

        var hasDrawings = false;

        var sqlu ="SELECT COUNT (*) FROM ins_srtdeel WHERE ins_srtdeel_uitleenbaar = 1 AND ins_srtdeel_verwijder IS NULL";
        var oRsu = Oracle.Execute(sqlu);
        ErisUitleenbaar = oRsu(0).value >0
        oRsu.close();
        sqlu ="SELECT COUNT (*) FROM res_deel WHERE res_deel_verwijder IS NULL";
        oRsu = Oracle.Execute(sqlu);
        ErisReserveerbaar = oRsu(0).value >0
        oRsu.close();

        var sqlu = "SELECT   1"
                 + " FROM   cad_tekening"
                 + " WHERE   cad_tekening_verwijder IS NULL AND ROWNUM = 1";
        oRsu = Oracle.Execute(sqlu);
        hasDrawings = !oRsu.eof;
        oRsu.close();

        // Start building the query to fetch all objects satisfying
        var sql = ins.getobjectinspect_sql(pautfunction, params);
        // ========== now 'sql' holds the main SQL-statement to fetch all object info

        ///////////////////////////////////////////////////////////
        //
        //      Now let's present the results:
        //
        //////////////////////////////////////////////////////////

        /***********************************************
         * Callback functies ResultsetTable for FO en BO
         **********************************************/

        function fnrowData(oRs)
        {
          var insKey = oRs("ins_deel_key").Value;
          var insTypeKey = oRs("ins_srtdeel_key").Value;
          var insAvailable = oRs("ins_alg_ruimte_key_org").Value == null? 1 : 0;
          var insSrtControleKey = inspect? oRs("ins_srtcontrole_key").Value : -2;

          // Als de status Verwerkt(6) is dan kan/moet er weer een nieuw inspectie gestart worden. Dan geen ins_deelsrtcontrole_key meegegeven (-2).
          var istatus = inspect? oRs("ins_deelsrtcontrole_status").Value : -1;
          var insDeelSrtContrKey = inspect && oRs("ins_deelsrtcontrole_key").Value != null && istatus != 6? oRs("ins_deelsrtcontrole_key").Value : -2;

          var data = {insKey: insKey, insTypeKey: insTypeKey, insAvailable: insAvailable,
                      insSrtControleKey: insSrtControleKey, insDeelSrtContrKey: insDeelSrtContrKey,
                      ins_status: istatus};
          return JSON.stringify(data);
        }

        function fnrowActionEnabler(oRs)
        {
          var eLendOut = false;
          var eReceive = false;
          var eAdapt = false;
          if (fronto)
          {
            eLendOut = oRs("ins_alg_ruimte_key_org").value == null;
            eReceive = !eLendOut;
            eAdapt = eReceive && (oRs("bewerkbaar").Value == 1);
          }
          var eDelete = false;
          var eEdit = true; // Indien enigste actie dan wordt de actie niet getoond en is het de default actie op de hele regel
          var eDetails = true; // Ik zie alleen objecten waar ik read rechten (3d) op heb. Dan mag ik ze ook verder inzien.
          var eShowInsp = false;
          var ePlan = false;
          var eStart = false;
          var eClose = false;
          var eFinish = false;
          if (inspect && !inspDone)
          {
            // Als object is vervallen dan kun je niet meer inspecteren en uitstellen.
            var this_ins = ins.func_enabled_deel(oRs("ins_deel_key").Value,
                                                 {srtcont_key: oRs("ins_srtcontrole_key").Value,
                                                  deelsrtcont_key: oRs("ins_deelsrtcontrole_key").Value
                                                 });
            var istatus = oRs("ins_deelsrtcontrole_status").Value;

            eShowInsp = this_ins.canInspShow && istatus < 6; // Als de inspectie is afgerond dan kun moet je eerst een nieuwe inspectie starten. Alleen lopende inspecties kun je inkijken.
            ePlan = this_ins.canInspPlan;
            eStart = this_ins.canInspStart;
            eClose = this_ins.canInspClose;
            eFinish = !this_ins.canInspClose && this_ins.canInspFinish; // Als er nog niet gereed gemeld/afgemeld is dan wordt die butten wel getoond.
          }

          var data = {eLendOut: eLendOut, eReceive: eReceive, eAdapt: eAdapt, eDelete: eDelete, eEdit: eEdit,
                      eDetails: eDetails, eShowInsp: eShowInsp, ePlan: ePlan, eStart: eStart, eClose: eClose, eFinish: eFinish};
          return data;
        }

        function fnrowClass(oRs)
        {
          var lclass = "";
          var istatus = oRs("ins_deelsrtcontrole_status").Value != null? oRs("ins_deelsrtcontrole_status").Value : -1;

          if (inspDone) return lclass;
          var ins_deelsrtcontrole_plandatum = oRs("ins_deelsrtcontrole_plandatum").Value;
          if (ins_deelsrtcontrole_plandatum == null)
            var dt = new Date(oRs("inspectie_next").Value);
          else
            var dt = new Date(oRs("ins_deelsrtcontrole_plandatum").Value);
          dt.setHours(0,0,0,0);     // trunc datum
          var dtsoon = new Date;
          dtsoon.setDate(dtsoon.getDate() + S("ins_inspect_soon_days"));
          dtsoon.setHours(0,0,0,0);     // trunc datum
          var dtlate = new Date(new Date().setHours(0,0,0,0));

          // Als het een eerste controle(1) is, dan staat "Onbekend/Undetermined" in beeld. Dan ook rood weergeven.
          var nonext = oRs("nonext").Value == 1;
          var ctr_controle_type = oRs("ctr_controle_type").Value;
          var undetermined = (nonext && ctr_controle_type == 1); // Eerste Controle(1).

          if (dt >= dtsoon && !undetermined)
              return lclass; // meer dan S("ins_inspect_soon_days") dagen in de toekomst

          if (dt >= dtlate && !undetermined)
              return lclass + " expired1"; // Binnenkort

          return lclass + " expired2"; // Te laat
        }

        function fnStatus(oRs)
        {
            var stat = oRs("ins_deelsrtcontrole_status").Value;
            if (!(stat>0) || stat == 6) // De status gaat over de vorige/lopende inspectie. Bij afgerond is dat niet boeiend
                return "";
            return ins.getinspectstatustext(oRs("ins_deelsrtcontrole_status").Value);
        }

        function fnPlace(oRs)
        {
          var place = ""
          if (oRs("ins_alg_ruimte_type_org").value != null)
            place = oRs("uitgegeven_vanuit");
          else
            if (oRs("ins_alg_ruimte_type").value == 'P' || oRs("ins_alg_ruimte_type").value == 'A')
              // Object niet uitgeleend. Uitgeleend aan is eigenlijk de plaats.
              place = oRs("uitgeleend_aan").value;
            else
              place = oRs("plaats").value;

          return safe.html(place);
        }

        function fnLentOutTo(oRs)
        {
          var lentOutTo
          if (oRs("ins_alg_ruimte_type_org").value != null)
            lentOutTo = oRs("uitgeleend_aan").value;
          else
            lentOutTo = "";

          return safe.html(lentOutTo);
        }

        function fnPosition(oRs)
        {
          var rkey = oRs("alg_ruimte_key").value;
          var rtype = oRs("ins_alg_ruimte_type").value;
          if (rtype == "A" || rtype == "P")
          { // Misschien is het uitgeleend en komt het wel uit een ruimte
            rkey = oRs("ins_alg_ruimte_key_org").value;
            rtype = oRs("ins_alg_ruimte_type_org").value;
          }
          if (rtype == null || rtype == "A" || rtype == "P")
            return ""; // Kunnen we niet tonen

          // TODO: beide kan natuurlijk ook nog/
          var xyavailable = (oRs("ins_deel_x").value != null? 1 : 0);
          var dwgxyavailable = (oRs("ins_deel_dwgx").value != null? 1 : 0);

          if (rtype == "W")
          {
            var sql = "SELECT prs_alg_ruimte_key, prs_werkplek_dwgx FROM prs_werkplek WHERE prs_werkplek_key = " + rkey;
            var oRs2 = Oracle.Execute(sql);
            var rkey = oRs2("prs_alg_ruimte_key").Value;
            var xyavailable = false;
            var dwgxyavailable = (oRs2("prs_werkplek_dwgx").value != null? 1 : 0);
            oRs2.Close();
            rtype = "R";
          }

          var position = "";
          if (xyavailable || dwgxyavailable) {
              if (outputmode == 0) {
                  position = '<span class="'+(xyavailable? 'fa fa-fw fa-globe fa-2x' : 'fa fa-fw fa-map-marker fa-2xs')+'" style="font-size: 1.3em" onclick="openFG(event, ' + oRs("ins_deel_key").value + ', ' + rkey + ', \'' + rtype + '\', ' + xyavailable + ');">'
                           + '</span>';
              } else {
                  position = (xyavailable? "M" : "FG");

              }
          } else {
              if (outputmode == 0) {
                  position = '<span class="fa fa-fw fa-map-marker fa-2x" style="font-size: 1.3em" onclick="openFG(event, ' + oRs("ins_deel_key").value + ', ' + rkey + ', \'' + rtype + '\');">'
                           + '</span>';
              }
          }

          return position;
        }

        function fnKoppelvan(oRs)
        {
            if (oRs("ins_deelkoppeling_naar_key").Value == koppel_key)
                return safe.html(oRs("ins_deel_omschrijving").Value)
                       + (oRs("ins_deel_opmerking").Value? " (" + safe.html(oRs("ins_deel_opmerking").Value) + ")" : "");
            else
                return "";
        }
        function fnKoppelaan(oRs)
        {
            if (oRs("ins_deelkoppeling_van_key").Value == koppel_key)
                return safe.html(oRs("ins_deel_omschrijving").Value)
                       + (oRs("ins_deel_opmerking").Value? " (" + safe.html(oRs("ins_deel_opmerking").Value) + ")" : "");
            else
                return "";
        }
        function fnReserveerbaar(oRs) {
            var res = "";
            if ( oRs("res_deel_key").value != null )
            {
                if (outputmode == 0 ) {
                    res= "<span";
                    if (oRs("res_deel_opmerking").value != null )
                        res += " title='" + safe.htmlattr(oRs("res_deel_opmerking").value) + "' ";
                    res += ">"+L("lcl_obj_reserveerbaar")+"</span>";
                }
                else
                    res = L("lcl_yes");
            } else {
                res = (outputmode == 0 ? "" : L("lcl_no"));
            }
            return res;
        }
        function fnUitleenbaar(oRs) {
            var res = "";
            if ( oRs("ins_srtdeel_uitleenbaar").value==1 ) {
                res = (outputmode == 0 ? L("lcl_obj_uitleensrtdeel") : L("lcl_yes"));
            } else {
                res = (outputmode == 0 ? "" : L("lcl_no"));
            }
            return res;
        }


        function fnInspectie(oRs) // TODO: Of via RowClass
        {
            var vervallen = (oRs("inspectie_eind").Value != null && new Date(oRs("inspectie_eind").Value).getTime() < new Date().midnight());
            if (vervallen) return L("lcl_ins_controle_vervallen");

            var txt;
            var dt;
            var nonext = oRs("nonext").Value == 1;
            if (nonext)
            { // Er is nog geen inspectie geweest. Eerste controle moet nog plaatsvinden.
              // 1: Controle, 2: Vervanging, 3: Certificering.
              if (oRs("ins_srtcontroledl_xcp_startdat").Value != null)
              {
                dt = new Date(oRs("ins_srtcontroledl_xcp_startdat").Value); // Startdatum.
                txt = (oRs("inspectie_eind").Value == 0? toDateTimeString(dt) : toDateString(dt));
              }
              else
              {
                switch (oRs("ctr_controle_type").Value)
                {
                  case 1:   { txt = L("lcl_ins_controle_first"); break; }    // Eerste controle.
                  case 2:
                  case 3:   { dt = new Date(oRs("inspectie_next").Value);    // Registratiedatum.
                              txt = (oRs("inspectie_eind").Value == 0? toDateTimeString(dt) : toDateString(dt));
                              break;
                            } // Eerste certificering.
                }
              }
              return txt;
            }

            var inspectie = (inspDone? oRs("inspectie_date").Value : oRs("inspectie_next").Value);

            var inspectie_eenheid = oRs("inspectie_eenheid").Value;
            if (inspectie_eenheid == 0)
              var dttxt = toDateTimeString(inspectie);
            else
              var dttxt = toDateString(inspectie);

            return "<span style='white-space: nowrap'>"+dttxt+"</span>";
        }

        function fnPlandatum(oRs)
        {
          var vervallen = (oRs("inspectie_eind").Value != null && new Date(oRs("inspectie_eind").Value).getTime() < new Date().midnight());
          if (vervallen) return L("lcl_ins_controle_vervallen");

          var plandatum = oRs("ins_deelsrtcontrole_plandatum").Value;

          var inspectie_eenheid = oRs("inspectie_eenheid").Value;
          if (inspectie_eenheid == 0)
            var dttxt = toDateTimeString(plandatum);
          else
            var dttxt = toDateString(plandatum);

          return "<span style='white-space: nowrap'>"+dttxt+"</span>";
        }

        function fnCMSuccess(oRs)
        {
          var res = "";
          if (oRs("ins_controlemode_success").Value == null)
            res = '<span class="fa fa-fw fa-exclamation-triangle fa-lg"></span>';
          else
            res = '<span class="fa fa-fw fa-check fa-lg"></span>';
          return res;
        }

        function fnActief(oRs)
        {
          var res = "";
          if (oRs("ins_deel_actief").Value == 1)
            res = L("lcl_ins_active");
          else
            res = L("lcl_ins_not_active");

          return res;
        }

        if (koppel_key && ins.func_enabled_deel(koppel_key).canChange)  // TODO (popup met objectselector (zoiets als bij meldingen?)
        {
            buttons = [{ icon: "wijzigen.png",
                           title: L("lcl_change"),
                           action: "ins_deelkoppeling()"
                          }
                        ];
        }
        else if (canAdd)
        {
          var addurl = "";
          if (parent_key)
          {
            var addurl = "appl/ins/ins_deel.asp?urole=" + urole + "&parent_key=" + parent_key;
          }
          else
          {
            // Er zijn nogal wat varianten van parameter name bij INS dus moeten wel in
            // het paramsobject wat vertalingen doen.
            var transitParam = buildTransitParam(["disc", "Group", "sort", "dept", "prs_key",
                                                  "locatiekey", "gebouwkey", "verdiepingkey", "ruimtekey", "werkplekkey"],
                                      { disc: disc_key, Group: insgroup_key, sort:objsrt_key, dept: dep_key, prs_key: persoon_key});
            var addurl = "appl/ins/ins_deel.asp?urole=" + urole + transitParam;
          }
          buttons.push({ icon: "page_refresh.png", title: L("lcl_refresh"), action: "FcltMgr.reload()" });
          buttons.push({ icon: "plus.png", title: L("lcl_add"), action: "FcltMgr.openDetail('" + addurl + "', '" + L("lcl_add") + "')" });
        }

        if (embedded && authparams.PRSwritelevel < 9 && fronto && (cpersoon_key > 0 || persoon_key > 0))
        {
          if (cpersoon_key > 0)
          { // Contactpersoon moet eerst binnengemeld zijn/worden alvorens een object toegekend kan worden.
            sql2 = "SELECT COUNT(b.prs_contactpersoon_key) aantal"
                + "  FROM bez_bezoekers b"
                + " WHERE b.prs_contactpersoon_key = " + cpersoon_key
                + "   AND b.bez_bezoekers_done IS NOT NULL"
                + "   AND b.bez_bezoekers_out IS NULL"
            var oRs2 = Oracle.Execute(sql2);
            var isbinnen = oRs2("aantal").value > 0;
          }
          else // (persoon_key > 0): Intern persoon kan altijd een object toegekend krijgen.
            isbinnen = true;

          if (isbinnen)  // ja, deze overschrijft het array
          {
            buttons = [{ icon: "page_refresh.png", title: L("lcl_refresh"), action: "FcltMgr.reload()" },
                       { icon: "plus.png", title: L("lcl_add"), action: "insCheckOutNewItem(" + (cpersoon_key > 0? cpersoon_key + ", 'C'" : persoon_key + ", 'P'") + ")" }
                      ];
          }
        }
        if (inspect) {
            buttons.push({ icon: "legenda.png",  title: L("lcl_mld_legenda"), action: "openLegenda()" });
        }
        /***************************************************
         * End callback functies ResultsetTable for FO en BO
         **************************************************/

        // TODO conditionele Add button
        var rst = new ResultsetTable({ keyColumn: "ins_deel_key",
                                       sql: sql,
                                       ID: "instable",
                                       rowData: fnrowData,
                                       rowActionEnabler: fnrowActionEnabler,
                                       rowClass: inspect? fnrowClass : null,
                                       flexModule: "INS",
                                       flexId: "ins_deel_key",
                                       flexGroupId: "ins_srtdeel_key",
                                       multiple: true,
                                       filterParams: params,
                                       outputmode: outputmode,
                                       title: (parent_key? L("lcl_subobjects") : (koppel_key? L("lcl_ins_koppelobjects") : (inspect? L("lcl_ins_planned_activities"): L("lcl_ins_objects")))),
                                       showAll: showall,
                                       buttons: buttons
                                     });

        // Kolommen
        if (fronto)
        {
          rst.addColumn(new Column({caption: L("lcl_obj_sort"), content: "soort", hasActions: true}));
          rst.addColumn(new Column({caption: L("lcl_obj_identification"), content: "ins_deel_omschrijving"}));
          rst.addColumn(new Column({caption: L("lcl_ins_opmerking"), content: "ins_deel_opmerking"}));
          rst.addColumn(new Column({caption: L("lcl_obj_position"), content: fnPlace}));
          rst.addColumn(new Column({caption: L("lcl_obj_lent_out_to"), content: fnLentOutTo}));
        }
        else
        {
          if (koppel_key && (L("lcl_obj_koppelaan") != L("lcl_obj_koppelvan")))
          {
              rst.addColumn(new Column({caption: L("lcl_obj_koppelaan"), content: fnKoppelaan}));
              rst.addColumn(new Column({caption: L("lcl_obj_koppelvan"), content: fnKoppelvan}));
          }
          else // gewoon
          {
              if (inspect && ctrdisc_key == -1)
                rst.addColumn(new Column({caption: L("ctr_discipline"), content: "ctr_disc_oms"}));
              rst.addColumn(new Column({caption: L("lcl_obj_identification"), content: "ins_deel_omschrijving"}));
              rst.addColumn(new Column({caption: L("lcl_ins_opmerking"), content: "ins_deel_opmerking", combine: inspect}));
          }

          if (koppel_key)
              rst.addColumn(new Column({caption: L("lcl_obj_koppeloms"), content: "ins_deelkoppeling_omschrijving"}));
          if (inspect)
          {
              rst.addColumn(new Column({caption: L("lcl_ins_status"), content: fnStatus}));
              rst.addColumn(new Column({caption: (inspDone? L("lcl_ins_controle_datum") : L("lcl_ins_controle_next")), content: fnInspectie}));
              rst.addColumn(new Column({caption: L("lcl_ins_controle_plandate"), content: fnPlandatum}));
              if (inspDone)
                rst.addColumn(new Column({caption: L("ins_controlemode_success"), content: fnCMSuccess}));
              rst.addColumn(new Column({caption: L("lcl_ins_controle_srt"), content: "ins_srtcontrole_omschrijving"}));
              rst.addColumn(new Column({caption: L("lcl_ins_controle_groep"), content: "groepoms"}));
          }

          if (!parent_key) {
              rst.addColumn(new Column({caption: L("lcl_obj_position"), content: "plaats"}));
              if (!fgraph)
                rst.addColumn(new Column({caption: L("lcl_obj_owner"), content: "uitgeleend_aan", combine: true}));
          }
          if (params.mjob)
          {
            rst.addColumn(new Column({caption: L("lcl_discipline"), content: "ins_disc_oms"}));
            rst.addColumn(new Column({caption: L("lcl_obj_group"), content: "ins_groep_oms"}));
          }
          rst.addColumn(new Column({caption: L("lcl_obj_sort"), content: "soort"}));
          if (!parent_key && !koppel_key && !inspect) {
              if (!fgraph && !embedded &&hasDrawings)
                rst.addColumn(new Column({caption: L("lcl_fg_gotofgheader"), content: fnPosition, align:"center"}));
              if (!embedded && ErisReserveerbaar && !inspect)
                  rst.addColumn(new Column({caption: L("lcl_obj_reserveerbaar"), content: fnReserveerbaar, align:"center"}));
              if (!embedded && ErisUitleenbaar && !inspect)
                  rst.addColumn(new Column({caption: L("lcl_obj_uitleensrtdeel"), content: fnUitleenbaar, align:"center"}));
          }
        }

        if (inacObjIncl) {
          // alleen als er ook inactieven voorkomen is het zinvol deze kolom te tonen
          rst.addColumn(new Column({caption: L("lcl_ins_active"), content: fnActief}));
        }
        if (!inspect && !fronto) {  // kan over gediscussieerd worden
          rst.addColumn(new Column({caption: L("lcl_ins_vervaldatum"), content: "ins_deel_vervaldatum", datatype: "date", prettydate: true}));
        }

        // Acties
        if (fronto && authparams.PRSwritelevel < 9) // Ik heb write rechten nodig voor deze acties
        {
          // 1 van de 2 mag zichtbaar zijn. Kijken naar query resultaat!!!
          // PF: TODO: multi in/uit werkt niet goed
          rst.addAction({ action: "insEdit", caption: L("lcl_details"), enabler: "eDetails", isDefault: true}); // Actie insEdit gaat toch eerst naar show mode.
          // Inchecken of uitchecken is zichtbaar. Beiden kunnen als default aangeven worden.
          // Nu alle regels aanklikbaar of inchecken of uitchecken
          rst.addAction({ action: "insCheckOut", caption: L("lcl_obj_lend_out"), enabler: "eLendOut"});
          rst.addAction({ action: "insCheckIn", caption: L("lcl_obj_receive"), enabler: "eReceive"});
          rst.addAction({ action: "insAdapt", caption: L("lcl_ins_adapt"), enabler: "eAdapt"});
        }
        if (backo)
        {
          rst.addAction({ action: "insEdit", caption: L("lcl_change"), isDefault: true}); // isDefault, dus nooit multi, alleen door aanklikken regel. Multi via afgehandeld via functie insMultiEdit()
          if (inspect)
          {
            var sql_opt = "SELECT MAX(BITAND(ins_srtcontrole_options, 1)) insplan"
                    + "     , MAX(BITAND(ins_srtcontrole_options, 2)) insstart"
                    + "     , MAX(BITAND(ins_srtcontrole_options, 4)) insclose"
                    + "     , MAX(BITAND(ins_srtcontrole_options, 8)) insfinish"
                    + "     , COUNT(ins_srtcontrole_options) aantal"
                    + "  FROM ins_srtcontrole";
            var oRs_opt = Oracle.Execute(sql_opt);

            if (oRs_opt("aantal").Value > 0)
              rst.addAction({ action: "insShowInsp", caption: L("lcl_change"), enabler: "eShowInsp" });
            if (oRs_opt("insplan").Value == 1)
              rst.addAction({ action: "insPlan", caption: L("lcl_ins_schedule"), multi: !tiny, multiOnce: true, enabler: "ePlan" });
            if (oRs_opt("insstart").Value == 2)
              rst.addAction({ action: "insStart", caption: L("lcl_ins_start"), multi: !tiny, multiOnce: true, enabler: "eStart" });
            if (oRs_opt("insclose").Value == 4)
              rst.addAction({ action: "insClose", caption: L("lcl_ins_stop"), multi: !tiny, multiOnce: true, enabler: "eClose" });
            if (oRs_opt("insfinish").Value == 8)
              rst.addAction({ action: "insFinish", caption: L("lcl_ins_finish"), multi: !tiny, multiOnce: true, enabler: "eFinish" });
          }
          else
          {
            rst.addAction({ action: "insDelete", caption: L("lcl_delete"), enabler: "eDelete", single: false, multi: !tiny, multiOnce: true});
            if (hasWriteINSMAN) // Ik heb INSMAN rechten nodig om multi te kunnen editen. Met alleen INSUSE rechten mag ik dat vooralsnog niet.
              rst.addAction({ action: "insMultiEdit", caption: L("lcl_ins_multi_edit"), enabler: "eEditMulti", multi: !tiny, single: false, multiOnce: true});
            rst.addAction({ action: "insMultiMove", caption: L("lcl_ins_multi_move"), enabler: "NotExist", multi: !tiny, multiOnce: true});
          }
        }

        var count = rst.processResultset();

        if (!excel && !print)
	    {
%>
		      <!-- LEGENDA  -->
		      <script type="text/javascript">
		        function openLegenda()
		        {
		            params = { width: 250,
		                       minWidth: 250,
		                       minHeight: 10,
		                       resizable: false,
		                       position: {my: "right top", at: "right top+30"},
		                       title: "<%=L("lcl_ins_controle_legenda")%>"
		                     }
		            $('div#legenda').dialog(params).dialog('open');
		            FcltMgr.resized();
		        }
		      </script>
		    <div id="legenda" style="display:none; line-height: 30px;">
		      <table id="inslegenda">
		        <tr class="expired1">
		          <td title="<%= L("lcl_ins_controle_soon") %>"><%= L("lcl_ins_controle_soon") %></td>
		        </tr>
		        <tr class="expired2">
		          <td title="<%= L("lcl_ins_controle_soon") %>"><%= L("lcl_ins_controle_late") %></td>
		        </tr>
		      </table>
		    </div>
<%
	    }
      }
%>
    </body>
  </html>
<%
}
%>
