<% /*
     $Revision$
     $Id$

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

    Parameters:     usrxxx_key (usrrapx id)

    Context:
    Note:

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

    FCLTHeader.Requires({ plugins: ["jQuery"],
                               js: ["jquery-ui.js", "jquery.timepicker-table.js", "multi.js"],
                              css: ["timePicker-table.css"]})

    if (scf_params.edit && "requires" in scf_params.edit)
        FCLTHeader.Requires(scf_params.edit.requires);
    if (model.edit && "requires" in model.edit)  // Voor het included model.
        FCLTHeader.Requires(model.edit.requires);

    var transit = scf_transit2url(scf_params);

    if (scf_params.incsetting)
        transit += "&" + scf_params.incsetting.joinfield + "=" + getQParamInt(scf_params.incsetting.joinfield);
    var cloning = getQParamInt( "scf_clone", 0 ) == 1;
    if (cloning)
        transit += "&scf_clone=1";

    if (scf_params.transit_qlist)
    {   // Toevoegen van niet-model gerelateerde Q-parameters.
        for (var i=0; i<scf_params.transit_qlist.length; i++)
        {
            var tp = scf_params.transit_qlist[i];
            transit += "&" + tp.name + "=" + tp.val;
        }
    }

    var key = getQParamInt("id", -1);
    var multi = getQParamInt("scf_multi", 0) == 1;
    if (multi)
    {
//        var keys = getQParamIntArray( "id" ); // Vanuit lijst/multi delete
        var xxx_data = {}; // TODO: vullen met waarden die in alle records gelijk zijn?
        scf_params.multicolumn = false;
        scf_params.scf_multi = true;
    }
    else if (key > 0)
    {
        user.auth_required_or_abort(model.REST_PUT || model.REST_DELETE);
        var xxx_params = { filter: { id: key }, cloning: cloning };
        xxx_params.for_edit = true; // dan wordt niet vertaald
        var xxx_array = model.REST_GET(xxx_params);

        if (!xxx_array.length)
            shared.record_not_found();
        var xxx_data = xxx_array[0];

        // Defaults vanuit url maken we readonly
        // Vooral bij includes wordt hier ook de parent_key verwijzing gezet
        var filter = shared.qs2json(model)
        for (var fld in model.fields)
        {
            var field = model.fields[fld];
            if (!model.REST_PUT) // Bij geen REST_PUT wordt *alles* readonly. Waarschijnlijk alleen delete dan.
                model.fields[fld].readonly = true;
        }
        // Uniques verwerken,
        // Die misbruiken we om een intelligentere 'Wilt U verwijderen' titel te kunnen maken
        // Koppeltabellen hebben namelijk geen 'name' veld en we gokken dan één van de uniques
        // interessant is
        for (var fld in model.fields)
        {
            var field = model.fields[fld];

            if (cloning && (field.clone === false || fld == "id"))
                xxx_data[fld] = field.defaultvalue;

            if (cloning && "module" in field && xxx_data[fld] && (field.typ == "symbol" && xxx_data[fld].match(/^fa-/) === null || field.typ == "file")) {
                xxx_data[fld] = copyLinkedFile(field.module, key, -1);
            }

            if (typeof field.clone == "function")
                xxx_data[fld] = field.clone(xxx_data);

            if (field.required && xxx_data[fld] == null)
                xxx_data[fld] = field.defaultvalue;

            if (field.uniquewith)
            {
                if (!xxx_data.name && !(fld in filter))
                {
                    xxx_data.name = xxx_data[fld].name;
                }
            }
            // 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);
            }
        }
    }
    else
    {
        user.auth_required_or_abort(model.REST_POST);
        var xxx_data = {};
        // Defaults vanuit url invullen
        // Bij includes wordt hier ook de parent_key verwijzing gezet
        var filter = scf_params.filter || shared.qs2json(model)
        for (var fld in model.fields)
        {
            var field = model.fields[fld];
            if (fld in filter)
            {
                xxx_data[fld] = filter[fld];
                if (field.typ == "date" || field.typ == "datetime")
                    xxx_data[fld] = new Date(parseInt(filter[fld],10));
                if (field.foreign)
                {   // name ook achterhalen. Voor includes is die waarschijnlijk ook wel te vinden
                    // in scf_params.orgmodel o.i.d. maar dit is doorgaans toch een heel goedkope query
                    var foreign = field.foreign;
                    if (typeof foreign == 'string')
                        foreign = foreignKeyTable(foreign);
                    var sqlf = "SELECT " + foreign.desc
                             + "  FROM " + foreign.tbl + " " + (foreign.alias||"")
                    if (foreign.where)
                        sqlf += " WHERE " + foreign.where + " AND ";
                    else
                        sqlf += " WHERE ";
                    sqlf += foreign.key + " = " + filter[fld];
                    var oRs = Oracle.Execute(sqlf);
                    if (!oRs.EOF)
                        xxx_data[fld] = { id: filter[fld], name: oRs(0).Value };
                    oRs.Close();
                }
                field.readonly = true;
            }
            else if ("defaultvalue" in field)
            {
                xxx_data[fld] = field.defaultvalue;
                if ("LOV" in field)
                {
                    var spl = api2.splitLOV(field.LOV);
                    xxx_data[fld] = { id: field.defaultvalue, name: spl[field.defaultvalue] };
                }
            }
        }
        // Uniques verwerken, bijvoorbeeld model_fac_gebruikersgroep
        for (var fld in model.fields)
        {
            var field = model.fields[fld];
            if (field.uniquewith)
            {
                var where = "{0} NOT IN (SELECT {1} FROM {2} WHERE {3} = {4} {5} {6})".format(field.foreign.key,
                                                                                          field.dbs,
                                                                                          model.table,
                                                                                      filter[field.uniquewith],
                                                                                      model.fields[field.uniquewith].dbs,
                                                                                      model.soft_delete?" AND " + model.soft_delete + " IS NULL":"",
                                                                                      model.soft_expire?" AND(" + model.soft_expire + " IS NULL OR " + model.soft_expire + " > SYSDATE)":""
                                                                                              )
                field.foreign.where = (field.foreign.where?field.foreign.where + " AND ":"") + where;
            }
        }

    }
    api2.setfieldlengths(model); // max lengtes bepalen

    if ("hook_pre_edit" in model && !multi)
        model.hook_pre_edit(xxx_data, model.fields, scf_params);
    else if ("hook_pre_multi_edit" in model && multi)
        model.hook_pre_multi_edit(xxx_data, model.fields, scf_params);

    var modal = multi || model.edit.modal || scf_params.edit && scf_params.edit.modal; // dan doen we een detailrecord altijd modal
    if (key < 0 && scf_params.edit && scf_params.edit.addmodal)
        modal = true;

    // In model_aut_idp_map is name een LOV, dus heeft weer een id en name.
    xxx_data.obj_name = (((typeof xxx_data.name === "object") && (xxx_data.name != null)) ? xxx_data.name.name : xxx_data.name) || xxx_data.id;

    %>

    <html>
      <head>
    <%  FCLTHeader.Generate(); %>
        <script>
          var scf_modalform = <%=(modal?1:0)%>;

          function scf_submit_callback(json)
          {
              if (json.success)
                  FcltMgr.closeDetail(window, json);
              else
                  iface.button.enable("btn_scf_submit");
          }

          async function scf_submit()
          {
            var params = { };
<% if (multi) { %>
            // Alleen de velden controleren waar het vinkje voor aan staat
            params.checkNot = [];
            $("input[type=text],input[type=checkbox],input[type=number],select").not("[name^=scf_multi]").each(function() {
                var thisname = $(this).attr("name");
                if (!thisname) { // Veel te ingewikkeld met datumvelden, die controleren we multi nooit
                    return;
                }
                var cb_name = "scf_multi_" + thisname;
                if (!$("input[name=" + cb_name + "]").is(":checked")) {
                    params.checkNot.push(thisname);
                }
            });
<% } %>
            if (!await validateForm("u2", params))
              return false;

            if (typeof pre_submit != "undefined")
            {
                if (!pre_submit( { isMulti: <%= multi?1:0 %>, isClone: <%= cloning?1:0 %>} ))
                    return false;
            }

            $.post($("form[name=u2]")[0].getAttribute("action"), $("[name=u2]").serialize(), FcltCallbackAndThenAlways(scf_submit_callback), "json");
            return true; // disable button
          }

          function scf_cancel()
          {
            FcltMgr.closeDetail(window, { cancel: true } );
          }

<% if (!multi && modal && key > 0) { %>
          function scf_history()
          {
            <%
                var url = "appl/mgt/fac_audit.asp?mode=list&table={0}&record={1}".format(model.table, key)
                var proturl = protectQS.create(url);
            %>
            FcltMgr.openDetail("<%= proturl %>", L("lcl_history") + " " + "<%=safe.jsstring(model.record_title) %>");
          }

          function scf_delete()
          {
            FcltMgr.confirm('<%=safe.jsstring(L("lcl_scf_confirm_delete").format(model.record_title, xxx_data.obj_name))%>',
                { fncancel: function() {
                    iface.button.enable("btn_scf_delete")
                  },
                  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");
                });
          }
<% } %>

          window.lastinputid = null;
          window.hints = {};
<%
          var sql = "SELECT fac_locale_xsl_label, COALESCE (fac_locale_xsl_cust, fac_locale_xsl_tekst) tekst"
                  + "  FROM fac_locale_xsl"
                  + " WHERE     fac_locale_xsl_lang = " + safe.quoted_sql(user_lang)
                  + "       AND fac_locale_xsl_module = 'ASP'"
                  + "       AND fac_locale_xsl_label LIKE 'hint.{0}%'".format(model.table)
                  + "       AND COALESCE (fac_locale_xsl_cust, fac_locale_xsl_tekst) IS NOT NULL";
          var oRs = Oracle.Execute(sql);
          while (!oRs.EOF)
          {
            model.hashints = true;
            %>
            window.hints['<%=safe.jsstring(oRs("fac_locale_xsl_label").Value)%>'] = '<%=safe.jsstring(oRs("tekst").Value)%>';
            <%
            oRs.MoveNext();
          }
          oRs.Close()
%>

          function sethint()
          {
              if (window.lastinputid)
              {
                  var ttl = $("label[for='"+window.lastinputid+"']").text().replace(/\:$/, "");
                  var veldnaam = window.lastinputid;
                  veldnaam = veldnaam.replace(/\_show$/, "");  // suggests hebben een _show postfix
                  veldnaam = veldnaam.replace(/^show\_/, "");  // datumvelden hebben een show_ prefix
                  var hintname = "hint.{0}.{1}".format("<%=safe.jsstring(model.table)%>", veldnaam);
                  var extra = "<%= __Logging > 0?" ({0})":"" %>".format(hintname);
                  var info = (hintname in window.hints ? window.hints[hintname] + extra : L("lcl_hint_not_found").format(ttl + extra));

                  if (scf_modalform==1)
                  {
                      FcltMgr.setModalHint(ttl, info);
                  }
                  else
                  {
                      if ($("#hinter").is(':visible'))
                      {
                          $("#hinter").dialog('option', 'title', L("lcl_hint_field_title").format(ttl));
                          $("#hinter div#hinttext").text (info);
                      }
                  }
              }
          }

          function scf_enablehint()
          {
            if (scf_modalform==1)
                FcltMgr.enableModalHint();
            else
                $("#hinter").dialog({ title: L("lcl_hint"),
                                      create: FcltMgr.fnCreateCloseButton("#hinter"),
                                      position: { my: "right top", at: "right bottom", of: ".fcltframeheader", collision: "fit" }
                                    });
            sethint();
          }

          $(function()
          {
            $('textarea').resize(function () { FcltMgr.resized(window) });
            $('textarea').autogrow();
<%            if (multi)
            {
%>              $('input[name=scf_multi_id]').val(FcltMgr.dialogArguments().id);
<%            }
%>
            $("input,textarea,select").on("focus", function () {
                  window.lastinputid = this.id;
                  sethint();
              });
            $("label").on("click", function () {
                  window.lastinputid = this.htmlFor;
                  sethint();
              });

            FcltMgr.resized(); // Indien labels over meer dan 1 regel staan.
          });

        </script>
      </head>
      <body id="<%=modal?"mod_scaffolding":""%>" class='<%=modal ? "fclt-modal scaffolding" : "editmode"%>'>
    <%
        var buttons = [ ];
        if (key > 0 && modal)
        {
            var sql = "SELECT COUNT(*)"
                    + "  FROM fac_audit"
                    + " WHERE fac_audit_tabelnaam = " + safe.quoted_sql(model.table)
                    + "   AND fac_audit_tabelkey = " + key;
            var oRs = Oracle.Execute(sql);
            var cnt = oRs(0).Value;
            oRs.Close();
            if (cnt > 0)
                buttons.push({title: L("lcl_history") + " ({0})".format(cnt), action:"scf_history()", icon: "fa-history", id: "btn_scf_history", importance: 3 });
        }

        if (model.REST_PUT || key < 0)
            buttons.push({title: L("lcl_submit"), action:"scf_submit()", icon: "fa-fclt-save", singlepress: true, id: "btn_scf_submit", importance: 1 });
        if (scf_params.edit.buttons)
        {
          for (var i = 0; i < scf_params.edit.buttons.length; i++)
          {   // Als je een action opgeeft *zonder* haakjes voegen we automagisch de key en model toe
              if (scf_params.edit.buttons[i].action.indexOf("(") < 0)
                  scf_params.edit.buttons[i].action += "(" + key + ", '" + model.table + "')"
              buttons.push(scf_params.edit.buttons[i]);
          }
        }
        if (modal && model.REST_DELETE && key > 0 && !multi)
            buttons.push({title: L("lcl_delete"), action:"scf_delete()", icon: "fa-trash-alt", singlepress: true, id: "btn_scf_delete", importance: 3 });
        buttons.push({title: L("lcl_cancel"), action:"scf_cancel()", icon: "fa-fclt-cancel", id: "btn_scf_cancel", importance: 3 });
//        if (!modal && model.hashints)
//            buttons.push({title: L("lcl_hint"), action:"scf_enablehint()", icon: "fa-question-circle", id: "btn_scf_enablehint", importance: 3 });
        if (!modal)
        {
            SUBFRAME_START();
            var ttl = safe.html(model.record_title);
            IFRAMER_HEADER(ttl, buttons, { ishtmlsafe: true, hints: model.hashints || __Logging > 0});
        }
        else
            MODAL_START();
    %>
        <div id="hinter" style='display:none'>
            <div id='hinttext'><%=I("fa-question-circle fa-2x")%> <%= L("lcl_hint_select_field")%></div>
        </div>
        <form name="u2" method="post" action="<%=scf_params.this_fullpath%>?mode=save&id=<%=key%><%=transit%>" onsubmit="return false;">
    <%
            if (scf_params.transit_flist)
            {   // Toevoegen van niet-model gerelateerde F-parameters.
                for (var i=0; i<scf_params.transit_flist.length; i++)
                {
                    Response.Write("<input type='hidden' name='" + scf_params.transit_flist[i].name + "' value='" + scf_params.transit_flist[i].val + "'>");
                }
            }

            if (multi)
            {
                Response.Write("<input type='hidden' name='scf_multi' value='1'>");
                Response.Write("<input type='hidden' name='scf_multi_id'>");
            }

            // Maak een lijst met alle velden die getoond moeten worden.
            // Hidden velden en velden die niet multi-editable zijn (meerdere records tegelijk wijzigen)
            // worden eruit gefilterd.
            var fld_arr_all = [];
            for (var fld in model.fields)
            {
                var field = model.fields[fld];
                if (field.sql)
                {
                     if (field.sqlshow) // toch tonen, ook al is hij readonly
                        fld_arr_all.push(fld);
                    continue; // weinig aan te bewerken
                }

                if (multi && !field.multiedit)
                {
                    delete model.fields[fld]; // Die is niet multi-edit enabled
                    continue;
                }

                // Als er geen database kolom (dbs) is ingevuld dan wordt het veld niet opgeslagen.
                // Dan hoeft er ook geen hidden input veld aanwezig te zijn. Dit is het geval bij buttons, labels enz..
                if ((field.hidden_fld || (field.readonly && (!(key > 0) ))) && field.dbs != "")
                {   // Eerst de hidden velden.
                    scf_RWHIDDENTR(model, fld, xxx_data[fld]);
                    if (field.showtransit) // toch tonen, ook al is hij readonly
                        fld_arr_all.push(fld);
                }
                else
                {
                    fld_arr_all.push(fld);
                }
            }

            var has_layout = (scf_params.layout ? true : false);
            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
                                 };

                // Hoeveel velden zitten er in dit blok
                var aantal = 0;
                for (var fld_nr in blk_obj.fields)
                {
                    var fld = blk_obj.fields[fld_nr];
                    if (inArray(fld, fld_arr_all))
                        aantal += 1;
                }

                if (aantal > 0)
                {
                    if (!modal)
                        BLOCK_START(blk_obj.blockid, blk_obj.label, blk_params);
                    else
                        MODAL_BLOCK_START(blk_obj.blockid, blk_obj.label, blk_params);

                    var multiadd = scf_params.incsetting && scf_params.incsetting.multiadd; // Dan kunnen we meerdere toevoegen
                    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];
                            var multiselect = (field.foreign ? field.foreign.multiselect : false) || (field.LOV ? field.multiselect : false);
                            if (field.readonly || fld == "id" || (field.hidden_fld && field.showtransit))
                                scf_ROFIELDTR(model, fld, xxx_data[fld]);
                            else if (field.insertonly && key > 0)
                                scf_ROFIELDTR(model, fld, xxx_data[fld]);
                            else if (!field.hidden_fld)
                                scf_RWFIELDTR(model, fld, xxx_data[fld], key, { multiadd: multiadd, multiselect: multiselect, multiedit: multi });
                        }
                    }

                    if (!modal)
                        BLOCK_END();
                    else
                        MODAL_BLOCK_END();
                }
            }

            if (modal)
            {
                SIMPLE_BLOCK_START();
                    CreateButtons(buttons);
                SIMPLE_BLOCK_END();
            }
            IFACE.FORM_END();
    %>

<% if (multi) {
	// Overal een vinkje voorzetten
%>
        <script>
        $(function()
          {
            init_multi_scaffolding();
          });
        </script>
<% } %>

        </form>
<%
        if (!modal)
            SUBFRAME_END();
        else
        MODAL_END();
%>
      </body>
    </html>
<%
}
%>