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

    File:               shared/Bijlagenform.asp
    Description:        Toon de bijlagen bij een entiteit
    Parameters:
        key             ALG_RUIMTE_KEY of ...
        Module          "ALG" of "CNT" of ...
                        of "FGII" om DWF bestanden te uploaden naar S("fg_dwf_path")/concept
                        of "FGIIV" om DWF bestanden te uploaden naar S("fg_dwf_path")/vlucht
                        of "FGIIS" om DWF bestanden te uploaden naar fg_symbols_path
                        of "FGIIP" om DWF bestanden te uploaden naar S("fg_dwf_path_prj")/<scenario_key>
                        of "INSPH" om JPG bestanden te uploaden naar cust/photos/INS
                        of "RESPH" om JPG bestanden te uploaden naar cust/photos
        Kenmerk_key     ALG_KENMERK_KEY of ...

        DoDelete        optioneel: bestandsnaam om te verwijderen
        Reado           optioneel: readonly
        encrypt         optioneel: met name 'E' voor encrypted
    Context:            Binnen ModalForm.asp als gebruiker knopje 'Bijlagen'
                        drukt van een flexkenmerk type 'F'/'E'/'M'
                        en/of: self-submit bij verwijderen bestand
                        en/of: FGII specifiek DWF bestanden folder
    Note:               Al de FG-varianten worden altijd oplopend op bestandsnaam gesorteerd.
                        Met TAMPER bescherming!
    TODO: pMulti, Reado en encrypt zelf bepalen uit key, Module, en Kenmerk_key, ach, we hebben tamper bescherming

*/ %>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="./flexfiles.inc" -->

<%
protectQS.verify(); // tamper check

// key of folder wordt doorgegeven
var pKey = getQParamInt("key", -1);
var pNiveau = getQParamSafe("niveau", "");

var pModule = getQParamSafe("module");
var pKenmerk_key = getQParamInt("kenmerk_key", -1);
var pMulti = getQParamInt("multi", 0) == 1;
var pReado = getQParamInt("reado", 0) == 1;

var showFilter = getFParam("showFilter", ""); // zoek mogelijkheid binnen lijst bestanden
var pDoDelete  = getQParam("DoDelete", "");

var transitParam = buildTransitParam(["key", "module", "niveau", "kenmerk_key", "encrypt", "extFilter", "pregexp", "showFilter", "reado", "multi", "tmpfolder"]);

params = flexProps(pModule, pKey, String(pKenmerk_key), pNiveau);

__Log("Zoeken bestanden onder " + params.AttachPath);

if (pDoDelete != "")
  DeleteFile(params.AttachPath + "/" + safe.filename(pDoDelete));

function OpenFlexFile(fname)
{
  var s = "../shared/BijlagenStream.asp"
  s += "?filename=" + Server.URLencode(fname)
    + transitParam;
  return s;
}

if (params.extFilter)
{
  // extFilter="pdf,tiff" of "pdf tiff" of "pdf;tiff"
  var regFilter = params.extFilter;
  regFilter = regFilter.replace(/( |,|;)/g,"|"); // Altijd | karakter
  regFilter = ".*\\." + "(" + regFilter + ")$"; // er moet een punt voor en extensie is aan het einde
}

function MatchFile(fName)
{
  if (vFileName.toLowerCase() == 'web.config') // die nooit tonen
    return false;

  if (showFilter=="")
      return true;

  //return fName.match(new RegExp(showFilter,"i"));
  return fName.toUpperCase().indexOf(String(showFilter).toUpperCase()) >= 0;
}

// TODO: flexProps met een { getFiles: true } komt volgens mij ook een heel eind?
var fileArray = [];  // Array of file information
var fso = Server.CreateObject("Scripting.FileSystemObject")
if (fso.FolderExists(params.AttachPath))
{
  // Haal alle bijlagen voor deze actie op.
  var f = fso.GetFolder(params.AttachPath);
  var fc = new Enumerator(f.files);
  if (fc.atEnd())
  {
    // Autodelete lege folder?
    // fso.DeleteFolder(params.AttachPath, true);
  }

  function FileToAdd(vFileName, vDateStr, vFileSize)
  {
    this.vFileName = vFileName;
    this.vDateStr = vDateStr;
    this.vFileSize = vFileSize;
  }

  for (; !fc.atEnd(); fc.moveNext())
  {
    fsoFile = fc.item();
    vFileName = fsoFile.Name
    if (!MatchFile(vFileName))
      continue;

    vFileDate = fsoFile.DateLastModified
    vFileSize = fsoFile.Size
    vDateStr = vFileDate // Right("0" & DatePart("d",vFileDate),2) & "/" & Right("0" & DatePart("m",vFileDate),2) & "/" & DatePart("yyyy",vFileDate)
    fileArray.push(new FileToAdd(vFileName, vDateStr, vFileSize));
  }

  // Sorteer afhankelijk van de setting S("flexFilesOrdering") twee FileToAdd 'record's
  // Hierbij wordt geen onderscheid gemaakt tussen kleine of hoofd letters
  function nameSort(a, b)
  {
    if (a.vFileName.toLowerCase() > b.vFileName.toLowerCase())
       if (S("flexFilesOrdering") == 0) return 1;
       else return -1;
    if (a.vFileName.toLowerCase() < b.vFileName.toLowerCase())
       if (S("flexFilesOrdering") == 0) return -1;
       else return 1;
    return 0;
  }
  // plain sort
  function plainSort(a, b)
  {
    if(a.vFileName.toLowerCase() > b.vFileName.toLowerCase())
      return 1;
    if(a.vFileName.toLowerCase() < b.vFileName.toLowerCase())
      return -1;
    return 0;
  }

  if (params.pickfile)
    fileArray.sort(plainSort);  // Sorteer de bestanden simpel
  else
    fileArray.sort(nameSort);  // Sorteer de bestanden
}
%>

<HTML>
  <HEAD>
<%  FCLTHeader.Generate(); %>
    <script type="text/javascript">
      window.return_data = {};

      function FindFile(fname)
      {
        document.forms.finder.action="<%=protectQS.create("Bijlagenform.asp?x=x"+transitParam)%>";
        document.forms.finder.target="_self";
        document.forms.finder.submit();
      }

      function DeleteFile(fname, safeDeleteurl)
      {
        if (confirm(L("lcl_delete") + " " + fname + "?"))
        {
            window.location = safeDeleteurl;
        }
      }

      function doSubmitUpload()
      {
        if (document.forms.u2.imgfile.value == "")
            return false;
        // TODO: Met FireFox kun je clientside de max-grootte controleren via
        //       document.getElementById('imgfile').files[0].fileSize
        //       IE ondersteunt dat helaas niet dus nog niet geimplementeerd.
        <% if (params.extFilter) { %>
            if (!new RegExp("<%=safe.jsstring(regFilter)%>", "ig").test(document.forms.u2.imgfile.value))
            {
                alert(L("lcl_shared_file_ext_invalid_start") + "<%=safe.jsstring(params.extFilter)%>" + L("lcl_shared_file_ext_invalid_end"));
                return false;
            }
        <% } %>
        if (!new RegExp("<%=safe.jsstring(S("flexAllowedExt"))%>", "ig").test(document.forms.u2.imgfile.value))
        {
            alert(L("lcl_shared_file_ext_not_allowed"));
            return false;
        }
        // Controleer of de te uploaden bestand al bestaat.
        var uName = document.forms.u2.imgfile.value.replace(/\\/g,"/").split("/");
        var fName = uName[uName.length-1];
        var fTable = document.getElementById("filetable");
        var fRow = fTable.getElementsByTagName("A");
        for(var i=0; i<fRow.length; i++)
        {
          var tName = fRow[i].innerHTML.replace(/^\s+|\s+$/g,""); // spaties ervoor en erachter verwijderen.
          if (tName.toLowerCase() == fName.toLowerCase())
          {
            if (!confirm(L('lcl_shared_file_replace').format(tName)))
            {  return false;
            }
          }
        }
        //
        $("#uploading").show();
        FcltMgr.resized();

        document.forms.u2.action = "<%=protectQS.create("UploadForm_save.asp?action=insert"+transitParam)%>"
        document.forms.u2.submit();
      }
      function uploadDone()
      {
         window.location = "<%=protectQS.create("BijlagenForm.asp?x=x"+transitParam)%>";
      }

      function mailFile()
      {
        <%
        if (false)
        {
            var user = shared.random(16);
            var adres = user + "@sgf12.dijkoraad.local";
            var expire = new Date();
            expire.setMinutes(expire.getMinutes() + 10);
            var sql = "INSERT INTO fac_email_setting("
                    + "          fac_email_setting_user,"
                    + "          fac_email_setting_actiontype,"
                    + "          fac_email_setting_attachpath,"
                    + "          fac_email_setting_expire)"
                    + "       VALUES("
                    +            safe.quoted_sql(user) + ","
                    +            "2 ," // Bijlagen
                    +            safe.quoted_sql(params.AttachPath + "/") + ","
                    +            expire.toSQL(true) + ")";
            Oracle.Execute(sql);
        }
        %>
        prompt("Stuur voor <%=toDateTimeString(expire)%>  e-mail naar", "<%=safe.jsstring(adres)%>");
      }
      function Sluiten()
      {
        window.return_data.org_data=FcltMgr.dialogArguments();
        FcltMgr.closeDetail(window, return_data);
      }
    </script>
  </HEAD>

  <BODY class="modal" id="mod_bijlagen" onLoad="FcltMgr.resized();">
<%    if (params.pickfile || params.searchfile) // Zoekveldje erboven
      {
      // Eigen formpje vanwege andere encoding
%>
    <form name="finder" method="post" target="_self">
        <input type="text" name="showFilter" value="<%=safe.htmlattr(showFilter)%>">
        <input type="button" class='button' value="<%=L("lcl_search")%>" onClick="FindFile()">
    </form>
  <%    }
%>
    <FORM name="u2" method="post" enctype="multipart/form-data" target="hidFrameUpload">
<%    BLOCK_START("bijlagen",L("lcl_appendixes"));
%>
      <THEAD>
        <tr>
          <th><%=L("lcl_filename")%></th>
          <th style='text-align:right'><%=L("lcl_filedate")%></th>
          <th style='text-align:right'><%=L("lcl_filesize")%></th>
<%        if (!pReado)
          { %>
            <th><%=L("lcl_filedelete")%></th>
<%        } %>
        </tr>
      </THEAD>
      <TBODY id="filetable">
<%
          // De array fileArray is al goed gesorteerd.
          for (var i = 0; i < fileArray.length; i++)
          { %>
            <tr>
              <TD>
<%              if (params.pickfile)
                { //onclick levert tekening naam op
%>
                  <a onClick="FcltMgr.closeDetail(window, { filenaam: '<%=safe.jsstring(fileArray[i].vFileName)%>'})">
                    <%=safe.html(fileArray[i].vFileName)%>
                  </a>
<%              }
                else
                { %>
                  <div id="filename">
                  <a href="#" onclick='parent.window.open("<%=protectQS.create(OpenFlexFile(fileArray[i].vFileName)+"&doSave=1")%>").focus(); return false;'>
                    <%=safe.html(fileArray[i].vFileName)%>
                  </a>
                </div>
<%              } %>
              </TD>
              <TD align='right'><%=toDateTimeString(fileArray[i].vDateStr)%></TD>
              <TD align='right'><%=fileArray[i].vFileSize%></TD>
<%            if (!pReado)
              { %>
                <td align=center><img onClick="DeleteFile('<%=safe.jsstring(fileArray[i].vFileName)%>', '<%=safe.jsstring(protectQS.create("Bijlagenform.asp?DoDelete="+Server.URLEncode(fileArray[i].vFileName)+transitParam))%>')"
                    src='../pictures/delete.gif' title='<%=L("lcl_filedelete")%>'>
                </td>
<%            } %>
            </tr>
<%        }
        if (fileArray.length == 0 && !params.pickfile)
        { %>
          <tr>
            <td colspan="5"><%=L("lcl_nofiles")%></td>
          </tr>
<%      } %>
<%
      var buttons = [];
      if (!pReado && (pMulti || params.multi || fileArray.length == 0)) // Uploadknop erbij
      {
        buttons.push({ title: L("lcl_do_upload_image"), action: "doSubmitUpload()", singlepress: true, id: "btn_upload_submit"});
%>      <tr><td colspan="4">
          <label><%=L("lcl_upload_file")%>:</label>
          <% if (params.extFilter) { Response.Write("(" + safe.html(params.extFilter) + ")"); } %>
              <input type="file" name="imgfile" style="width: 95%" onchange="iface.button[this.value?'enable':'disable']('btn_upload_submit')">
          <div id="uploading" style="display:none">
                  Please wait...
          </div>
      </td></tr>
<%    } %>
      </tbody>
      <script type="text/javascript">
            window.return_data = { cnt: <%=fileArray.length%>, fileName: '<%=safe.jsstring(fileArray.length > 0? vFileName : "")%>'};
            FcltMgr.setCloseParams(window.return_data); // Zelfs als je kruisje gebruikt
            $(document).ready(function ()
            {
                iface.button.disable("btn_upload_submit")}
            );
      </script>
<%    BLOCK_END();
      // buttons.push({id: "addButton", title: "Mail naar", action: "mailFile()"});

      buttons.push({id: "closeButton", title: L("lcl_close_window"), action: "Sluiten()"});
      CreateButtons(buttons);
IFACE.FORM_END();
%>
    </FORM>
    <iframe src="../Shared/empty.html"
            name="hidFrameUpload"
            id="hidFrameUpload"
            style="display:none"></iframe>
</BODY>
</HTML>
