<% /*
    $Revision$
    $Id$

    File:        scaffolding_search.asp

    Description: Generiek zoekscherm
    Parameters:
    Context:
    Note:

*/ %>
<%
function scaffolding_search(model, scf_params)
{
    scf_params.search = scf_params.search || model.search;
    scf_params.list = scf_params.list || model.list || {};

    if ("search" in model)
    {
        scf_params.search.title = scf_params.search.title || model.search.title || model.records_title;
        scf_params.search.filters = scf_params.search.filters || model.search.filters || [];
    }
    FCLTHeader.Requires({plugins:[],
                         js: ["jquery-ui.js", "jquery.timepicker-table.js"],
                         css: ["timePicker-table.css"]});
    if ("requires" in scf_params.search)
        FCLTHeader.Requires(scf_params.search.requires);

    if (model.autfunction)
        var authparams = user.checkAutorisation(model.autfunction);

    scf_params.search.autosearch |= getQParamInt("autosearch", 0) == 1;

    if ("hook_pre_search" in model)
        model.hook_pre_search(model.fields);
    %>
    <html>
    <head>
     <% FCLTHeader.Generate() %>
        <script>
          <% if ("title" in scf_params.search) { %>
              FcltMgr.setTitle("<%=safe.jsstring(scf_params.search.title)%>");
          <% } %>

          $(function ()
          {
            $("#scfcolpicker table tbody" ).not('thead tr').sortable({ axis: "y", distance: 10 });
            $("#chkall").click(function () // Allemaal aan of uit
                {
                    $("#scfcolpicker tr").find("input[type=checkbox]").prop("checked", $(this).prop("checked"))
                });
          });

          function pick_columns(deze)
          {
            $("#scfcolpicker").show();
            updateTableHeaders();
            $("#scfcolpicker").css("left", window.fcltevent.clientX - $("#scfcolpicker").width() - 50);
          }

          $(function () {
                $(document).click(function(){
                    $("#scfcolpicker").hide();
                })
                $("#scfcolpicker").click(function(event)
                {
                    event.stopPropagation();
                })
          });

          // where needed
          $(function($){
            $('select').not(".notmulti").multiSelectToggle({ xxxlabel: "<i class='autoreport fa fa-comment fa-lg'>&nbsp;</i>" });
          });

          function doSubmit()
          {
            $("#scfcolpicker").hide();

            if (!validateForm("u2"))
              return false;

            var cols = [];
            var groups = [];
            $("#scfcolpicker tr").each(function()
                {
                    if (!this.id)
                        return;

                    if (this.id == "chk_pivot")
                        return;

                    if ($(this).find("input[type=checkbox]").prop("checked"))
                    {
                        cols.push(this.id);
                        var selectgroup = $(this).find("select").val();
                        var defaultgroup = $(this).find("input[type=checkbox]").attr("group");
                        var thisgroup = (selectgroup?selectgroup:defaultgroup);
                        groups.push( (thisgroup?thisgroup:"") );
                    }
                }
            );
            //if ($("show_deleted").is(":checked"))
            //{   // het soft_delete veld zit niet in het model
            //    cols.push("<%=model.soft_delete%>");
            //    groups.push('G');
            //}
            $("#columns").val(cols.join(","));
            $("#groupby").val(groups.join(","));

            if ($("#chk_pivot").length)
                $("#scf_pivot").val($("#chk_pivot").prop("checked")?1:0);

            $("#workFrame").width($(window).width()); // grafieken 'krimpen' slecht
            document.forms.u2.submit();
          }
    <% if (scf_params.search.autosearch) { %>
          $(doSubmit);
    <% } %>
        </script>
    </head>

    <body id="searchbody">
    <div id="search">
        <form name="u2" method="get" target="workFrame" onsubmit="doSubmit()">
            <input type='hidden' name='mode' value='list'>
            <input type='hidden' name='columns' id='columns'>
            <input type='hidden' name='groupby' id='groupby'>
            <input type='hidden' name='scf_pivot' id='scf_pivot' value='<%=(model.list.autoPivot&2)?1:0%>'>
    <%
        var defaults = shared.qs2json(model); // TODO: Ook via scf_params

        for (var fld in model.fields)
        {
            var field = model.fields[fld];
            if (field.hidden && fld in defaults)
            {
                Response.Write("<input type='hidden' name='" + fld + "' value='" + safe.htmlattr(defaults[fld]) + "'>");
            }
        }
        if (scf_params.transit)
        {
            var tdata = scf_params.transit;
            for (trans in tdata) {
        %>
                <input type='hidden' name='<%=trans%>' value='<%=safe.htmlattr(tdata[trans])%>'>
        <%  }
        }

        var est_title = "";
        if ("estimated_rows" in model)
            est_title = " <em style='font-size:10px'>estimated {0} rows as of {1}</em>".format(model.estimated_rows, toDateTimeString(model.last_analyzed));
        else
            est_title = " " + model.records_title;

        BLOCK_START("searchtable", L("lcl_filterblok") + est_title);

        if (scf_params.search.labels)
        {
            for (var i=0; i < scf_params.search.labels.length; i++)
            {
                ROFIELDTR("fldtxt", scf_params.search.labels[i].lbl, scf_params.search.labels[i].txt, { suppressEmpty: true });
            }
        }

        var includefilters = [];
        for (var i=0; i < scf_params.search.filters.length; i++)
        {
            var xmodel = model;
            var fld = scf_params.search.filters[i];
            if (fld.indexOf(".") > 0) // Bij res_ruimte configurations.res_opstelling_key ofwel <include>.<field>
            {
                includefilters.push(fld);
                xmodel = model.includes[fld.split(".")[0]].model;
                var fld = fld.split(".")[1];
            }
            var field = xmodel.fields[fld];
            if (!field) // Een veld kan verwijderd zijn met delete this.fields.veld.
                continue;

            field.defaultvalue = null;

            if (field.hidden)
                continue;

            if (field.typ == "memo")
                field.typ = "varchar"; // We hoeven geen groot veld om in te zoeken

            var def = field.filterdefault || defaults[fld];
            var defs = scf.parseDefault(def, field);

            if (field.filter == 'like' || field.filter == 'exact' || !("filter" in field))
            {
                if (scf_params.fcltfilters && scf_params.fcltfilters[fld])
                {   // pinned filter parameters
                    var fldval = scf_params.fcltfilters[fld];
                    var LOVval = "";
                    if (typeof fldval == "string")
                    {
                        scf_RWFIELDTR(xmodel, fld, fldval, null, {search: true, extraclass: "pinned"});
                    }
                    else
                    {
                        for (var j=0; j<fldval.length; j++)
                        {
                            LOVval += fldval[j] + ";" + fldval[j] + (j<fldval.length-1 ? ";" : "");
                        }
                        field.LOV = LOVval;
                        field.emptyoption = null;
                        scf_RWFIELDTR(xmodel, fld, defs.vmin, null, {readonly: true, extraclass: "pinned"});
                    }
                }
                else
                {
                    if (defs.fixed)
                    {
                        if (field.showfixedfilter)
                            scf_ROFIELDTR(xmodel, fld, defs.vmin, null);
                    }
                    else
                        scf_RWFIELDTR(xmodel, fld, defs.vmin, null, {search: true});
                }
            }
            else if (field.filter == "range")
            {
                if (!defs.fixed)
                {
                    var org_label = field.label;
                    field.label = org_label + " " + L("lcl_from");
                    scf_RWFIELDTR(xmodel, "start_" + fld, defs.vmin, null, {search: true});
                    field.label = org_label + " " + L("lcl_to");
                    scf_RWFIELDTR(xmodel, "end_" + fld, defs.vmax, null, {search: true});
                    field.label = org_label;
                }
            }
        }
        if (model.soft_delete)
            RWCHECKBOXTR("show_deleted", "fldcheck", L("lcl_scf_show_deleted"), defaults["show_deleted"]);
        if (model.soft_expire)
            RWCHECKBOXTR("show_expired", "fldcheck", L("lcl_scf_show_expired"), defaults["show_expired"]);

        if (model.includes)
        {
            for (var i in model.includes)
            {
                if ("outertoggle" in model.includes[i])
                    RWCHECKBOXTR("scf_outer", "fldcheck", model.includes[i]["outertoggle"].lbl, model.includes[i]["outertoggle"].def);
            }
        }

        if ((model.list.autoGraph & 1) == 1)
        {
            var on = (model.list.autoGraph & 2) == 2;
            RWCHECKBOXTR("scf_graph", "fldcheck", L("lcl_scf_graph"), on);
        }

        if (includefilters.length)
            scf_RWHIDDENTR(model, "includefilter", includefilters.join(","));

        BLOCK_END();
        var buttons =  [];
        buttons.push({title: L("lcl_search"), action: "doSubmit()" });

        if (model.list && !model.list.fixedColumns)
            buttons.push({title: L("lcl_scf_columns"), action: "pick_columns(this)" });
        CreateButtons(buttons, { entersubmit: true });
    %>
        </form>

        <div id="scfcolpicker" style='display:none'>
            <table>
            <tbody>
            <%
                if (model.list && model.list.canGroup)
                    Response.Write("<thead><tr><th><input id='chkall' type='checkbox'>" + L("lcl_rap_visible") + "</th><th>" + L("lcl_rap_groupby") + "</th></tr></thead>");
                else
                    Response.Write("<thead><tr><th><input id='chkall'  type='checkbox'>" + L("lcl_rap_visible") + "</th></tr></thead>");

                // Bouw het fields object opnieuw op in de volgorde van params.columns. Goed voor sorteren later.
                // Sortering van hide_f sorteer velden lossen we in model_reports wel op.
                var newfields = {};
                for (var i=0; i < scf_params.list.columns.length; i++)
                {
                    var fld = scf_params.list.columns[i];
                    if (fld in model.fields)
                    {
                        newfields[fld] = model.fields[fld];
                        delete model.fields[fld];
                    }
                }
                for (fld in model.fields)
                    newfields[fld] = model.fields[fld];
                model.fields = newfields;

                for (fld in model.fields)
                {
                    var field = model.fields[fld];
                    if (field.hidden || field.typ=="label") // Hidden kun je ook niet aanzetten, en labels idem.
                        continue;
                    if (!field.label || field.label == '<hidden>' || !field.dbs)
                        continue;

                    var on = inArray(fld, scf_params.list.columns);
                    var groupselector = "";
                    var groupdefault = ""
                    if (model.list && field.typ != "varchar" && field.typ != "html" && !field.dbs.match(/_key$/i))
                    {
                        if (model.list.canGroup)
                        {
                            if (field.typ == "date" || field.typ == "datetime")
                                grp = api2.filterLOV(L("lcl_rap_groupbyLOV"), "G,D,W,M,Q,Y,H");
                            else if (field.typ == "time")
                                grp = api2.filterLOV(L("lcl_rap_groupbyLOV"), "G,H");
                            else if (field.typ == 'varchar')
                                grp = api2.filterLOV(L("lcl_rap_groupbyLOV"), "G");
                            else
                                grp = api2.filterLOV(L("lcl_rap_groupbyLOV"), "G,S,C,A");
                            groupselector = "<td>" + api2.splitLOV2select(grp , field.group.id, { selclass: "notmulti" }) + "</td>";
                        }
                        else
                        {
                            if (field.group && field.group.id != "G")
                                groupdefault = field.group.id;
                        }
                    }
                    Response.Write("\n<tr id='" + fld + "'><td><label>"
                                    + "<input type='checkbox'" + (on?" checked='1'":"")
                                                               + (groupdefault?" group='"+safe.html(groupdefault)+"'":"") + ">"
                                    + safe.html(field.label || ("<"+field.dbs+">")) + "</label></td>"
                                    + groupselector
                                    + "</tr>"
                                  );
                }
                for (var i = 0; i < scf_params.list.columns.length; i++)
                {
                    var col = scf_params.list.columns[i];
                    if (col.indexOf(".") > 0)
                    {
                        var on = true;
                        var xmodel = model.includes[col.split(".")[0]].model;
                        var field = xmodel.fields[col.split(".")[1]];
                        Response.Write("\n<tr id='" + col + "'><td><label><input type='checkbox'" + (on?" checked='1'":"") + ">"
                                                              + safe.html(field.label || ("<"+field.dbs+">")) + "</label></td>");
                    }
                }
                // Kolom "Aantal" is altijd zichtbaar is de lijst met kolommen, behalve als de standaardwaarde "altijd uit"="Nee" is.
                if (model.list.autoCount > 0)
                {
                    var on = (model.list.autoCount & 2) == 2; // Standaard waarde van "Aantal" is "on".
                    var toggle = (model.list.autoCount & 1) == 1; // Veld "Aantal" mag getoggled worden.
                    Response.Write("\n<tr id='scf_count'><td><label><input type='checkbox'"
                                                          + (on?" checked='1'":"")
                                                          + (toggle?"":" disabled")
                                                          + ">"
                                                          + L("lcl_count") + "</label></td></tr>");
                }
                // Idem voor Kolom "Ratio"
                if (model.list.autoRatio > 0)
                {
                    var on = (model.list.autoRatio & 2) == 2; // Standaard waarde van "Aantal" is "on".
                    var toggle = (model.list.autoRatio & 1) == 1; // Veld "Aantal" mag getoggled worden.
                    Response.Write("\n<tr id='scf_ratio'><td><label><input type='checkbox'"
                                                          + (on?" checked='1'":"")
                                                          + (toggle?"":" disabled")
                                                          + ">"
                                                          + L("lcl_ratio") + "</label></td></tr>");
                }

                if ((model.list.autoPivot & 1) == 1)
                {
                    var on = (model.list.autoPivot & 2) == 2;
                    Response.Write("<tfoot><tr><td><label><input type='checkbox' id='chk_pivot' " + (on?" checked='1'":"") + ">"
                                               + L("lcl_scf_pivot") + "</label></td></tr></tfoot>");
                }
             %>
            </tbody>
            </table>
            <input type='button' class='button' value='<%=L("lcl_search")%>' onclick='doSubmit()'>
            <input type='button' class='button' value='<%=L("lcl_close_window")%>' onclick='$("#scfcolpicker").hide()'>
        </div>
    </div>

    <div id="result">
     <iframe width="100%" height="100%" src="<%=rooturl%>/appl/Shared/empty.asp"
             name="workFrame" id="workFrame"  onload='FcltMgr.iframeLoaded(this)'
             <% if (scf_params.search.autosearch) { %>skipautoscroll="1"<% } %>
             frameborder="0" scrolling="no"></iframe>
    </div>

    </body>
    </html>
<%
}
%>