<% /*
     $Revision$
     $Id$

    File:           scaffolding_show.asp
    Description:    show detailed information of a usrrapx

    Parameters:     usrrap_key (usrrapx id)

    Context:
    Note:

*/ %>
<%
function scaffolding_show(model, scf_params)
{
    scf_params.show = scf_params.show || {};

    FCLTHeader.Requires({ plugins: ["jQuery"],
                               js: ["jquery-ui.js"]
                              })
    if ("requires" in scf_params.show)
        FCLTHeader.Requires(scf_params.show.requires);

    if (model.autfunction)
        var authparams = user.checkAutorisation(model.autfunction);
    else
        var authparams = { PRSreadlevel: -1, ALGreadlevel: -1, PRSwritelevel: -1, ALGwritelevel: -1 };

    var transit = scf_transit2url(scf_params);
    if (scf_params.incsetting)
        transit += "&" + scf_params.incsetting.joinfield + "=" + getQParamInt(scf_params.incsetting.joinfield);

    var key = getQParamInt("id");
    var xxx_params = { filter: { id: key } };
    var xxx_array = model.REST_GET(xxx_params);
    if (!xxx_array.length)
        shared.record_not_found();
    var xxx_data = xxx_array[0];

    for (var fld in model.fields)
    {
         var field = model.fields[fld];
        // Met friendlyname kun je het ook expliciet sturen (factuurschema bijvoorbeeld)
        if (field.friendlyname && !xxx_data.name)
        {
            xxx_data.name = field.foreign?xxx_data[fld].name:xxx_data[fld];
            if (typeof xxx_data.name == "date" || xxx_data.name instanceof Date)
                xxx_data.name = toDateString(xxx_data.name);
        }
    }

    if (key > 0)
    {
        var parent_key_array = [key];
        var sql = "";

        // Fac_audit_tabelkey's van de verwijderde parents vinden.
        if (model.table == "ins_tab_discipline")
        {
          sql = "SELECT ins_discipline_key"
              + "  FROM ins_tab_discipline"
              + " WHERE ins_discipline_omschrijving = " + safe.quoted_sql(xxx_data.name)
              + "   AND ins_srtdiscipline_key = (SELECT ins_srtdiscipline_key"
              + "                                  FROM ins_tab_discipline"
              + "                                 WHERE ins_discipline_key = " + key + ")"
              + "   AND ins_discipline_verwijder IS NOT NULL"
              + "   AND ins_discipline_key != " + key;
        }
        else if (model.softdelete)
        {
          sql = "SELECT x." + model.table + "_key"
              + "  FROM " + model.table + " x"
              + " WHERE x." + model.table + "_verwijder IS NOT NULL"
              + "   AND " + (model.fields.name.dbsa? model.fields.name.dbsa : model.fields.name.dbs) + " = " + safe.quoted_sql(xxx_data.name);
        }
        else if (model.fields.name && model.fields.name.dbs && xxx_data.name)
        {
          sql = "SELECT fac_audit_tabelkey"
              + "  FROM fac_audit"
              + " WHERE fac_audit_tabelnaam = " + safe.quoted_sql(model.table)
              + "   AND fac_audit_veldnaam = " + safe.quoted_sql(model.fields.name.dbs)
              + "   AND fac_audit_waarde_oud = " + safe.quoted_sql(xxx_data.name);
        }

        if (sql != "")
        {
          var oRs = Oracle.Execute(sql);
          while(!oRs.eof)
          {
            parent_key_array.push(oRs(0).Value);
            oRs.Movenext();
          }
          oRs.Close();
        }

        // Verwijder audit van de verwijderde parents.
        var wheres = ["(fac_audit_tabelnaam = " + safe.quoted_sql(model.table)
                       + " AND fac_audit_tabelkey IN (" + parent_key_array.join(",") + "))"];

        // Fac_audit_tabelkey's van de child audits vinden van de verwijderde en recente parents.
        if (model.table == "ins_tab_discipline") // disc_params ook meetellen
        {
            var sql = "SELECT ins_discipline_module"
                    + "  FROM ins_tab_discipline"
                    + " WHERE ins_discipline_key = " + key;
            var oRs = Oracle.Execute(sql);
            var module = oRs("ins_discipline_module").Value.toLowerCase();
            oRs.Close();
            if (module != "mrk" && module != "cht" && module != "faq")
            {
                var key_field = "ins_discipline_key";
                if (module != "ins")
                    key_field = "{0}_ins_discipline_key".format(module);
                var sql = "SELECT {0}_disc_params_key disc_params_key".format(module)
                        + "  FROM {0}_disc_params".format(module)
                        + " WHERE {0} IN ({1})".format(key_field, parent_key_array.join(","));
                var oRs = Oracle.Execute(sql);
                var child_key_array = [];
                while(!oRs.eof)
                {
                  child_key_array.push(oRs("disc_params_key").Value);
                  oRs.Movenext();
                }
                oRs.Close();

                wheres.push("(fac_audit_tabelnaam = " + safe.quoted_sql("{0}_disc_params".format(module))
                              + (child_key_array.length? " AND fac_audit_tabelkey" + " IN (" + child_key_array.join(",") + ")" : " AND 1=0") + ")");
            }
        }
        else if (model.audit && model.audit.childaudit && model.audit.childaudit.sql)
        {
          var sql = model.audit.childaudit.sql.format(parent_key_array.join(","), parent_key_array.join("','"));
          var oRs = Oracle.Execute(sql);
          var child_key_array = [];
          while(!oRs.eof)
          {
            child_key_array.push(oRs(0).Value);
            oRs.Movenext();
          }
          oRs.Close();

          wheres.push("(fac_audit_tabelnaam = '" + model.audit.childtable + "'"
                        + " AND fac_audit_tabelkey IN (" + sql + "))");
        }
        var sql = "SELECT COUNT(*)"
                + "  FROM fac_audit"
                + " WHERE (" + wheres.join(" OR ") + ")";
        var oRs = Oracle.Execute(sql);
        var cnt = oRs(0).Value;
        oRs.Close();
    }

    if ("hook_pre_show" in model)
        model.hook_pre_show(xxx_data, model.fields, scf_params);
    %>

    <html>
      <head>
    <%  FCLTHeader.Generate(); %>
        <script>
            <% if ("name" in xxx_data) { %>
              FcltMgr.setTitle("<%=safe.jsstring((xxx_data.name||"") + ' (' + model.record_title) + ')'%>", {hot:false});
            <% } %>

            function xxx_change()
            {
              if (FcltMgr.startEdit(window))
              {
                window.location.href = "<%=scf_params.this_fullpath%>?mode=edit&id=<%=key%><%=transit%>";
              }
            }

            function scf_clone()
            {
                var url = "<%=scf_params.this_path%>?mode=wrap&scf_clone=1&id=<%=key%><%=transit%>"
                FcltMgr.openDetail(url);
            }

            function xxx_delete()
            {
              FcltMgr.confirm('<%=safe.jsstring(L("lcl_scf_confirm_delete").format(model.record_title, xxx_data.name || xxx_data.id))%>',
                { oktekst: L("lcl_delete") },
                function() {
                  var data = {
                      key: "<%=key%>"
                  };
                  <% protectRequest.dataToken("data"); %>
                  $.post("<%=scf_params.this_fullpath%>?mode=delete&id=<%=key%><%=transit%>",
                      data,
                      FcltCallbackClose,
                      "json");
              });
            }
            function scf_history()
            {
              <%
                  var url = "appl/mgt/fac_audit.asp?mode=list&table={0}&record={1}".format(model.table, parent_key_array.join(","))
                          + (model.audit && model.audit.childtable
                            ? "&childtable={0}".format(model.audit.childtable)
                            : "");
                  var proturl = protectQS.create(url);
              %>
              FcltMgr.openDetail("<%= proturl %>", L("lcl_history") + " " + "<%=safe.jsstring(model.record_title) %>");
            }

            var url = "<%=scf_params.this_fullpath%>?mode=api2&format=html&id=<%=key%><%=transit%>";
            <%
            if (model.includes)
            {
                allincludes = [];
                for (var inc in model.includes)
                    if (model.includes[inc].enable_update && !model.includes[inc].notransport) {
                    %>
                        url += "&include=<%=safe.url(inc)%>";
                    <%
                }
            }
            %>
            function scf_export(key)
            {
                FcltMgr.windowopen(url); // Doet automatisch een GET
            }

            function scf_print()
            {
                FcltMgr.windowopen("<%=scf_params.this_fullpath%>?mode=print&id=<%=key%><%=transit%>");
            }
        </script>
      </head>
      <body class="showmode">
    <%  var buttons = [];
        if (user.has("WEB_FACFAC") && model["REST_POST"])
            buttons.push({ title: L("lcl_scf_transport"), action: "scf_export()", icon: "fa-brackets-curly" });

        if (key > 0 && model["REST_POST"] && !scf_params.show.no_clone)
            buttons.push({ title: L("lcl_scf_clone"), action: "scf_clone()", icon: "fa-copy" });

        if (key > 0 && cnt > 0)
        {
            buttons.push({title: L("lcl_history") + " ({0})".format(cnt), action:"scf_history()", icon: "fa-history", id: "btn_scf_history" });
        }

        if (scf_params.show.buttons)
        {
          for (var i = 0; i < scf_params.show.buttons.length; i++)
          {   // Als je een action opgeeft *zonder* haakjes voegen we automagisch de key en model toe
              if (scf_params.show.buttons[i].action.indexOf("(") < 0)
                  scf_params.show.buttons[i].action += "(" + key + ", '" + (model.terms ? model.terms : model.table) + "')"
              buttons.push(scf_params.show.buttons[i]);
          }
        }

        if (model.autfunction_del)
          var authparams_del = user.checkAutorisation(model.autfunction_del, true);
        else
          var authparams_del = authparams;

        if (model["REST_PUT"]) // TODO: Eventueel autfunction testen?
        {
          buttons.unshift({title: L("lcl_change"), action: "xxx_change()", icon: "fa-fclt-edit" });
          if (model["REST_DELETE"] && authparams_del && authparams_del.PRSwritelevel < 9 && authparams_del.ALGwritelevel < 9)
            buttons.push({title: L("lcl_delete"), action: "xxx_delete()", icon: "fa-trash-alt" });
        }
        // if stylesheet gevonden
        var fso = Server.CreateObject("Scripting.FileSystemObject");
        var xslfile = Server.MapPath(custpath + "/xsl/scf_" + model.table + ".xsl");
        if (model.print.xmlnode || fso.FileExists(xslfile))
            buttons.push({ icon: "fa-print", title: L("lcl_print"), action: "scf_print()" });
        else
            __Log("Geen printknop want {0} is niet gevonden".format(xslfile));

        if (model.edit.modal|| scf_params.edit && scf_params.edit.modal)
        {                     // het is dan vreemd dat we hier zijn. Expliciete showmode
            buttons = [];     // zoals fac_usrtab record vanuit materiaal.
        }
        SUBFRAME_START();
        IFRAMER_HEADER(model.record_title, buttons);
            var fld_arr_all = [];
            for (var fld in model.fields)
            {
                var field = model.fields[fld];
                if (!field.hidden_fld)
                    fld_arr_all.push(fld);
            }

            var scf_layout = scf_create_layout_list(model, scf_params, fld_arr_all);
            //
            // Sorteer de velden volgens gegeven layout.
            for (var blk in scf_layout)
            {
                var blk_obj = scf_layout[blk];
                var blk_params = { icon: blk_obj.icon,
                                   extraclass: (blk_obj.extraclass ? blk_obj.extraclass : ""),
                                   ishtmlsafe: blk_obj.ishtmlsafe,
                                   hidden: blk_obj.hidden,
                                   buttons: blk_obj.buttons
                                 };
                BLOCK_START(blk_obj.blockid, blk_obj.label, blk_params);
                    for (var fld_nr in blk_obj.fields)
                    {
                        var fld = blk_obj.fields[fld_nr];
                        if (inArray(fld, fld_arr_all))
                        {
                            var field = model.fields[fld];
                            if (field.foreign && field.foreign.emptyisrealvalue)
                            {
                                model.fields[fld].foreign.readonly = true;
                                scf_RWFIELDTR(model, fld, xxx_data[fld], key);
                            }
                            else if (field.LOV && field.emptyisrealvalue)
                            {
                                model.fields[fld].readonly = true;
                                scf_RWFIELDTR(model, fld, xxx_data[fld], key);
                            }
                            else
                                scf_ROFIELDTR(model, fld, xxx_data[fld], key);
                        }
                    }
                BLOCK_END();
            }
        SUBFRAME_END();
    %>
      </body>
    </html>
<%
}
%>