<%@ language="javascript"%>
<% /*
     $Revision$
     $Id$

    File:               mld_show_note2.asp
    Description:        Nieuwe notities versie.
                        Betere layout, altijd een invulveld
    Parameters:         mld_key (altijd verplicht hier)

    Note:               Nu kan iedereen hier zijn, FE of FOBO. FE mag de interne notes niet zien, let daarop.

*/

var mld_key = getQParamInt("mld_key"); // Altijd verplicht mld_key.
var LOCKED_USER_OK = { "xmlnode": "melding", "key": mld_key };
%>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="../Shared/status.inc"-->
<!-- #include file="./mld.inc" -->
<!-- #include file="../Shared/resultset_table_v2.inc" -->
<!-- #include file="../Shared/discx3d.inc" -->
<!-- #include file="../Shared/notes.inc" -->
<%
FCLTHeader.Requires({js: ["jquery-ui.js", "notes.js"]}); // Bestand "../mld/mld_list.js" is niet nodig.

var urole = getQParamSafe("urole", "fe");
var outputmode = getQParamInt("outputmode", 0);
var tracking = getQParamInt("tracking", (urole=="fe" && S("mld_hide_fe_tracking") ? 0 : 1)) == 1; // tracking erbij tonen? Onderdrukken met 0

var tmp_note = getQParam("tmp_note", "");
var parent_reload = getQParamInt("parent_reload", 0);

var note_key = getQParamInt("note_key", -1);
var mld_info = mld.mld_melding_info(mld_key);
// afgehandeld:  1=Afgewezen, =Afgemeld, 6=Verwerkt. Setting mld_rejected_is_open: show rejected meldingen as Open FE/FO {1=Open | 0=Closed}.
var afgehandeld = (mld_info.mld_status == 5 || mld_info.mld_status == 6 || (mld_info.mld_status == 1 && S("mld_rejected_is_open") == 0));
var stdm_info = mld.mld_stdmeldinginfo(mld_info.stdm_key);

var verynew = getQParamInt("verynew", 0) == 1;

lcl.set_dialect(mld_info.srtdisc_key, "MLD_SRTDISCIPLINE_KEY");
var mfe = mld.func_enabled_melding (mld_key);
// Heb ik rechten om notities te zien
user.auth_required_or_abort(mfe.canReadNotes && (!mfe.haveOnlyFErights || mld_info.stdm_notes & 1));

var hasFOBOMIread = mfe.canFOread || mfe.canBOread || mfe.canMIread;

var actiebijaanvrager = (mld_info.actiecode & 2);
var eigenMelding = user.isCollega(mld_info.melder_key);
var canDeleteNoteAttachment = (mld_info.mld_status == 6? 0 : 1);

var kenmerk_key_arr = [];
var srtkenm_oms_arr = [];
var multipleBijlagenTypes = false;
if (mld_key > 0)
{
  // Zijn er een bijlage kenmerken?
  var sql = mld.getMldKenmerk_sql(mld_key, {wheres: ["BITAND(mkm.mld_kenmerk_rolcode, 1) > 0", // FE mag het zien
                                                     "mkm.mld_kenmerk_volgnummer >= 0",  // negatieven zijn verstopt
                                                     "msk.mld_srtkenmerk_kenmerktype = 'M'",
                                                     "(mkm.mld_kenmerk_toonbaar = 0 OR mkm.mld_kenmerk_toonbaar IS NULL)"]}
                                 );
  var oRs = Oracle.Execute(sql);
  while (!oRs.eof)
  {
    kenmerk_key_arr.push(oRs("mld_kenmerk_key").Value);
    srtkenm_oms_arr.push(oRs("mld_kenmerk_omschrijving").Value);

    oRs.moveNext();
    if (!multipleBijlagenTypes && !oRs.eof)
      multipleBijlagenTypes = true;
  }
  oRs.Close();

  var upload_url = [];
  for (var i = 0; i < kenmerk_key_arr.length; i++)
  {
    upload_url[i] = protectQS.create("../Shared/BijlagenForm.asp?module=MLD&niveau=M&multi=1&candelete=" + canDeleteNoteAttachment + "&key=" + mld_key + "&kenmerk_key=" + kenmerk_key_arr[i]);
  }
}

%>
<html>
  <head>
<%  FCLTHeader.Generate({outputmode: outputmode}); %>
    <script>
      // De functie note_submit is aanwezig in LocalScripts/notes.js.
      // Elke module heeft een eigen callback functie note_submit_callback.
      function note_submit_callback(json)
      {
        if (window.noteediting && FcltMgr.stopEdit(window))
        {
          window.noteediting = false;
        }
        if (json.mustrefreshMLD)
          window.parent.mldframe.FcltMgr.reload();

        if (json.verynewnote)
        {
          window.FcltMgr.reload({ "appendurl": "verynewnote=1" });
          return;
        }
        promptAccept(json.canAccept);
      }

      function promptAccept(canAccept)
      {
        if (canAccept && window.parent.mldframe.mld_accept)
        {
          FcltMgr.confirm(L("lcl_mld_accept_3"),
                          {
                            fncancel: function() {
                                window.location.href = "../mld/mld_show_note2.asp?urole=<%=urole%>&mld_key=<%=mld_key%>&tracking=<%=tracking?1:0%>";
                             <% if (parent_reload == 1)
                                { %>
                                window.parent.FcltMgr.reload();
                             <% } %>
                            }
                          },
                          function() {
                            window.location.href = "../mld/mld_show_note2.asp?urole=<%=urole%>&mld_key=<%=mld_key%>&tracking=<%=tracking?1:0%>&startacceptdialog=1";
                          }
                         );
        }
        else
        {
          window.location.href = "mld_show_note2.asp?urole=<%=urole%>&mld_key=<%=mld_key%>&tracking=<%=tracking?1:0%>";
<%        if (parent_reload == 1)
          { %>
            window.parent.FcltMgr.reload();
<%        } %>
        }
      }

      function toggleDropdown()
      {
        $("li#printhamburger").find("> .fa-times").toggleClass("fa-bars fa-times");
        $("li.byHamburger").toggleClass("hidden", true);
        $("li.byDropdown").toggleClass("hidden");
        FcltMgr.resized();
      }

<%  if (S("ai_enabled") & 4)
    { %>
        var ai_params = {};
        function aiSummarize() {
            let $popup = parent?.$(".ai_mld_summary");
            if (!$popup.length) {
                return;
            }
            $popup.find(".card").html(`
                <div class="header">${L("lcl_ai_generated")}</div>
                <div class="body">${I("fa-spinner-third fa-spin fa-lg")}</div>
            `);
            $popup.dialog(ai_params).dialog("open");
<%          var url_get_mld_info_ajax = "../mld/get_mld_info_ajax.asp?req_info=promptAI&mld_key=" + mld_key; %>
            var protected_mld_info_ajax = "<%=safe.jsstring(protectQS.create(url_get_mld_info_ajax))%>";
            var data = {
                for: "summary"
            };
            protectRequest.dataToken(data);
            var request = $.ajax(protected_mld_info_ajax, {
                method: "POST",
                noSpinner: true,
                data: data
            });
            request.then(json => {
                if (json.success) {
                    var $ai_body = $popup.find(".mld-summary > .card > .body > i").parent(".body");
                    if ($ai_body.length) {
                        $ai_body.data("summary", json.content);
                        $.when($ai_body.text(json.content)).then(_ => {
                            $popup.closest("[role='dialog']").position({ my: "center", at: "center", of: parent.window });
                        });
                    }
                }
            });
        }
<%  } %>

      $(function ()
      {
<%  if (S("ai_enabled") & 4)
    { %>
        ai_params = {
            modal: true,
            width: 600,
            position: { my: "center", at: "center", of: parent.window },
            create: parent.FcltMgr.fnCreateCloseButton(".ai_mld_summary"),
            closeOnEscape: true
        };

        let $popup = parent?.$(".ai_mld_summary");
        $popup.find(".mld-summary .card").on("click", function () {
            var summary = $popup.find(".body").data("summary");
            if (summary) {
                if ($("#note").val() == "") {
                    $("#note").val(summary)
                              .trigger("blur") // Autogrow
                              .get(0).scrollIntoView({ block: "nearest", behavior: "smooth" });
                    validateTextarea();
                }
                $popup.dialog("close");
            }
        });
<%  }
        if (getQParamInt("startacceptdialog", 0 )== 1)
        { %>
          window.parent.mldframe.mld_accept("<%=stdm_info.doublecheck%>", 1);
<%      }
        if (getQParamInt("verynewnote", 0) == 1)
        { %>
          promptAccept(<%=(mfe.canAccept? 1 : 0)%>);
<%      } %>

        init_note(<%=note_key%>);

<%      if (multipleBijlagenTypes)
        { %>
          $("div.hambdropdown.bijlagen").appendTo($("#appendixes").parent("ul"));
<%      } %>
      });
    </script>
  </head>

  <body class="notesmode">
<%
  SUBFRAME_START();
    var buttons =  [];
    buttons.push({ icon: "fa-fclt-refresh", title: L("lcl_refresh"), action: "FcltMgr.stopEdit(window);FcltMgr.reload()"});

    if (urole=="fo" || urole=="bo")
        buttons.push({ icon: "fa-print", title: L("lcl_print"), action: "doPrint(" + mld_key + ", 'MLD', '" + urole + "')" });

    if (kenmerk_key_arr.length == 1)
        buttons.push({ icon: "fa-folder-open", title: L("lcl_appendixes"), action: "Upload('" + upload_url[0] + "')", showAlways: true });
    else if (kenmerk_key_arr.length > 1)
        buttons.push({ id: "appendixes", icon: "fa-chevron-down", title: L("lcl_appendixes"), action: "toggleDropdown()", showAlways: true });

    IFRAMER_HEADER(L("lcl_mld_behandeling"), buttons, { inhamburger: true });
    var safe_notes_title = safe.html(L("lcl_mld_frame_notes"));
    if (S("ai_enabled") & 4) {
        safe_notes_title += "&nbsp;<span class='default-clickable-icon' onclick='aiSummarize()' title='" + safe.htmlattr(L("lcl_mld_summarize")) + "'>" + I("fa-sparkles") + "</span>";
    }
    BLOCK_START("mldHistorie", safe_notes_title, { detailToggle: true, wide: true, nopadding: true, icon: "fa-clipboard-list-check", ishtmlsafe: true });

    var note_zichtbaarFE = mld_info.fenotes == 1 || mld_info.fenotes == 3;
    var mld_note_flag = 0;
    if (note_key > -1)
    { // Bestaande net toegevoegde note voor re-edit: gegevens uit record gebruiken.
        sql = "SELECT mld_melding_note_flag"
            + "  FROM mld_melding_note"
            + " WHERE mld_melding_note_key = " + note_key
            + "   AND mld_melding_key = " + mld_key;
        var oRs = Oracle.Execute(sql);
        mld_note_flag = oRs("mld_melding_note_flag").value;
        oRs.Close();
    }

    var params = { tabel: "mld_melding",
                   xmlnode: "melding",
                   mod_tabel: "mld_melding",
                   note_tabel: "mld_melding_note",
                   tmp_note: tmp_note,
                   showNote: ((!mfe.haveOnlyFErights && mfe.canReadAny) || (mfe.haveOnlyFErights && !mfe.parentOfOwnRead && mld_info.fenotes > 0) || mfe.canChangeKenmerkBlok),
                /* showNote: mfe.canReadNotes, // Waarom werkt dit niet gewoon .. ? -> Nou, minstens omdat die mld_info.fenotes nog niet incorporeert, maar dat zou wel mogen */
                   writeNote: mfe.canWriteNotes,
                   afgehandeld: afgehandeld,
                   note_flag: mld_note_flag,
                   mld_info: mld_info,
                   this_mld: mfe,
                   tracking: tracking
                 };

    var mld_att_cnt_sql = "SELECT COUNT(*)"
                        + "  FROM fac_bijlagen fb, mld_melding_note mn"
                        + " WHERE fb.fac_bijlagen_refkey = mn.mld_melding_note_key"
                        + "   AND fb.fac_bijlagen_module = 'MLDN'"
                        + "   AND fb.fac_bijlagen_verwijder IS NULL"
                        + (mfe.haveOnlyFErights ? " AND BITAND(mld_melding_note_flag, 1) = 1" : "")
                        + "   AND mn.mld_melding_key = " + mld_key;
    var ord_att_cnt_sql = "0";

    var show_opdr_notes = (mld_info.stdm_notes & 4);
    if (show_opdr_notes) {
        ord_att_cnt_sql = "SELECT COUNT(*)"
                        + "  FROM fac_bijlagen fb"
                        + "     , mld_opdr_note n"
                        + " WHERE fb.fac_bijlagen_refkey = n.mld_opdr_note_key"
                        + "   AND fb.fac_bijlagen_module = 'ORDN'"
                        + (mfe.haveOnlyFErights
                            ? " AND BITAND(mld_opdr_note_flag, 1) = 1"
                            : "")
                        + "   AND n.mld_opdr_key IN (SELECT mld_opdr_key"
                        + "                            FROM mld_opdr o"
                        + "                           WHERE o.mld_melding_key = " + mld_key + ")";
    }

    var any_att_sql = "SELECT (" + mld_att_cnt_sql + ") + (" + ord_att_cnt_sql + ") attachment_count FROM DUAL";
    var any_att_oRs = Oracle.Execute(any_att_sql);
    var has_any_attachments = any_att_oRs("attachment_count").Value > 0;
    any_att_oRs.Close();

    if (S("note_sort_ascending") == 0) { notes.note_field(mld_key, note_key, "MLD", params); }

    // What notes to show? determined by mld_stdmelding.mld_stdmelding_notes
    // 0  = meldingnotes
    // &1 = Notes van FE
    // &2 = Notes van FOBO
    // &4 = Notes van Uitvoerder

    if (multipleBijlagenTypes)
    {
        // Create a dropDown div for the multiple bijlagen types
        Response.write("<div id=\"buttons\" class=\"hambdropdown bijlagen\"><ul onclick=\"FcltMgr.stopPropagation(event);\">");
        for (var i = 0; i < kenmerk_key_arr.length; i++)
        {
            CreateButton(srtkenm_oms_arr[i], "$('li.byDropdown').toggleClass('hidden');FcltMgr.resized();Upload('" + upload_url[i] + "')", { icon: "fa-folder-open", showIcon: true, xclass: "hidden byDropdown" }, { vertical: true });
        }
        Response.write("</ul></div>");
    }

    var selector_sql = "(SELECT fac_note_group_naam"
                      + "  FROM fac_note_group fng"
                      + " WHERE n.fac_note_group_key = fng.fac_note_group_key"
                      + "   AND fac_note_group_vervaldatum IS NULL) fac_note_group_naam";

    // Melding notes
    var sql = "SELECT n.mld_melding_note_aanmaak creation_date"
            + "     , '1' seq"
            + "     , n.mld_melding_note_wijzigdatum"
            + "     , n.mld_melding_note_key note_and_tracking_key"
            + "     , n.mld_melding_note_parent_key note_parent_key"
            + "     , pf.prs_perslid_key"
            + "     , pf.prs_perslid_naam_friendly"
            + "     , n.mld_melding_note_omschrijving"
            + "     , mld_melding_note_flag note_flag"
            + "     , NULL fac_srtnotificatie_code"
            + "     , 1 regeltype"
            + "     , null prefix"
            + "     , null opdr_image"
            + "     , null opdr_key"
            + "     , null uitv_key"
            + "     , null intern"
            + "     , " + selector_sql
            + "  FROM mld_melding_note n, prs_v_perslid_fullnames_all pf"
            + " WHERE n.prs_perslid_key = pf.prs_perslid_key (+)"
            + "   AND n.mld_melding_key = " + mld_key
            + (mfe.haveOnlyFErights? " AND BITAND(mld_melding_note_flag, 1) = 1" : "");
    var sqls = [sql];

    // Opdracht notes
    if (show_opdr_notes)
    {
        selector_sql = "(SELECT fac_note_group_naam"
                        + "  FROM fac_note_group fng"
                        + " WHERE nop.fac_note_group_key = fng.fac_note_group_key"
                        + "   AND fac_note_group_vervaldatum IS NULL) fac_note_group_naam";
        sql = "SELECT nop.mld_opdr_note_aanmaak"
            + "     , '1' seq"
            + "     , nop.mld_opdr_note_wijzigdatum"
            + "     , nop.mld_opdr_note_key"
            + "     , nop.mld_opdr_note_parent_key note_parent_key"
            + "     , pf.prs_perslid_key"
            + "     , pf.prs_perslid_naam_friendly"
            + "     , nop.mld_opdr_note_omschrijving"
            + "     , nop.mld_opdr_note_flag note_flag"
            + "     , NULL"
            + "     , 2 regeltype"
            + "     , mld_opdr_bedrijfopdr_volgnr prefix"
            + "     , ty.mld_typeopdr_image opdr_image"
            + "     , o.mld_opdr_key opdr_key"
            + "     , o.mld_uitvoerende_keys uitv_key"
            + "     , mu.intern intern"
            + "     , " + selector_sql
            + "  FROM mld_opdr_note nop, prs_v_perslid_fullnames_all pf, mld_opdr o, mld_typeopdr ty, mld_v_uitvoerende mu"
            + " WHERE nop.prs_perslid_key = pf.prs_perslid_key (+)"
            + "   AND o.mld_opdr_key = nop.mld_opdr_key"
            + "   AND ty.mld_typeopdr_key = o.mld_typeopdr_key"
            + "   AND nop.mld_opdr_key IN (SELECT mld_opdr_key FROM mld_opdr WHERE mld_melding_key = " + mld_key + ")"
            + "   AND o.mld_uitvoerende_keys = mu.mld_uitvoerende_key"
            + (mfe.haveOnlyFErights? " AND BITAND(mld_opdr_note_flag, 1) = 1" : "");
        sqls.push(sql);
    }

    if (tracking) // Tracking info erbij?
    {   // Melding
        sql = "SELECT tr.fac_tracking_datum"
            + "     , '2' seq"
            + "     , NULL wijzigdatum"
            + "     , tr.fac_tracking_key"
            + "     , NULL"
            + "     , tr.prs_perslid_key"
            + "     , pf.prs_perslid_naam_friendly"
            + "     , tr.fac_tracking_oms"
            + "     , NULL note_flag"
            + "     , str.fac_srtnotificatie_code"
            + "     , 1 regeltype"
            + "     , null prefix"
            + "     , null opdr_image"
            + "     , null opdr_key"
            + "     , null uitv_key"
            + "     , null intern"
            + "     , null fac_note_group_naam"
            + "  FROM fac_tracking tr, fac_srtnotificatie str, prs_v_perslid_fullnames_all pf"
            + " WHERE tr.fac_srtnotificatie_key = str.fac_srtnotificatie_key"
            + "   AND tr.prs_perslid_key = pf.prs_perslid_key (+)"
            + "   AND str.fac_srtnotificatie_code <> 'MLDNOT'"  // beetje dubbelop
            + "   AND tr.fac_tracking_refkey = " + mld_key
            + "   AND str.fac_srtnotificatie_xmlnode IN ('melding')";
        sqls.push(sql);

        // MLDNEW van evt. Vervolgmelding(en)
        sql = "SELECT tr.fac_tracking_datum"
            + "     , '3' seq"
            + "     , NULL wijzigdatum"
            + "     , tr.fac_tracking_key"
            + "     , NULL"
            + "     , tr.prs_perslid_key"
            + "     , pf.prs_perslid_naam_friendly"
            + "     , tr.fac_tracking_oms"
            + "     , NULL note_flag"
            + "     , str.fac_srtnotificatie_code"
            + "     , 1 regeltype"
            + "     , m.mld_melding_key prefix"
            + "     , null opdr_image"
            + "     , null opdr_key"
            + "     , null uitv_key"
            + "     , null intern"
            + "     , null fac_note_group_naam"
            + "  FROM fac_tracking                 tr"
            + "     , fac_srtnotificatie           str"
            + "     , prs_v_perslid_fullnames_all  pf"
            + "     , mld_melding                  m"
            + " WHERE     tr.fac_srtnotificatie_key = str.fac_srtnotificatie_key"
            + "       AND tr.prs_perslid_key = pf.prs_perslid_key(+)"
            + "       AND str.fac_srtnotificatie_code = 'MLDNEW'"
            + "       AND m.mld_melding_start_key = " + mld_key
            + "       AND m.mld_melding_key <> " + mld_key
            + "       AND tr.fac_tracking_refkey = m.mld_melding_key"
            + "       AND str.fac_srtnotificatie_xmlnode IN ('melding')";
        sqls.push(sql);

        // Opdracht
        if (show_opdr_notes)
        {
            sql = "SELECT tr.fac_tracking_datum"
                + "     , '2' seq"
                + "     , NULL wijzigdatum"
                + "     , tr.fac_tracking_key"
                + "     , NULL"
                + "     , tr.prs_perslid_key"
                + "     , pf.prs_perslid_naam_friendly"
                + "     , tr.fac_tracking_oms"
                + "     , NULL note_flag"
                + "     , str.fac_srtnotificatie_code"
                + "     , 2 regeltype"
                + "     , mld_opdr_bedrijfopdr_volgnr prefix"
                + "     , ty.mld_typeopdr_image opdr_image"
                + "     , o.mld_opdr_key opdr_key"
                + "     , null uitv_key"
                + "     , null intern"
                + "     , null fac_note_group_naam"
                + "  FROM fac_tracking tr, fac_srtnotificatie str, prs_v_perslid_fullnames_all pf, mld_opdr o, mld_typeopdr ty"
                + " WHERE tr.fac_srtnotificatie_key = str.fac_srtnotificatie_key"
                + "   AND o.mld_opdr_key = tr.fac_tracking_refkey"
                + "   AND tr.prs_perslid_key = pf.prs_perslid_key (+)"
                + "   AND ty.mld_typeopdr_key = o.mld_typeopdr_key"
                + "   AND tr.fac_tracking_refkey IN (SELECT mld_opdr_key FROM mld_opdr WHERE mld_melding_key = " + mld_key + ") "
                + "   AND str.fac_srtnotificatie_xmlnode IN ('opdracht')";
            sqls.push(sql);
        }
    }

    sql = "SELECT * FROM (" + sqls.join(" UNION ") + ") ORDER BY creation_date"
        + (S("note_sort_ascending") == 0? " DESC " : "")
        + ", seq" // Volgorde (sequence) ook bij gelijktijdigheid chronologisch.
        + (S("note_sort_ascending") == 0? " DESC " : "")
        + ", note_and_tracking_key" // Zijn de tijden op de seconde af ook nog gelijk, dan maar op note/tracking key.
        + (S("note_sort_ascending") == 0? " DESC " : "");

    var oRs = Oracle.Execute(sql);
    var lasttime = null;
    var lastuser = null;
    // XXXINF: 'Notificatie XXXXXX verstuurd aan xxxx@example.com' herhalingen onderdrukken
    // We doen reverse-enigineering op S("puo_lcl_tracknoti") (een tekst)
    // Niet echt jofel maar gelukkig is hij niet vertaalbaar
    var NotiMailArr = [];
    var notiRegexp = new RegExp(S("puo_lcl_tracknoti").format("(MLDINF|MLD2..)", "(.*)")); // De haakjes doen een 'capture' op de waarden
    var firstrec = true;
    Response.Write("<div class='notes-wrapper'>");
    while(!oRs.Eof)
    {
        var thisuser            = oRs("prs_perslid_naam_friendly").Value;
        var prs_key             = oRs("prs_perslid_key").Value;
        var opdr_key            = oRs("opdr_key").Value || -1;
        var note_parent_key     = oRs("note_parent_key").value || -1;
        var thistime            = new Date(oRs("creation_date").Value);
        var timestr             = toTimeString(thistime);
        var srtnoti             = oRs("fac_srtnotificatie_code").Value;
        var prefix              = (note_parent_key === -1 ? oRs("prefix").Value : "");
        var note_oms            = oRs("mld_melding_note_omschrijving").Value;
        var fac_note_group_naam = oRs("fac_note_group_naam").Value;
        var fullname_html       = notes.fnPerslidNaamFull(oRs);
        var last_note_key       = oRs("note_and_tracking_key").Value;
        var notechange_url      = "mld_show_note2.asp?urole=" + urole + "&mld_key=" + mld_key + "&note_key=" + last_note_key + "&tracking=" + (tracking? 1 : 0);
        var melding_note_wijzigdatum = oRs("mld_melding_note_wijzigdatum").Value!=null ? new Date(oRs("mld_melding_note_wijzigdatum").Value) : null;
        var isvanOpdracht       = oRs("regeltype").Value == 2; // 1=melding, 2=opdracht
        var isVervolgmelding    = oRs("seq").Value == 3;
        var note_zichtbaarFE    = oRs("note_flag").Value & 1;
        var note_zichtbaarUITV  = oRs("note_flag").Value & 4; /* TODO irrelevant? */
        var note_unanswered     = oRs("note_flag").Value & 32;
        var ismailnote          = oRs("note_flag").Value & 64;
        var note_flag           = oRs("note_flag").Value || 0;
        var eigenNotitie        = prs_key == user_key;
        var note_uid            = "note-" + oRs("regeltype").value + oRs("note_and_tracking_key").Value;
        var note_wrapper_class  = "note-wrapper" + (note_unanswered ? " note-marked" : "");
        var note_container_class = "note-container note-module-" + (isvanOpdracht ? "ord" : "mld");

        var note_author_role    = mld_info.melder_key == prs_key ? 1 : 2; /* Evt UITV wordt hieronder bepaald */
        var note_author_icon    = "";
        if (prefix && note_author_role != 1) // Een melder en een uitvoerder zullen vast mutually exclusive zijn, en zo niet dan mist die maar een icoontje
        {
            var note_author = new Perslid(prs_key);
            var uitv_key = oRs("uitv_key").Value;
            if (prs_key == uitv_key
                || (oRs("intern").Value == 1 ? note_author.isCollega(uitv_key)
                                             : note_author.isBedrijfContact(uitv_key)))
            {   // Ik ben (in rol van) uitvoerder
                note_author_role = 4; /* Note auteur = uitvoerder */
                var uitv_icon = oRs("opdr_image").Value || "";
                note_author_icon = uitv_icon.match(/^fa-/) ? uitv_icon : "fa-hammer";
            }
        }

        var canReply = (mfe.haveOnlyFErights && note_unanswered && prs_key !== user_key && isvanOpdracht && eigenMelding)
                    || !mfe.haveOnlyFErights;
        canReply = canReply && !srtnoti && note_key == -1; // In edit-mode kunnen we niet aanpassen op welke notitie dit een reply is

        oRs.MoveNext();

        if (!(mld_info.stdm_notes & note_author_role)) // Notities van deze auteur worden op basis van mld_stdmelding_notes uitgesloten
            continue;

        // Probeer herhalingen van MLD2BO te onderdrukken
        if (!oRs.Eof && note_oms && note_oms.match(notiRegexp))
        {
            var nextNote = oRs("mld_melding_note_omschrijving").Value;
            if (nextNote && nextNote.match(notiRegexp))
            {
                NotiMailArr.push(note_oms.match(notiRegexp)[2]);
                continue; // los het maar op bij de volgende
            }
        }
        if (NotiMailArr.length) // als we hier komen zullen we zelf matchen maar wel de laatste zijn
        {
            NotiMailArr.push(note_oms.match(notiRegexp)[2]);
            note_oms = S("puo_lcl_tracknoti").format(note_oms.match(notiRegexp)[1], NotiMailArr.join(", "));
            NotiMailArr = [];
        }

        var newestIsNote = false;
        var newestIsSelfNote = false;
        if ((firstrec && S("note_sort_ascending") == 0) ||  // first in descending sort
            (oRs.Eof && S("note_sort_ascending") == 1))     // last in ascending sort
        {
            firstrec = false;
            newestIsNote = !srtnoti;
            newestIsSelfNote = newestIsNote && user.isCollega(prs_key);
        }

        var changeAfter = new Date();
        changeAfter.setMinutes(changeAfter.getMinutes() - S("mld_note_change_threshold"));
        var canChangeSelfNote = !srtnoti && eigenNotitie && melding_note_wijzigdatum && Math.max(thistime, melding_note_wijzigdatum) > changeAfter;

        if (eigenNotitie)
            note_wrapper_class += " note-type-self";
        // Bij user of dag switch altijd kopje. Ik zou graag systeemmeldingen niet als user-switch zien,
        // dus die bij het voorgaande kopje laten horen door die te skippen bij lastuser

        if (newestIsSelfNote && last_note_key == note_key)
            continue; // uit de while-loop

        var dedatum = toDateString(thistime, false, true);
        if (lasttime == null || (S("note_sort_ascending")? thistime.midnight() > lasttime.midnight() : thistime.midnight() < lasttime.midnight()))
            Response.Write("<div class='note-date-wrapper'><div class='note-date'>{0}</div></div>".format(toDateString(thistime, false, true)));

        var sameevent = (srtnoti && lastuser == thisuser && lasttime && Math.abs(thistime.getTime() - lasttime.getTime()) < 60000);

        lasttime = thistime;
        if (thisuser != null)
            lastuser = thisuser;   // de laatste echte user

        var safehtml = "";

        note_container_class += (srtnoti ? " note-type-tracking" : "");
        if (note_oms) // Notitie of tracking met opgeslagen tekst
        {
            safehtml = safe.notehtml(note_oms, (isvanOpdracht ? "ORD" : "MLD"), last_note_key);

            if (srtnoti == 'MLDUPD')
            {
                var arr = safehtml.split("<br>");
                if (arr.length > 1)
                    arr.shift(); // Verwijder de tekst 'Melding xxx is gewijzigd'
                safehtml = arr.join("<br>");
            }

            var prefixstr = prefix ? L("lcl_shared_order")+" "+prefix+": " : "";
            safehtml = prefixstr + safehtml;

            if (!note_zichtbaarFE && !srtnoti)
                note_container_class += " note-fe-hidden";
            note_container_class += (ismailnote ? " note-type-email" : "");

            var note_header_left = "";
            if (!sameevent)
            {
                if (note_author_icon)
                    note_header_left += "<span class='note-author-icon'>{0}</span>".format(I(safe.html(note_author_icon)));
                note_header_left += "<span class='note-author'>{0}</span>".format(fullname_html);
                note_header_left += "<span class='note-timestamp' title='{0}'>{1}</span>".format(dedatum, timestr == "00:00" ? "" : (fullname_html != "" ? " - " : "") + timestr);
            }

            if (melding_note_wijzigdatum && melding_note_wijzigdatum > thistime)
                note_header_left += "<span class='note-edited' title='"+toDateTimeString(melding_note_wijzigdatum, false, false, true)+"'> (" + L("lcl_mld_note_edited") + ")</span>";

            note_header_left = "<span class='note-header-left-wrapper'>{0}</span>".format(note_header_left);

            var note_header_right = "";
            if (fac_note_group_naam)
                note_header_right += "<span class='note-group'>" + safe.html(fac_note_group_naam) + "</span>";

            if (!note_zichtbaarFE && !srtnoti)
                note_header_right += "<span class='note-icon-hidden-frontend' title='{0}'>".format(L("lcl_mld_verborgen_FE")) + I("fa-lock") + "</span>";

            var note_actions = [];
            if ((newestIsSelfNote || canChangeSelfNote) && !isvanOpdracht)
            {
                note_actions.push({ "name"  : "edit",
                                    "label" : L("lcl_change"),
                                    "icon"  : "fa-fclt-edit",
                                    "action": "notechange('" + notechange_url + "')" });
            }

            if (canReply)
            {
                note_actions.push({ "name"  : "reply",
                                    "label" : L("lcl_note_reply"),
                                    "icon"  : "fa-reply",
                                    "action": "noteReply(" + last_note_key + ", " + (isvanOpdracht ? opdr_key : mld_key) + ", '" + (isvanOpdracht ? "OPDR" : "MLD") + "')" });
            }

            if (note_actions.length >= 1)
                note_header_right += notes.note_actions_html(note_actions);

            note_header_right = "<span class='note-header-right-wrapper'>{0}</span>".format(note_header_right);

            var note_header = "<div class='note-header'>{0}{1}</div>".format(note_header_left, note_header_right);

            var autocollapse = S("note_autocollapse") && note_oms.match(new RegExp(S("note_autocollapse"))) && note_oms.split("\n").length > 2;
            var collapse_class = "";
            if (!newestIsNote)
            {
                if (autocollapse) /* ingeklapt tot 2 regels */
                    collapse_class += " note-autocollapse";
                else if (safehtml.length > S("rs_maxchar") * 5) /* ingeklapt tot 5 regels */
                    collapse_class += " note-collapsed";
            }
            var toggler = "";
            if (autocollapse || safehtml.length > S("rs_maxchar") * 5)
                toggler += "<div class='note-toggler'>{0}</div>".format(newestIsNote ? L("lcl_rs_truncate") : L("lcl_rs_truncated"));

            var reply_to_this_note = notes.inlineReplyNote(note_parent_key, (isvanOpdracht ? "O" : "M"));

            var note_attachments = "";
            if (has_any_attachments && !srtnoti) {
                note_attachments = BB_ATTACHMENTS_HTML((isvanOpdracht ? "ORDN" : "MLDN"), last_note_key, "note");
            }

            var note_text = "<div class='note-body'>{0}<div class='note-text{1}'>{2}</div>{3}{4}</div>"
                .format(reply_to_this_note, collapse_class, safehtml, toggler, note_attachments);

            /* Nu hebben we alles om de notitie te printen; */
            Response.Write("<div id='{0}' class='{1}'><div class='{2}' data-flag='{3}'>{4}{5}</div></div>".format(note_uid, note_wrapper_class, note_container_class, note_flag, note_header, note_text));
        }
        else if (srtnoti)
        {
            var prefixstr = isVervolgmelding ? L("lcl_mld_continuation_mld") + " " + prefix + ": " : "";
            safehtml = prefixstr + status.getsrtnotificatietext(srtnoti); // default tracking tekst

            var note_header = "";
            if (!sameevent)
            {
                note_header += "<span class='note-author'>{0}</span>".format(fullname_html);
                note_header += "<span class='note-timestamp' title='{0}'>{1}</span>".format(dedatum, timestr == "00:00" ? "" : (fullname_html != "" ? " - " : "") + timestr);
            }
            var note_text = "<div class='note-text" + (thisuser == null ? " note-type-system" : "") + "'>{0}</div>".format(safehtml);

            /* Nu hebben we alles om de notitie te printen; */
            Response.Write("<div class='{0}'><div class='{1}'>{2}{3}</div></div>".format(note_wrapper_class, note_container_class, note_header, note_text));
        }

        // De MoveNext hebben we al eerder gehad
    }
    Response.Write("<div class='note-top-button' onclick='$(document.documentElement).animate({ scrollTop: 0 }, 150);'>" + I("fa-chevron-up fa-2x") + "</div>");
    Response.Write("</div>"); /* .notes-wrapper */
    oRs.Close();

    if (S("note_sort_ascending") != 0) { notes.note_field(mld_key, note_key, "MLD", params); }
    BLOCK_END();
    SUBFRAME_END();
%>
</body>
</html>
<% ASPPAGE_END(); %>
