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

    File            fac_report.asp
    Description:    Voer een nieuwe stijl rapport uit (toon het zoekblok)
    Parameters:     usrrap_key van een rapport
                    mode=list optioneel, toon het rapport direct zonder zoekblok
    Note:           XSL rapporten en view rapporten gaan via de oude code
*/
%>
<!-- #include file="../scf/scaffolding.inc" -->
<!-- #include file="../api2/model_reports.inc" -->
<!-- #include file="../Shared/xml_converter.inc" -->
<%
    var usrrap_key = getQParamInt("usrrap_key", -1);
    if (usrrap_key == -1) // Dan moet rap_name meegegeven zijn
    {
        var rap_name = getQParam("rap_name"); // Let op: deprecated sinds 2015.1
        var sql = "SELECT fac_usrrap_key"
                + "  FROM fac_usrrap"
                + " WHERE UPPER(fac_usrrap_view_name) = " + safe.quoted_sql_upper(rap_name);
        var oRs = Oracle.Execute(sql);
        var usrrap_key = oRs("fac_usrrap_key").Value;
        oRs.MoveNext()
        if (!oRs.Eof)
            INTERNAL_ERROR_RAPNAME_NOT_UNIQUE; // gebruik dan maar usrrap_key
        oRs.Close();
    }

    if (mode == "list" && Server.ScriptTimeout<600)
        Server.ScriptTimeout=600; // extra tijd

    var rapport = model_reports(usrrap_key);

    if (mode == "search" && rapport.autorefresh > 0)
    {
        var theURL = "../shared/refresher.asp?url=" + Server.URLencode("/appl/fac/fac_report.asp?mode=list" + transitQS()) + "&refreshrate=" + S("usrrap_refreshrate");
        Response.Redirect(theURL);
    }

    rapport.list.canGroup = (S("fac_usrrap_mode") == 1);

    if (rapport.styling && (rapport.styling.id & 2)) // view proc doen we 'old style'
            Response.Redirect("fac_usrrap_search.asp?usrrap_key=" + usrrap_key);

    var params = { transit: { "usrrap_key": usrrap_key },
                   search: { requires: { js: ["./fac_report.js"] }}
                 };
    if ("estimated_rows" in rapport && rapport.estimated_rows < 250)
        params.search.autosearch = true;

    if (rapport.styling && (rapport.styling.id & 1)) // XSL proc doen we niet via resultsettable
    {
        // Overrule scaffolding_list
        scaffolding_list = function _styled_report_scaffolding_list(model, scf_params)
        {
            var xxx_params = { filter : scf_params.filter || shared.qs2json(rapport) };

            rapport.addfixedfilters(xxx_params.filter);
            var wheres = api2.sqlfilter(xxx_params, rapport);
            rapport.add3d(wheres);

            var sql_where = null;
            if (wheres.length)
                sql_where = "WHERE " + wheres.join(" AND " );

            var outputmode = getQParamInt("outputmode", 0);
            var nobuttons = getQParamInt("nobuttons", 0) == 1;

            var rmode = '';
            if (outputmode==2) rmode = 'excel';
            if (outputmode==1) rmode = 'print';

            var nohtml = getQParamInt("nohtml", 0) == 1;
            if (nohtml) // Die is simpel
            {
                Response.Clear();
                FCLT2XMLResponse ({xmlnode: 'rapport', key: usrrap_key, mode: rmode, where: sql_where });
                Response.End;
            }

            // Zelf niet nodig maar sommige XSL-rapportages (ARAI KPI) doen modal popup
            FCLTHeader.Requires({js: ["jquery-ui.js"]});

            %><html>
                  <head>
                <%  FCLTHeader.Generate({ outputmode: outputmode }); %>
                    <% if (outputmode == 0) {%>
                      <script type="text/javascript">
                        function rap_print()
                        {
                            window.open("fac_report.asp?outputmode=1<%=safe.jsstring(transitQS())%>");
                        }
                        function rap_excel()
                        {
                            window.open("fac_report.asp?outputmode=2<%=safe.jsstring(transitQS())%>");
                        }
                      </script>
                    <% } %>
                  </head>
                  <body id="listbody" <%= (outputmode == 1? "onload='window.print()'" : "")%>>
                <%
                    if (outputmode==0)
                    {
                        var buttons = [];
                        if(!nobuttons)
                        {
                            var buttons = [ { icon: "page_refresh.png", title: L("lcl_refresh"), action: "FcltMgr.reload()" },
                                            { icon: "print.png",  title: L("lcl_print_table"), action: 'rap_print()' },
                                            { icon: "excel.png", title: L("lcl_export_to_excel"), action: 'rap_excel()  ' }
                                          ];
                        }
                        IFRAMER_HEADER(model.records_title, buttons);
                    }
                    FCLT2XMLResponse ({xmlnode: 'rapport', key: usrrap_key, mode: rmode, where: sql_where});
                %>
                  </body>
                </html>
            <%
        }
    }
    else
    {
        var graph = false;
        if (getQParamInt("has_scf_graph", 0) == 1)
            graph = getQParam("scf_graph", "") == "on";
        else
            graph = (rapport.list.autoGraph & 2) == 2;
        if (mode == "list" && graph)
        {
            FCLTHeader.Requires({plugins: ["jQuery"],
                                 js: ["../Localscripts/jqPlot/dist/excanvas.js",
                                      "../Localscripts/jqPlot/dist/jquery.jqplot.min.js",
                                      "../Localscripts/jqPlot/dist/plugins/jqplot.canvasTextRenderer.js",
                                      "../Localscripts/jqPlot/dist/plugins/jqplot.canvasAxisLabelRenderer.js",
                                      "../Localscripts/jqPlot/dist/plugins/jqplot.canvasAxisTickRenderer.js",
                                      "../Localscripts/jqPlot/dist/plugins/jqplot.categoryAxisRenderer.js",
                                      "../Localscripts/jqPlot/dist/plugins/jqplot.barRenderer.js",
                                      "../Localscripts/jqPlot/dist/plugins/jqplot.meterGaugeRenderer.js",
                                      "../Localscripts/jqPlot/dist/plugins/jqplot.pieRenderer.min.js",
                                      "../Localscripts/jqPlot/dist/plugins/jqplot.highlighter.min.js"
                                     ],
                                 css: ["../Localscripts/jqPlot/dist/jquery.jqplot.css"]
                                 });
            // Overrule scaffolding_list
            scaffolding_list = fac_usrrap_list_graph;
        }
    }

    if (mode == "list")
        shared.registeraction("report", {refkey: usrrap_key, daily: true});

    scaffolding(rapport, params);

function fac_usrrap_list_graph (model, scf_params)
{
    scf_params.list = scf_params.list || {};
    scf_params.list.columns = scf_params.list.columns || [];
    scf_params.list.groupby = scf_params.list.groupby || [];

    var transit = "";
    if ("transit" in scf_params)
        transit = "&" + scf_params.transit.name + "=" + safe.url(scf_params.transit.val);

    var cols = getQParamArray("columns", []);
    if (cols.length && cols[0])
        scf_params.list.columns = cols;

    var grps = getQParamArray("groupby", []);
    if (grps.length)
        scf_params.list.groupby = grps;

    if (!scf_params.list.columns.length && "list" in model)
    {
        scf_params.list.columns = model.list.columns;
        scf_params.list.groupby = model.list.groupby;
    }

    var xxx_params = { filter : scf_params.filter || shared.qs2json(model), columns: scf_params.list.columns, groupby: scf_params.list.groupby, scf_graph: "on" };
    var xxx_array = model.REST_GET(xxx_params);

    graphData = { teller: xxx_array.length
                , arr_x: []
                , arr_y: []
                , arr_xy: []
                };

    graphAxes = { url: null
                    , xas: { naam: model.fields[scf_params.list.columns[0]].label}
                    , yas: []
                    };

    for (var c=1; c < scf_params.list.columns.length; c++)
    {
        graphData.arr_y.push([]);
        graphAxes.yas.push({ naam: model.fields[scf_params.list.columns[c]].label });
    }

    var typX = model.fields[scf_params.list.columns[0]].orgtyp;
    var lineRenderer = typX=='date'||typX=='datetime';

    for (var i=0; i < xxx_array.length; i++)
    {
            var txtX = xxx_array[i][scf_params.list.columns[0]]
            if (typX == "datetime")
                txtX = toDateTimeString(txtX);
            else if (typX == "time")
                txtX = toTimeString(txtX);
            else if (typeof txtX == "date" || txtX instanceof Date)
                txtX = toDateString(txtX);

        graphData.arr_x.push(txtX);
        for (var c=1; c < scf_params.list.columns.length; c++)
        {
            graphData.arr_y[c-1].push(xxx_array[i][scf_params.list.columns[c]]||0);
            graphData.arr_xy.push([xxx_array[i][scf_params.list.columns[c-1]], xxx_array[i][scf_params.list.columns[c]]]||0);
        }
    }

    graphInit = { title           : model.records_title
                , graph_type      : (rapport.graph_type?rapport.graph_type.id:null)
                , maxrows         : 0
                , limiet          : [0,70,90,100] //limiet_arr
                , report_options  : rapport.graph_options || "{}"
                , default_options : S("fac_graph_default_json") || "{}"
                , sql_orderby     : "" //oRs("fac_usrgraph_orderby").Value || ""
                //, sql : sql_select
                };

%>
<html>
<head>
<%  FCLTHeader.Generate(); %>
    <script>
    var JSONdata = '<%=safe.jsstring(JSON.stringify(graphInit))%>';
    var l_init = eval('(' + JSONdata + ')');

    var JSONdata = '<%=safe.jsstring(JSON.stringify(graphAxes))%>';
    var l_axes = eval('(' + JSONdata + ')');

    var JSONdata = '<%=safe.jsstring(JSON.stringify(graphData))%>';
    var l_data = eval('(' + JSONdata + ')');

    var l_arr_x = l_data.arr_x;
    var l_arr_y = l_data.arr_y;
    var l_xas_naam = l_axes.xas.naam;
    var l_yas_naam = l_axes.yas[0].naam;
    var l_yas_count = l_axes.yas.length;

    var l_colors = (l_yas_count==1?<%=S("fac_graph_colors1")%>:<%=S("fac_graph_colors2")%>);
    var l_labels = [];
    for (y=0; y<l_axes.yas.length; y++)
    {
      l_labels.push(l_axes.yas[y].naam);
    }

    var default_options = eval('(' + l_init.default_options + ')');
    var report_options = $.extend(default_options,
                                  eval('(' + l_init.report_options + ')'));

<%
    switch (graphInit.graph_type)
    {
        case 1: // BarChart
%>
            var l_colors = (l_yas_count == 1?<%=S("fac_graph_colors1")%> : <%=S("fac_graph_colors2")%>);
            var effectivedata = l_arr_y;
            var props = { seriesDefaults:{ renderer: $.jqplot.BarRenderer
                                         , pointLabels: { show: false }
                                         }
                        , stackSeries: true
                        //, series:[{label:'a'},{label:'b'}]
                        //, legend: {show: true}
                        , title: l_init.title
                        , seriesColors: l_colors
                        , axes: { xaxis: { renderer: $.jqplot.CategoryAxisRenderer
                                         , ticks: l_arr_x
                                         , label: l_xas_naam
                                         , tickRenderer: $.jqplot.CanvasAxisTickRenderer
                                         , tickOptions: { enableFontSupport: true
                                                        , angle: 30
                                                        , fontSize: '9pt'
                                                        }
                                         }
                                , yaxis: { label: l_yas_naam
                                         , tickOptions: { formatString:'%.1f'
                                                        }
                                         }
                                }
                        , highlighter: { show: true
                                       , showMarker: false
                                       , tooltipAxes: 'y'
                                       , tooltipLocation: 'n'
                                       , formatString: '<table style="background-color: #cccccc" class="xjqplot-highlighter"><tr><td>%s</td></tr></table>'
                                       }
                        };
<%
            break;
        case 2:  // MeterGauge
%>
            var l_limits = [];
            if ("intervals" in report_options.seriesDefaults.rendererOptions)
            {
                l_limits = report_options.seriesDefaults.rendererOptions.intervals;
                delete report_options.seriesDefaults.rendererOptions.intervals; // Voorkom dat deze array de "effectiveprops" overschrijft.
            }                                                                   // De eeste waarde in het array wordt alleen gebruikt voor het minimum.

            if (l_limits.length < 3)
                l_limits = l_init.limiet;

            var l_limit_min = l_limits[0];
            var l_limit_max = l_limits[l_limits.length-1];
            l_limits.splice(0,1); // haal alleen de eerste waarde weg.

            var l_x = l_arr_x[0];
            var l_y = l_arr_y[0];

            var l_colors = <%=S("fac_graph_gauge_colors")%>;
            var effectivedata = [ [100* l_x / l_y] ];
            var props = { title: l_init.title
                        , seriesDefaults: { renderer: $.jqplot.MeterGaugeRenderer
                                          , rendererOptions: { showTicks: true
                                                             , showTickLabels: true
                                                             , label: l_init.title + l_x + "/"  + l_y
                                                             , labelPosition: 'bottom'
                                                             , labelHeightAdjust: -5
                                                             , background: '#f0f0f0'
                                                             , tickColor: '#333333'
                                                             , ringColor: '#333333'
                                                             , ringWidth: 3
                                                             , min: l_limit_min
                                                             , max: l_limit_max
                                                             , intervals: l_limits
                                                             , intervalColors: l_colors
                                                             }
                                          }
                        };
<%
            break;
        case 3:  // pie-chart
%>
            var l_colors = <%=S("fac_graph_pie_colors")%>;
            var effectivedata = [l_data.arr_xy];
            var props = { title: l_init.title
	                      , seriesColors: l_colors
	                      , seriesDefaults: { renderer:$.jqplot.PieRenderer
                                          , showDataLabels: true
                                          , rendererOptions: { fill: true
                                                             , showDataLabels: true
                                                             , dataLabelPositionFactor: 1.2
                                                             , dataLabelCenterOn: true
                                                             }
                                          }
                        , legend: { show: true
                                  , location: 'ne'
                                  }
                        , grid: { drawBorder: false
                                , shadow : false
                                , background: '#ffffff'
                                }
                        };
<%
            break;
        case 4: // LineChart
%>
            var l_labels = [];
            for (y=0; y<l_axes.yas.length; y++)
            {
              l_labels.push(l_axes.yas[y].naam);
            }
            var l_colors = (l_yas_count == 1? <%=S("fac_graph_colors1")%> : <%=S("fac_graph_colors2")%>);
            var effectivedata = l_arr_y;
            var props = { seriesDefaults: { pointLabels: { show: true
                                                         }
                                          }
                        , stackSeries: false
                        , title: l_init.title
                        , seriesColors: l_colors
                        , legend: { show: (l_yas_count > 1)
                                  , placement: (l_yas_count > 1?'outsideGrid' : 'intsideGrind')
                                  , location: 'ne'
                                  , labels: l_labels
                                  }
                        , axes: { xaxis: { renderer: $.jqplot.CategoryAxisRenderer
                                         , ticks: l_arr_x
                                         , label: l_xas_naam
                                         , tickRenderer: $.jqplot.CanvasAxisTickRenderer
                                         , tickOptions: { enableFontSupport: true
                                                        , angle: 30
                                                        }
                                         }
                                , yaxis: { label: (l_yas_count == 1? l_yas_naam : '')
                                         , tickOptions: { formatString: '%.1f'
                                                        }
                                         }
                                }
                        , highlighter: { show: true
                                       , showMarker: false
                                       , tooltipAxes: 'y'
                                       , tooltipLocation: 'n'
                                       , formatString: '<table style="background-color: #cccccc" class="xjqplot-highlighter"><tr><td>%s</td></tr></table>'
                                       }
                        };
<%
            break;
        default:
            break;
    }
%>



        var effectiveprops = $.extend(true, props, report_options);

        $(function () {
            plot1 = $.jqplot( 'myGraph'
                            , effectivedata
                            , effectiveprops
                            );
                      });
    </script>
</head>
<body id="listbody">
    <%
        var buttons = []; // niet ondersteund
        IFRAMER_HEADER(model.records_title, []);
    %>
            <div id="myGraph" style="height:500px;"></div>
      </body>
    </html>
<%
    }
%>
