<% /*
     $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"],
                              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 key = getQParamInt("id", -1);
    if (key > 0)
    {
        user.auth_required_or_abort(model.REST_PUT || model.REST_DELETE);
        var xxx_params = { filter: { id: key } };
        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 (fld in filter || !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 (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);
        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.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);
                    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)
        model.hook_pre_edit(xxx_data, model.fields);

    var modal = 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;
    %>

    <html>
      <head>
    <%  FCLTHeader.Generate(); %>
        <script>
          function scf_submit_callback(json)
          {
              if (json.success)
                  FcltMgr.closeDetail(window, json);
              else
                  iface.button.enable("btn_scf_submit");
          }

          function scf_submit()
          {
            if (!validateForm("u2"))
              return false;

            if (typeof pre_submit != "undefined")
            {
                if (!pre_submit())
                    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 } );
          }

          function scf_delete()
          {
            FcltMgr.confirm('<%=safe.jsstring(L("lcl_scf_confirm_delete").format(model.record_title, xxx_data.name || xxx_data.id))%>',
                { 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;
          $(function () {
              $("input,textarea").on("focus", function () {
                    window.lastinputid = this.id;
                    sethint();
                });
            });
          window.hints = {};
          function sethint()
          {
            if ($("#hinter").is(':visible'))
            {
                if (window.lastinputid)
                {
                    if (window.lastinputid in window.hints)
                        $("#hinter div#hinttitle").text (window.hints[window.lastinputid]);
                    else
                    {
                        $.getJSON("../shared/load_hint.asp?model=<%=model.table%>&fld=" + escape(window.lastinputid),
                                      function (data, textStatus)
                                      {
                                          if (data && data.hint)
                                          {
                                            window.hints[window.lastinputid] = data.hint;
                                          }
                                          else
                                            window.hints[window.lastinputid] = "No info found";
                                          $("#hinter div#hinttitle").text (window.hints[window.lastinputid]);
                                      }
                                  );
                    }
                }
            }
          }
          function scf_enablehint()
          {
            $("#hinter").dialog({ title: L("lcl_hint")});
            sethint();
          }
          jQuery(function()
              {
                $('textarea').resize(function () { FcltMgr.resized(window) });
                $('textarea').autogrow();
                FcltMgr.resized(); // Indien labels over meer dan 1 regel staan.
              });
        </script>
      </head>
      <body id="<%=modal?"mod_scaffolding":"editbody"%>" <%=modal?"class='modal scaffolding'":""%>>
        <div id="hinter" style='display:none'>Hint!
            <div id='hinttitle'></div>
        </div>
    <%
        var buttons = [ ];
        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 (model.REST_PUT || key < 0)
            buttons.push({title: L("lcl_submit"), action:"scf_submit()", icon: "fa-save", singlepress: true, id: "btn_scf_submit" });
        if (modal && model.REST_DELETE && key > 0)
            buttons.push({title: L("lcl_delete"), action:"scf_delete()", icon: "fa-trash", singlepress: true, id: "btn_scf_delete" });
        buttons.push({title: L("lcl_cancel"), action:"scf_cancel()", icon: "fa-undo", id: "btn_scf_cancel" });
        if (model.hashints)
            buttons.splice(0, 0, {title: L("lcl_hint"), action:"scf_enablehint()", icon: "lightbulb.png", id: "btn_scf_enablehint" });
        if (!modal)
            IFRAMER_HEADER(model.record_title, buttons);
    %>
        <div id="edit">
          <form name="u2" method="post" action="<%=scf_params.this_fullpath%>?mode=save&id=<%=key%><%=transit%>" onsubmit="return false;">
    <%
            var fld_arr = [];
            for (var fld in model.fields)
            {
                var field = model.fields[fld];
                if (field.sql)
                    continue; // weinig aan te beweken

                if (field.hidden_fld || (field.readonly && !(key > 0)))
                {   // Eerst de hidden velden.
                    scf_RWHIDDENTR(model, fld, xxx_data[fld]);
                }
                else
                    fld_arr.push(fld);
            }

            // Sorteer de velden volgens gegeven layout.

            var col_id = "scf_info";
            var col_1_length = fld_arr.length;
            if (scf_params.multicolumn)
            {
                col_id = "scfInfo";
                col_1_length = ( ((fld_arr.length % 2)==0) ? (fld_arr.length/2) : ((fld_arr.length+1)/2) );
            }

            var i = 0;
            BLOCK_START(col_id, model.record_title);
            while (i < col_1_length)
            {
                var fld = fld_arr[i];
                var field = model.fields[fld];
                if (field.readonly || fld == "id")
                    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);
                i++;
            }
            BLOCK_END();

            if (scf_params.multicolumn)
            {
                BLOCK_START("scfInfo_F", model.record_title);
                while (i < fld_arr.length)
                {
                    var fld = fld_arr[i];
                    var field = model.fields[fld];
                    if (field.readonly || fld == "id")
                        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);
                    i++;
                }
                BLOCK_END();
            }

            if (modal)
                CreateButtons(buttons);
            IFACE.FORM_END();
    %>
          </form>
        </div>
      </body>
    </html>
<%
}
%>