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

    File:               shared/queuemail.asp
    Description:        Zet een e-mail notifatie in de queue. Die wordt later verstuurd
                        door PutNotification.exe
    Parameters:         defemail_key met key van de user waar de mail naar toe moet
                        defemail (rechtstreeks het e-mail adres)
    Context:
    Note:


*/ %>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="../Shared/selector.inc" -->
<!-- #include file="../Shared/persoonselector.inc" -->
<!-- #include file="../Shared/bedrijfselector.inc" -->
<!-- #include file="../Shared/kenmerk_common.inc" -->
<!-- #include file="../Shared/FlexFiles.inc" -->
<!-- #include file="../mld/mld.inc" -->

<%
protectQS.verify(); // tamper check
FCLTHeader.Requires({ plugins:["jQuery"],
                      js: []
                    });

var defaultemail = getQParam("defemail","");
var defemail_type = getQParam("defemail_type", "P");
var defemail_key = getQParamInt("defemail_key", -1);

var pcode = getQParamSafe("pcode", "");
var pmodule = getQParamSafe("pmodule", "");
var pniveau = getQParamSafe("pniveau", "");
var pkey = getQParamInt("key", -1);
var subject = getQParam("subject", "");
var mailfrom = getQParamInt("mailfrom", 0) == 1;
var xkey = getQParamInt("xkey", -1);
var pshowcompany = getQParamInt("pshowcompany", 0) == 1;

// Ben ik voor deze module FO, en mag ik dus attachments selecteren?
var xfunc = user.func_enabled("*", null, null, user_key);
var iamfo = false;
var iambo = false;
switch (pmodule)
{
  case "RES": iamfo = xfunc.canWrite("WEB_RESFOF"); break;
  case "MLD": iamfo = xfunc.canWrite("WEB_MLDFOF"); iambo = xfunc.canWrite("WEB_MLDBOF"); break;
  case "BES": iamfo = xfunc.canWrite("WEB_BESFOF"); break;
  case "PRS": iamfo = xfunc.canWrite("WEB_PRSSYS"); break;
}

function bestandenlijst(pmodule, pniveau, pkey)
{   // flexfiles.inc/flexProps() niet bruikbaar omdat die niet over kenmerken heen kan zoeken
    var bestandlijst = [];
    if (pmodule && pniveau)
    {
        var vSubfolder = pmodule + "/" + subfolderKey(pniveau, pkey);
        var vAttachPath = S("flexFilesPath")+ "/" + vSubfolder;

        var fso = new ActiveXObject("Scripting.FileSystemObject");
        if (fso.FolderExists(vAttachPath))
        {
            var f1 = fso.GetFolder(vAttachPath);
            var vmap = new Enumerator(f1.subFolders);
            for (; !vmap.atEnd(); vmap.moveNext()) // Doorloop alle kenmerken
            {
                var f2 = fso.GetFolder(vAttachPath + "/" + vmap.item().Name);
                var vfile = new Enumerator(f2.files);
                for (; !vfile.atEnd(); vfile.moveNext()) // Doorloop alle bestanden per kenmerk
                {
                    bestandlijst.push( { folder: vSubfolder,
                                         file: { kenmerkkey: vmap.item().Name,
                                                 bestandnaam: vfile.item().Name,
                                                 size: vfile.item().Size
                                               }
                                       }
                                     );
                }
            }
        }
    }
    return bestandlijst;
}

// Bij MLD worden ook de bestanden van de 'parents' aangeboden
function bestandenlijstALL(pmodule, pniveau, pkey)
{
    var bestandlijst = bestandenlijst(pmodule, pniveau, pkey);
    if (pmodule == "MLD")
    {
        var sk = pkey;
        var mk = pkey;
        while (true)
        {
            var sql = "SELECT mld_melding_start_key"
                    + "  FROM mld_melding"
                    + " WHERE mld_melding_key = " + mk;
            var oRs = Oracle.Execute(sql);
            var sk = oRs("mld_melding_start_key").Value;
            if (!sk || sk == mk)
                break; // klaar
            bestandlijst = bestandlijst.concat(bestandenlijst(pmodule, pniveau, sk));
            mk = sk;
        }
    }
    return bestandlijst
}


%>
  <html>
    <head>
<%    // Bepaal default email
      if (defemail_key > 0)
      {
        if (defemail_type == "C")
        {
          var sql = " SELECT replace(c.prs_contactpersoon_email, ' ', '') AS email"
                  + " FROM prs_contactpersoon c"
                  + " WHERE c.prs_contactpersoon_key = " + defemail_key;
        }
        else if (defemail_type == "B")
        {
          var sql = " SELECT replace(b.prs_bedrijf_email, ' ', '') AS email"
                  + " FROM prs_bedrijf b"
                  + " WHERE b.prs_bedrijf_key = " + defemail_key;
        }
        else if (defemail_type == "P")
        {
          var sql = " SELECT replace(p.prs_perslid_email, ' ', '') AS email"
                  + " FROM prs_perslid p"
                  + " WHERE p.prs_perslid_key = " + defemail_key;
        }
        oRs = Oracle.Execute(sql);
        defaultemail = oRs("email").Value;
        oRs.Close();
      }

      FCLTHeader.Generate();
%>
      <script type='text/javascript'>
        jQuery(document).ready(function()
            {
                $("textarea").resize(function () { FcltMgr.resized(window) } );
                $("textarea").autogrow();
            });

        jQuery(function()
                   {
                        FcltMgr.fixActiveelementError();
                        $("#emails").focus();
                   });

<%      if (pshowcompany)
        { %>
          function onChangeComp()
          {
            // Vul email van bedrijf in
            $("#emails").val($("#emailbedrijf").val());

            // Wis Persoon
            sgPerson.setValue(-1, "");
          }
<%      } %>

        function onChangePerson()
        {
          // Vul email van persoon in
          if ($("#emailpersoon").val())
          {
            var current_val = ($("#emails").val() != "" ? $("#emails").val() + "; " : "");
            $("#emails").val(current_val + $("#emailpersoon").val());
            $("#sName_key_show").val("");
            $("textarea").autogrow();
          }

<%        if (pshowcompany)
          { %>

            // Wis Bedrijf
            sgComp.setValue(-1, "");
<%        } %>
        }

        function queueSubmit()
        {
            // Standaard checks op verplichte velden, datum formaat, numeriek en float formaat, currency formaat.
            if (!validateForm("u2"))
                return false;

            if (!new RegExp("<%=safe.jsstring(S("email_regexp"))%>", "ig").test($("#emails").val()))
            {
                alert(L("lcl_invalid_email"));
            }
            else
            {
<%
                if (pcode == "MLDMAI" || pcode == "ORDMAI")
                {
                    if (pcode == "MLDMAI")
                        var save_note_url = "../mld/mld_edit_note_save.asp?mld_key=" + pkey;
                    if (pcode == "ORDMAI")
                        var save_note_url = "../mld/opdr_edit_note_save.asp?opdr_key=" + pkey;
%>
                    var data = { note: $("#notes").val(),
                                 zichtbaarFE: ($("#zichtbaarFE").prop("checked") ? "on" : "off")
                               };
                    <% protectRequest.dataToken("data"); %>
                    $.post("<%=save_note_url%>",
                           data,
                           FcltCallbackAndThenAlways(queueSubmitCallback),
                           "json");
                    return true; // disable button
<%
                }
                else
                {
%>
                    var data = { success: true,
                                 note_key: <%=xkey %>
                               };
                    queueSubmitCallback(data);
<%
                }
%>
            }
        }

        function queueSubmitCallback(data)
        {
            if (data.note_key > -1 )
            {
                $("#xkey").val(data.note_key);
            }

            var xurl = "queuemail_save.asp?key=<%=pkey%>&pcode=<%=pcode%>&pmodule=<%=pmodule%>&pniveau=<%=pniveau%>";
            $.post(xurl,
                   $("[name=u2]").serialize(),
                   FcltCallbackAndThenAlways(queueMailClose),
                   "json");
        }

        function queueMailClose(data)
        {
            var emails = $("#emails").val();
            var maillist = "\n" + emails.replace(/\;/g, "\n");

            FcltMgr.closeDetail(window, { emails: maillist,
                                          key: "<%=pkey%>" });
        }

        function queueCancel()
        {
          FcltMgr.closeDetail(window, { cancel: true, key: "<%=pkey%>" } );
        }

        function chooseEmailCallbackRefresh(data)
        {
          alert(data.email);
        }

      </script>
    </head>

    <body class="modal" id="mod_queuemail">
      <div id="email">
        <form name="u2" id="u2" method="post">
            <input type="hidden" id="orgsubject" name="orgsubject" value="<%=safe.htmlattr(subject)%>">
            <input type="hidden" id="xkey" name="xkey" value="<%=xkey%>">
<%
          BLOCK_START("emailInput", subject);

              if (mailfrom && S("replyaddress"))
              {
                // <!-- Namens -->
                var sql = "SELECT prs_perslid_email"
                        + "     , prs_perslid_email"
                        + "     , 1"
                        + "  FROM prs_perslid"
                        + " WHERE prs_perslid_key = " + user_key
                        + "   AND prs_perslid_email IS NOT NULL"
                        + " UNION "
                        + "SELECT " + safe.quoted_sql(S("replyaddress"))
                        + "     , " + safe.quoted_sql(S("replyaddress"))
                        + "     , 2"
                        + "  FROM DUAL"
                        + " ORDER BY 3"
                FCLTselector("namens",
                             sql,
                             { label: L("lcl_noti_email_namens") }
                            );
              }

              // <!-- Naam -->
              if (S("show_perslidselector_by_mail"))
              {
                FCLTpersoonselector("sName_key",
                                    "sgPerson",
                                    { perslidKey: -1,
                                      label: L("lcl_name"),
                                      onChange: "onChangePerson",
                                      trclass: "more",
                                      filtercode: "MAIL",
                                      extracode: "E",
                                      extraParamField: "emailpersoon",
                                      whenEmpty: L("lcl_search_generic")  // want filter
                                    });
              }
                // <!-- Bedrijf -->
            if (pshowcompany)
            {
                FCLTbedrijfselector("sComp_key",
                                    "sgComp",
                                    { companyKey: -1,
                                      label: L("lcl_company"),
                                      onChange: "onChangeComp",
                                      extracode: "E",
                                      trclass: "more",
                                      extraParamField: "emailbedrijf",
                                      whenEmpty: L("lcl_search_generic")
                                    });

            }
            RWTEXTAREATR("emails",
                         "fldmaillist required",
                         L("lcl_noti_sendto"),
                         safe.htmlattr(defaultemail),
                         {html: "rows='2' cols='60'"} // kan hier nog iets een nieuwe regel forceren?
                        );

%>

            <tr>
              <td class="label"><label for="subject"><%=L("lcl_noti_sendsubject")%></label></td>
              <td>
                <input class="fldsubject" type="text" id="subject" name="subject" value="<%=safe.htmlattr(subject)%>">
              </td>
            </tr>
<%
            // Notitie
            if (pcode == "MLDMAI" || pcode == "ORDMAI")
            {
                RWTEXTAREATR("notes",
                             "fldmaillist",
                             L("lcl_mld_note"),
                             "",
                             {html: "rows='2' cols='60'"}
                            );
                if (pcode == "MLDMAI")
                {
                    pkey

                    var mld_info = mld.mld_melding_info(pkey);
                    var mfe = mld.func_enabled_melding (pkey);
                    var eigenMelding = user_key == mld_info.melder_key || user.isCollega(mld_info.melder_key);
                    var note_zichtbaar = (mld_info.fenotes & 1);
                    var note_zichtbaar = (eigenMelding ? true : (mld_info.fenotes & 1) );

                    if (mld_info.fenotes & 2 && !mfe.haveOnlyFErights)
                    {
                        if (!eigenMelding)
                            RWCHECKBOXTR("zichtbaarFE", "fldcheck", "<nobr>" + L("lcl_mld_zichtbaar_FE") + "</nobr>", note_zichtbaar, {html: ""});
                        else
                            ROCHECKBOXTR("fldmldzichtbaarFE", "<nobr>" + L("lcl_mld_zichtbaar_FE") + "</nobr>", note_zichtbaar, {html: "" });
                    }
                }
            }
%>


            <tr><td><br/></td></tr>
<%
            // Bijlagen meesturen.
            if (iamfo || iambo)
            {
                checklist = bestandenlijstALL(pmodule, pniveau, pkey);
                for (i=0; i<checklist.length; i++)
                {
                    var label = (i==0 ? "<label>" + L("lcl_appendixes") + ":</label>" : "&nbsp;");
                    var fid   = "kmnr"+i;
                    var fnaam = checklist[i].file.bestandnaam;
                    var sz = (Math.ceil(checklist[i].file.size / 1024));
%>
                    <tr>
                      <td><%=label%></td>
                      <td>
                        <% CHECKBOX("fldafr", fid, false) %>
                        <label for="<%=fid%>"><%="{0} ({1} kB)".format(safe.html(fnaam), sz)%></label>
                      </td>
                    </tr>
<%
                }
            }
          BLOCK_END();
          var buttons =  [ {title: L("lcl_noti_send"), id: "btn_send", icon: "email.png", action: "queueSubmit()", singlepress: true },
                           {title: L("lcl_cancel"), id: "btn_cancel", icon: "undo.png", action: "queueCancel()" }];
          CreateButtons(buttons);
          var buttons =  [ {title: L("lcl_accept"), icon: "accept.png", action: "mld_accept()", singlepress: true, id: "btn_accept_submit"  },
                       {title: L("lcl_cancel"), icon: "cancel.png", action: "mld_cancel()" } ];

IFACE.FORM_END();
%>
        </form>
      </div>
    </body>
  </html>