<%
// JGL: Experimenteel, niet in gebruik

function fac_usrrap_list_graph (model, scf_params, p_xxx_array)
{
    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 = p_xxx_array || model.REST_GET(xxx_params);
    var xxx_columns = (xxx_params.filter.columns ? xxx_params.filter.columns.split(",") : null);

    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: []
                    , zas: { naam: ((xxx_params.filter.scf_pivot==1 && xxx_columns && xxx_columns[2]) ? model.fields[xxx_columns[2]].label : null)}
                    };

    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 newtyp = model.fields[scf_params.list.columns[0]].typ;
        var txtX = xxx_array[i][scf_params.list.columns[0]]
        if (newtyp == "datetime")
            txtX = toDateTimeString(txtX);
        else if (newtyp == "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);
        }
    }

var udr_graph_typ_json = "";    
switch (graph_type)
{
    case 1: udr_graph_typ_json = "udr_graph_bar_json"; break;
    case 2: udr_graph_typ_json = "udr_graph_gauge_json"; break;
    case 3: udr_graph_typ_json = "udr_graph_pie_json"; break;
    case 4: udr_graph_typ_json = "udr_graph_line_json"; break;
    case 5: udr_graph_typ_json = "udr_graph_block_json"; break;
}
rapport = { graph_type: {id: 4} }
    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  : 0&&rapport.graph_options || "{}"
                , default_options : S(udr_graph_typ_json) || "{}"
                , sql_orderby     : "" //oRs("fac_usrgraph_orderby").Value || ""
                //, sql : sql_select
                };

    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.js",
                              "../Localscripts/jqPlot/dist/plugins/jqplot.highlighter.js"
                             ],
                         css: ["../Localscripts/jqPlot/dist/jquery.jqplot.css"]
                         });
    if (rapport.graph_type.id == 1 || rapport.graph_type.id == 4)
    {
        // Alleen bij barchart (1) en linechart (4) dit script voor label-points, bij gaugemeter NIET(!) om runtime error te voorkomen (en voegt daar niets toe).
        // "axes[...]._ticks.0.formatter is null or not an object" krijg je namelijk
        // https://bitbucket.org/cleonello/jqplot/issue/201/highlighter-plugin-causes-error-on-hover meldt min of meer hetzelfde
        FCLTHeader.Requires({  js: ["../Localscripts/jqPlot/dist/plugins/jqplot.pointLabels.js"]});
    }



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

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

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

    var l_arr_x = [];
    for (x=0; x<l_data.arr_x.length; x++)
    {
      if (l_data.arr_x[x] === null || l_data.arr_x[x] == "")
          l_arr_x[x] = " ";
      else
          l_arr_x[x] = l_data.arr_x[x];
    }
    var l_arr_y = l_data.arr_y;
    var l_xas_naam = l_axes.xas.naam;
    var l_yas_naam = (l_axes.zas.naam ? l_axes.zas.naam : l_axes.yas[0].naam);
    var l_yas_count = l_axes.yas.length;

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

    var default_options = JSON.parse(l_init.default_options);
    var report_options = $.extend(default_options,
                                  JSON.parse(l_init.report_options));

<%
    switch (graphInit.graph_type)
    {
        case 1: // BarChart
%>
            var l_colors = (l_yas_count == 1?<%=S("udr_graph_colors1")%> : <%=S("udr_graph_colors2")%>);
            var effectivedata = l_arr_y;
            var props = { seriesDefaults:{ renderer: $.jqplot.BarRenderer
                                         , rendererOptions: { fillToZero: true }
                                         , pointLabels: { show: false }
                                         }
                        , stackSeries: true
                        //, series:[{label:'a'},{label:'b'}]
                        , legend: { show: (l_yas_count > 1)
                                  , placement: (l_yas_count > 1?'outsideGrid' : 'insideGrid')
                                  , location: 'ne'
                                  , labels: l_labels
                            }
                        , 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 (report_options.seriesDefaults)
            {
                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("udr_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("udr_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("udr_graph_colors1")%> : <%=S("udr_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' : 'insideGrid')
                                  , 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
                            );
                      });

        function toImg()
        {
            $("#myGraph").find("table.jqplot-table-legend").remove();
            var imgData = $("#myGraph").jqplotToImageStr({});
            document.getElementById('myGraph').innerHTML = "<img alt='<%=safe.htmlattr(L("fac_usrgraph"))%>' src=" + imgData + ">";
            $("#toImgButton").hide(); //untested
            FcltMgr.alert(L("lcl_viewimagealert"));
        }
    </script>
</head>
<body id="listbody">
    <%
        var widget_height = getQParam("widget_height", null);
        var nobuttons = getQParamInt("nobuttons", 0) == 1;
        var noheader = getQParamInt("noheader", 0) == 1;
        var mygraph_height = ((widget_height != null) ? parseInt(widget_height) : 500);
        var buttons = [];
        if(!nobuttons)
            var buttons = [ { icon: "fa-file-image", title: L("lcl_openimage"), action: "toImg()", id: "toImgButton" } ];
        if (!noheader)
            IFRAMER_HEADER(model.records_title, buttons);
    %>
            <div id="myGraph" style="height:<%=mygraph_height%>px;" ></div>
      </body>
    </html>
<%
    }
%>
