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

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

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

*/

var opdr_key = getQParamInt("opdr_key"); // Altijd verplicht opdr_key.
var LOCKED_USER_OK = { "xmlnode" : "opdracht", "key": opdr_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: ["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"?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 verynew = getQParamInt("verynew", 0) == 1;

var this_opdr = mld.func_enabled_opdracht(opdr_key); // Wat mag ik zoal op deze opdracht.
user.auth_required_or_abort(this_opdr.canShowOpdrNote);

var mld_opdr = this_opdr.mld_opdr;
// afgehandeld:  1=afgewezen, 6=Technisch Voltooid/Afgemeld, 7=Verwerkt en 9= Kosten Voltooid
var afgehandeld = (mld_opdr.opdr_status == 1 || mld_opdr.opdr_status == 6 || mld_opdr.opdr_status == 7 || mld_opdr.opdr_status == 9);
lcl.set_dialect(mld_opdr.opdr_type, "MLD_TYPEOPDR_KEY");

var kenmerk_key = -1;
if (opdr_key > 0)
{ // Is er een bijlage kenmerk?
    var where = " AND BITAND(k.mld_kenmerk_rolcode, 3) > 0"
              + " AND (k.mld_kenmerk_verplicht IS NULL OR k.mld_kenmerk_verplicht=0)"
              + " AND t.mld_srtkenmerk_kenmerktype = 'M'"
              + " AND mld_kenmerk_toonbaar IS NULL";

    var sql = "SELECT k.mld_kenmerk_key"
            + "  FROM mld_srtkenmerk t"
            + "     , mld_kenmerk k"
            + "     , mld_opdr o"
            + " WHERE (o.mld_typeopdr_key = k.mld_typeopdr_key OR k.mld_typeopdr_key IS NULL)"
            + "   AND k.mld_kenmerk_niveau IN ('P', 'O')"
            + "   AND k.mld_srtkenmerk_key = t.mld_srtkenmerk_key"
            + "   AND k.mld_kenmerk_verwijder IS NULL"
            + "   AND t.mld_srtkenmerk_verwijder IS NULL"
            + "   AND o.mld_opdr_key = " + opdr_key
            + where
            + " ORDER BY mld_kenmerk_volgnummer"
            + "        , DECODE (k.mld_kenmerk_niveau, 'P', 0, 'O', 1)";
    var oRs = Oracle.Execute(sql);
    if (!oRs.eof)
    {
        kenmerk_key = oRs("mld_kenmerk_key").Value;
    }
    oRs.Close();

    var upload_url = protectQS.create("../Shared/BijlagenForm.asp?module=MLD&niveau=O&multi=1&key=" + opdr_key + "&kenmerk_key=" + kenmerk_key);
}

%>
<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.parent_reload == 1<%=parent_reload == 1 ? " || true" : ""%>) {
                    window.parent.FcltMgr.reload();
                } else {
                    window.location.href = "opdr_show_note2.asp?urole=<%=urole%>&opdr_key=<%=opdr_key%>&tracking=<%=tracking?1:0%>";
                }
            }


            function highlight_note(deze, toggle)
            {
                var note_tracking_key = deze.id.substr("track-".length);
                var $notities = $("[data-tracking='" + note_tracking_key + "']");
                if (note_tracking_key && $notities.length)
                {
                    $notities.toggleClass("highlight", toggle);
                    $(deze).toggleClass("highlight", toggle);
                }
            }
            function highlight_track(deze, toggle)
            {
                var note_tracking_key = $(deze).data("tracking");
                if (note_tracking_key)
                {
                    var $tracking = $("div#track-" + note_tracking_key);
                    if ($tracking.length) {
                        $tracking.toggleClass("highlight", toggle);
                        $(deze).toggleClass("highlight", toggle);
                    }
                }
            }
            $(function ()
            {
                init_note(<%=note_key%>);

                $("[data-tracking][data-tracking!='']")
                    .mouseenter(function () { highlight_track(this, true);})
                    .mouseleave(function () { highlight_track(this, false);});
                $("[id^='track-']")
                    .mouseenter(function () { highlight_note(this, true);})
                    .mouseleave(function () { highlight_note(this, false);});
            });
        </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(" + opdr_key + ", 'OPDR', '" + urole + "')" });

        if (kenmerk_key != -1)
            buttons.push({ icon: "fa-folder-open", title: L("lcl_appendixes"), action: "Upload('" + upload_url + "')", showAlways: true});

        IFRAMER_HEADER(L("lcl_mld_behandeling"), buttons, { inhamburger: true });
        BLOCK_START("opdrHistorie", L("lcl_opdr_frame_notes"), { detailToggle: true, wide: true, nopadding: true, icon: "fa-clipboard-list-check" });
        var mld_info = this_opdr.mld_info || mld.mld_melding_info(mld_opdr.mld_key);

        var opdr_note_flag = 0;
        if (note_key > -1)
        { // Bestaande net toegevoegde note voor re-edit: gegevens uit record gebruiken.
            sql = "SELECT mld_opdr_note_flag"
                + "  FROM mld_opdr_note"
                + " WHERE mld_opdr_note_key = " + note_key
                + "   AND mld_opdr_key = " + opdr_key;
            var oRs = Oracle.Execute(sql);
            opdr_note_flag = oRs("mld_opdr_note_flag").value;
            oRs.Close();
        }

        var params = { tabel: "mld_opdr",
                       xmlnode: "opdracht",
                       mod_tabel: "mld_opdr",
                       note_tabel: "mld_opdr_note",
                       tmp_note: tmp_note,
                       showNote: this_opdr.canShowOpdrNote,
                       writeNote: this_opdr.canEditOpdrNote,
                       afgehandeld: afgehandeld,
                       note_flag: opdr_note_flag,
                       this_opdr: this_opdr, // meegeven wat je al weet
                       mld_info: mld_info,
                       tracking: tracking
                     };

        var any_att_sql = "SELECT COUNT(*) attachment_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'"
                        + (this_opdr.myRole === 4 ? " AND BITAND(n.mld_opdr_note_flag, 4) = 4" : "")
                        + "   AND n.mld_opdr_key = " + opdr_key;
        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(opdr_key, note_key, "OPDR", params); }

        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";

        var sql_n = "SELECT n.mld_opdr_note_aanmaak"
                  + "     , n.mld_opdr_note_key pkey"
                  + "     , n.mld_opdr_note_parent_key"
                  + "     , pf.prs_perslid_key"
                  + "     , pf.prs_perslid_naam_friendly"
                  + "     , n.mld_opdr_note_omschrijving"
                  + "     , n.mld_opdr_note_flag"
                  + "     , NULL fac_srtnotificatie_code"
                  + "     , n.fac_tracking_key note_fac_tracking_key" // verwijzing naar de tracking waar de notitie bij hoort
                  + ", " + selector_sql
                  + "  FROM mld_opdr_note n"
                  + "     , prs_v_perslid_fullnames_all pf"
                  + " WHERE n.prs_perslid_key = pf.prs_perslid_key (+)"
                  + "   AND n.mld_opdr_key = " + opdr_key
                  + (this_opdr.myRole === 4 ? " AND BITAND(n.mld_opdr_note_flag, 4) = 4" : "");
        var sqls = [sql_n];

        if (tracking) // tracking info erbij?
        {
            var sql_t = "SELECT tr.fac_tracking_datum"
                      + "     , tr.fac_tracking_key pkey"
                      + "     , NULL"
                      + "     , tr.prs_perslid_key"
                      + "     , pf.prs_perslid_naam_friendly"
                      + "     , tr.fac_tracking_oms"
                      + "     , NULL"
                      + "     , str.fac_srtnotificatie_code"
                      + "     , NULL"
                      + "     , 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 (tr.fac_tracking_refkey = " + opdr_key
                      + "   AND str.fac_srtnotificatie_xmlnode IN ('opdracht'))";
            sqls.push(sql_t);
        }
        var sql = "SELECT * FROM ("+ sqls.join(" UNION ") + ")"
                + " ORDER BY 1" + (S("note_sort_ascending") == 0 ? " DESC " : "")
                        + ", 2" + (S("note_sort_ascending") == 0 ? " DESC " : "");

        var oRs = Oracle.Execute(sql);
        var lasttime = null;
        var lastuser = null;
        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 note_parent_key     = oRs("mld_opdr_note_parent_key").value || -1;
            var thistime            = new Date(oRs("mld_opdr_note_aanmaak").Value);
            var timestr             = toTimeString(thistime);
            var srtnoti             = oRs("fac_srtnotificatie_code").Value;
            var note_oms            = oRs("mld_opdr_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("pkey").Value;
            var notechange_url      = "opdr_show_note2.asp?urole=" + urole + "&opdr_key=" + opdr_key + "&note_key=" + last_note_key + "&tracking=" + (tracking? 1 : 0);
            var note_zichtbaarUITV  = oRs("mld_opdr_note_flag").Value & 4;
            var note_unanswered     = oRs("mld_opdr_note_flag").Value & 32;
            var ismailnote          = oRs("mld_opdr_note_flag").Value & 64;
            var note_flag           = oRs("mld_opdr_note_flag").Value || 0;
            var note_fac_tracking_key = oRs("note_fac_tracking_key").Value;
            var eigenNotitie        = prs_key == user_key;

            if (srtnoti)
            {
                var note_uid        = "track-" + last_note_key; /* Eigenlijk tracking */
            }
            else
            {
                var note_uid        = "note-2" + last_note_key; /* Hardcoded 2, want dit staat altijd in de mld_opdr_note tabel */
            }
            var note_wrapper_class  = "note-wrapper" + (note_unanswered ? " note-marked" : "");
            var note_container_class = "note-container note-module-ord";

            var note_author_icon    = "";
            if (mld_info.melder_key == prs_key) {
                note_author_icon = "fa-user-circle";
            }

            var canReply = this_opdr.myRole === 2; // Alleen FOBO
            canReply = canReply && !srtnoti && note_key == -1; // In edit-mode kunnen we niet aanpassen op welke notitie dit een reply is

            oRs.MoveNext();
            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);
            }

            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 && srtnoti) // tracking zonder dat tekst is overruled
                note_oms = status.getsrtnotificatietext(srtnoti); // default tracking tekst

            if (note_oms) // Notitie of tracking met opgeslagen tekst
            {
                safehtml = safe.notehtml(note_oms, "ORD", last_note_key);

                if (!note_zichtbaarUITV && !srtnoti)
                    note_container_class += " note-uitv-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);
                }
                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_zichtbaarUITV && !srtnoti)
                    note_header_right += "<span class='note-icon-hidden-uitv' title='{0}'>".format(L("lcl_mld_verborgen_UITV")) + I("fa-lock") + "</span>";

                var note_actions = [];
                if (newestIsSelfNote)
                {
                    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 + ", " + opdr_key + ", 'OPDR')" });
                }
                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, "O");

                var note_attachments = "";
                if (has_any_attachments && !srtnoti) {
                    note_attachments = BB_ATTACHMENTS_HTML("ORDN", 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 of tracking te printen; */
                Response.Write("<div id='{0}' class='{1}' data-tracking='{2}'>".format(note_uid, note_wrapper_class, note_fac_tracking_key||"")
                             + "    <div class='{0}' data-flag='{1}'>{2}{3}</div>".format(note_container_class, note_flag, note_header, note_text)
                             + "</div>");

            }
            // else obscuur dat we geen tekst hebben?

            // 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(opdr_key, note_key, "OPDR", params); }
        BLOCK_END();
        SUBFRAME_END(); %>
    </body>
</html>
<% ASPPAGE_END(); %>
