<%@ 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:               We forceren dat je BO of FO rechten hebt. Je mag dus altijd alles zien
*/%>

<!-- #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" -->
<%
FCLTHeader.Requires({js: ["../mld/mld_list.js"]})

var mld_key = getQParamInt("mld_key"); // altijd verplicht mld_key
var urole = getQParamSafe("urole", "fe");
var outputmode = getQParamInt("outputmode", 0);
var tracking = getQParamInt("tracking", 1) == 1; // tracking erbij tonen? Onderdrukken met 0

var note_key = getQParamInt("note_key", -1);
var mld_info = mld.mld_melding_info(mld_key);

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

lcl.set_dialect(mld_info.srtdisc, "MLD_SRTDISCIPLINE_KEY");
var mfe = mld.func_enabled_melding (mld_key);
// Heb ik rechten om notities te zien
__DoLog(1);
user.auth_required_or_abort(mfe.canReadNotes);
__DoLog(2);
user.auth_required_or_abort(!mfe.haveOnlyFErights); // FE only mag hier helemaal niet (kunnen) komen
__DoLog(3);

var eigenMelding = user_key == mld_info.melder_key || user.isCollega(mld_info.melder_key);
var afgehandeld = (mld_info.mld_status == 1 || mld_info.mld_status == 5 || mld_info.mld_status == 6);

%>
<html>
  <head>
<%  FCLTHeader.Generate({outputmode: outputmode}); %>
    <script>
      function persoonDetails(evt, perslid_key)
      {
        FcltMgr.stopPropagation(evt);
        FcltMgr.openDetail("appl/fac/fac_user.asp?prs_key=" + perslid_key);
      }
      function mld_notechange(mld_note_key)
      {
          window.location.href = "mld_show_note2.asp?urole=<%=urole%>&mld_key=<%=mld_key%>" + (mld_note_key?"&note_key="+mld_note_key:"");
      }
      function note_submit()
      {
          var url = $("form[name=u2]")[0].action;
          $.post($("form[name=u2]")[0].action,
                 $("[name=u2]").serialize(),
                 FcltCallbackAndThen(note_submit_callback),
                 "json");
          return true; // disabled button ook
      }
      function note_submit_callback(json)
      {
        window.location.href = "mld_show_note2.asp?urole=<%=urole%>&mld_key=<%=mld_key%>";
      }

      $(function () {
           $('textarea').resize(function () { FcltMgr.resized(window) } );
           $('textarea').autogrow();
           // Let op: scrollen is complexer dan je denkt. Ons huidige document heeft
           //         helemaal geen scrollbars, die zijn van de parent-IFrame!
           <% if (!verynew && getQParamInt("autoscroll", 0) == 1) { %>
                $('#note').focus();
                window.setTimeout('parent.scrollBy(0,$(\'#note\').height() + $(\'#note_submit\').height())', 1);
           <% } %>

        var timerID=null;
        function delayed(delay, fn)
        {
            if (window.timerID)
                clearTimeout(window.timerID);
            window.timerID = setTimeout(fn, delay);
        }
        function doFilter(deze)
        {
            var deze = $("#autofilter");
            var valThis = deze.val().toLowerCase();
            $('#mldHistorieList table.fcltblocktab>tbody>tr.mldhandlingdiv,tr.mldhandlinghead').each(function(){
                var text = $(this).text().toLowerCase();
                var moretext = ($(this).find("span.rsTruncmore").attr('resttxt')||"").toLowerCase();
                $(this).toggle(text.indexOf(valThis) > -1 || moretext.indexOf(valThis) > -1);
           });
        }

        if ($('#mldHistorieList table.fcltblocktab>tbody>tr').length > 12)
        {
            $("#mldHistorie .fcltblockhead").append("<input id='autofilter' type='text' placeholder='"+L("lcl_autofilter")+"'>");
            $("#autofilter")
                .click(function (e) {e.stopPropagation()})
                .keyup(function(e){
                    if (e.which == 27) {
                        $("#autofilter").val("");
                    }
                    delayed(200, doFilter);
                });
        }
      });
    </script>
  </head>

  <body id="showbody">
<%
    function fnPerslidNaamFull(oRs)
    {
        if (!oRs("prs_perslid_key").Value) return "";
        if (outputmode != 0)
            return safe.html(oRs("prs_perslid_naam_friendly").Value);

        if (oRs("prs_perslid_key").Value == user_key) {
            var html = "<span class='self'>"
                     + safe.html(oRs("prs_perslid_naam_friendly").Value)
                     + "</span>";
        } else {
            var html = "<span class='details' onclick='persoonDetails(event,"+ oRs("prs_perslid_key").Value +")'>"
                     + safe.html(oRs("prs_perslid_naam_friendly").Value)
                     + "</span>";
        }
        return html;
    }
//({ icon: "page_refresh.png", title: L("lcl_refresh"), action: "FcltMgr.reload()"
    var refresher = '&nbsp;<img class="details" id="refresh" src="../Pictures/page_refresh.png" title="' + L("lcl_refresh") + '" onclick="FcltMgr.reload()">'
    BLOCK_START("mldHistorie",  L("lcl_status_details") + refresher);

        sql = "SELECT n.mld_melding_note_aanmaak"
            + ",      n.mld_melding_note_key"
            + ",      pf.prs_perslid_key"
            + ",      pf.prs_perslid_naam_friendly"
            + ",      n.mld_melding_note_omschrijving"
            + ",      mld_melding_note_flag"
            + ",      NULL fac_srtnotificatie_code"
            + "  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;
        var sqls = [sql];

        if (S("mld_merge_notes_and_tracking") == 1 && tracking)    // tracking info erbij?
        {
            var sql = "SELECT tr.fac_tracking_datum"
                    + "     , tr.fac_tracking_key"
                    + "     , tr.prs_perslid_key"
                    + "     , pf.prs_perslid_naam_friendly"
                    + "     , tr.fac_tracking_oms"
                    + "     , NULL mld_melding_note_flag"
                    + "     , str.fac_srtnotificatie_code"
                    + "  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)
        }
        sql = "SELECT * FROM ("+ sqls.join(" UNION ") + ") ORDER BY 1"

    var oRs = Oracle.Execute(sql);
    var lasttime = null;
    var lastuser = null;
    while(!oRs.Eof)
    {
        var thisuser = oRs("prs_perslid_naam_friendly").Value;
        var prs_key = oRs("prs_perslid_key").Value;
        var thistime = new Date(oRs("mld_melding_note_aanmaak").Value);
        var timestr = toTimeString(thistime);
        var srtnoti = oRs("fac_srtnotificatie_code").Value;
        var note_oms = oRs("mld_melding_note_omschrijving").Value;
        var fullname = fnPerslidNaamFull(oRs);
        var last_note_key = oRs("mld_melding_note_key").Value;
        var note_zichtbaar = oRs("mld_melding_note_flag").value == 1;
        oRs.MoveNext();
        var LastIsSelfNote = oRs.Eof && user.isCollega(prs_key) && !srtnoti;

        // 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 ((lastuser != thisuser || !lasttime || thistime.midnight() > lasttime.midnight()) && thisuser != null )
        {
            Response.Write("<tr class='mldhandlinghead'><td colspan='2'>");
            if (fullname != "") {
                Response.Write("<div class='mldhandlinghead'>"+L("lcl_status_behandelheader").format(toTimeString(thistime),
                                                                                              toDateString(thistime, false, true),
                                                                                              fullname)+"</div>");
            } else {
                // zal maar sporadisch voorkomen
                Response.Write("<div class='mldhandlinghead'>"+L("lcl_status_behandelheaderanonym").format(toTimeString(thistime),
                                                                                              toDateString(thistime, false, true))+"</div>");
            }
            Response.Write("</td></tr>");
        }
        else
        {
            if (lasttime && (thistime.getTime() - lasttime.getTime()) < 1000 * 60 * 5)
                timestr = ""; // Binnen 5 minuten onderdrukken
        }
        if (LastIsSelfNote && last_note_key == note_key)
            break; // uit de while-loop
        lasttime = thistime;
        if (thisuser != null)
            lastuser = thisuser;   // de laatste echte user

        var safehtml = "";
        if (note_oms) // Notitie of tracking met opgeslagen tekst
        {
            safehtml = safe.fclthtml(note_oms, true);
        }
        else if (srtnoti)
            safehtml = status.getsrtnotificatietext(srtnoti); // default tracking tekst

        if (srtnoti)
        {
            if (srtnoti == 'MLDUPD')
            {
                var arr = safehtml.split("<br>");
                arr.shift(); // Verwijder de tekst 'Melding xxx is gewijzigd'
                for (var i = 0; i < arr.length; i++) // Eerste woord tot ':' vet maken
                {
                    arr[i] = arr[i].replace(/^([\w]+)\:/, "<span class='mldhandlingfield'>$1:</span>")
                }
                safehtml = arr.join("<br>");
            }
            Response.Write(("<tr class='mldhandlingdiv'><td class='mldhtime'>{0}</td><td"+(thisuser == null ? " class='system'" : "")+">{1}</td></tr>").format(timestr, safehtml));
        }
        else // notitie
        {
            var edittm = timestr;
            var cls = '';
            if (LastIsSelfNote)
            {
                edittm = "<img src='../pictures/wijzigen.png' onclick='mld_notechange(" + last_note_key + ")' class='details' title='" + L("lcl_change") + "'></img>";
                var cls = " mldnoteedit";
            }
            Response.Write("<tr class='mldhandlingdiv'><td class='mldhtime " + cls + "'>{0}</td><td class='mldhandlingnote {1}'>{2}</td></tr>".format(edittm, (note_zichtbaar?"note_fe_visible":"note_fe_hidden"), safehtml));
        }
        // De MoveNext hebben we al eerder gehad
    }
    oRs.Close()

// == Verder met de nieuwe/bestaande notitie
    var note_oms = "";
    var note_zichtbaar = (mld_info.fenotes & 1);
    if (note_key > -1)
    { // Bestaande note: gegevens uit record gebruiken.
      sql = "SELECT mld_melding_note_omschrijving"
          + "     , mld_melding_note_flag"
          + "  FROM mld_melding_note"
          + " WHERE mld_melding_note_key = " + note_key;
      var oRs = Oracle.Execute(sql);
      note_oms = oRs("mld_melding_note_omschrijving").value;
      note_zichtbaar = oRs("mld_melding_note_flag").value == 1;
    }

    // Bron van verwarring maar: als het een eigen melding is dan ben je zelf de FE-user van die melding
    // Dan is het heel onlogisch als je het vinkje zou kunnen uitzetten. Disablen we dan ook effectief.
    if (eigenMelding)
      note_zichtbaar = true;

   if (note_key < 0) { %>
        <tr><td colspan='2'><div class='mldhandlinghead'><%=L("lcl_mld_note_new")%>:<span class='mldgotop details' onclick='if (parent) parent.scrollTo(0,0)'>^Top</span></div></td></tr>
<% } %>
    <tr><td></td><td>
      <div class='mldhandlingdiv'>
        <form name=u2 method=post action="mld_edit_note_save.asp?mld_key=<%=mld_key%>&urole=<%=urole%>&note_key=<%=note_key%>">
          <textarea id='note' name='note' class='fldtxt' rows='4' cols='80' maxlength='4000'><%=safe.textarea(note_oms)%></textarea>
<%
      if (mld_info.fenotes & 2)
      {
        if (note_key == -1 && !eigenMelding)
          RWCHECKBOXTR("zichtbaarFE", "fldcheck", "<nobr>" + L("lcl_mld_zichtbaar_FE") + "</nobr>", note_zichtbaar, { boxfirst: true } );
        else
          Response.Write("<tr><td></td><td>{0}: {1}</td></tr>".format(L("lcl_mld_zichtbaar_FE"), note_zichtbaar?L("lcl_Yes"):L("lcl_No")));
      }
      IFACE.FORM_END();
%>
    </form></td></tr>
<%
      buttons = [{ title: L("lcl_submit"), action: "note_submit()", id: "note_submit"}];

      //if (LastIsSelfNote && note_key < 0)
      //{
      //  buttons.push({title: L("lcl_change"), icon: "wijzigen.png", action: "mld_notechange(" + last_note_key + ")", id: "bedit_mld_note"});
      //}
      //else
      if (note_key > 0)
        buttons.push({title: L("lcl_cancel"), icon: "undo.png", action: "note_submit_callback()"});
      Response.Write("<tr><td colspan='2'><div style='float:left'>");
      CreateButtons(buttons);

    BLOCK_END();
%>
</body>
</html>
