<% /*
     $Revision$
     $Id$

    fac_usrgraph.inc

*/%>

<!-- #include file="./fac_usrrap.inc" -->
<!-- #include file="../shared/json2.js" -->

<%

function fac_graph_type (usrgraph_key)
{
   var sql;
   var oRs;
   sql  = "SELECT fac_usrgraph_type FROM fac_usrgraph WHERE fac_usrgraph_key = "+usrgraph_key;
   oRs = Oracle.Execute( sql );
   return oRs("fac_usrgraph_type").Value;
}

function fac_graph_sql_query (p_tableName, l_functie_key, fclt_key, params)
{
   // Wat variabelen
   var sql,sql1,sql_where,sql_order, sql_rep;
   var oRs, oRs2;

   // Start opbouw SQL-query
   sql1 = "SELECT * FROM " + p_tableName;

   // De '3D' conditie
   var sqlWhere3D = usrrap.create3Dclause(p_tableName, l_functie_key);

   // Order by clause
   sql = "SELECT fac.usrrap_orderby(" + safe.quoted_sql(p_tableName) + ") FROM dual";
   oRs = Oracle.Execute(sql);
   sql_order = oRs.Fields(0).Value;
   sql_order = ''
   oRs.close();
   //

   sql_where = "";
   sql_cond = " WHERE ";

   if (sqlWhere3D != "")
   {
     sql_where +=  sql_cond  + sqlWhere3D
     sql_cond = " AND ";
   }

   if (fclt_key > 0)
   {
     sql_where +=  sql_cond  + " FCLT_KEY=" + fclt_key;
     sql_cond = " AND ";
   }

   for (var i=0; i<=9; i++)
   {
     if (params.fclt_text[i])
     {
       sql_where += sql_cond + " FCLT_TEXT" + i + "=" + safe.quoted_sql(params.fclt_text[i]);
       sql_cond = " AND ";
     }
   }


   sql_rep = sql1 + sql_where + sql_order;
   return (sql_rep);
}

function getGraphInit(usrgraph_key, fclt_key, params)
{
    var sql = "SELECT "+lcl.xsqla("fac_usrgraph_omschrijving", "fac_usrgraph_key") +","
            + "       fac_usrgraph_type,"
            + "       fac_usrgraph_view_name,"
            + "       fac_usrgraph_maxrows,"
            + "       fac_usrgraph_orderby,"
            + "       fac_functie_key,"
            + "       fac_usrgraph_options,"
            + "       fac_usrgraph_limiet0,"
            + "       fac_usrgraph_limiet1,"
            + "       fac_usrgraph_limiet2,"
            + "       fac_usrgraph_limiet3"
            + "  FROM fac_usrgraph"
            + " WHERE fac_usrgraph_key = "+usrgraph_key;
    var oRs = Oracle.Execute( sql );

    var sql_select = fac_graph_sql_query(oRs("fac_usrgraph_view_name").Value, oRs("fac_functie_key").Value, fclt_key, params);
    var fac_option = oRs("fac_usrgraph_options").Value || "{}";
    var limiet_arr = [ oRs("fac_usrgraph_limiet0").Value
                     , oRs("fac_usrgraph_limiet1").Value
                     , oRs("fac_usrgraph_limiet2").Value
                     , oRs("fac_usrgraph_limiet3").Value
                     ];
    var userGraphInit = { title       : oRs("fac_usrgraph_omschrijving").Value || ""
                        , type        : oRs("fac_usrgraph_type").Value
                        , maxrows     : oRs("fac_usrgraph_maxrows").Value || 0
                        , limiet      : limiet_arr
                        , fac_options : fac_option
                        , sql_orderby : oRs("fac_usrgraph_orderby").Value || ""
                        , sql         : sql_select
                        };
    oRs.Close();
    return userGraphInit;
}

function getGraphColors(graphInit)
{
    var myColors = "";
    var myXs = "";

    var sql = graphInit.sql + (graphInit.sql_orderby? " ORDER BY " + graphInit.sql_orderby : "");
    oRs = Oracle.Execute(sql);

    // Eerst kijken of de optionele kolom fclt_color aanwezig is.
    var hasColorField = false;
    if (!oRs.Eof)
    {
      for (var i = 0; i < oRs.Fields.Count; i++)
      {
        if (oRs.Fields(i).Name.toUpperCase() == "FCLT_COLOR")
          hasColorField = true;
      }
    }

    if (hasColorField)
    {
      while (!oRs.Eof)
      {
          myColors += (myColors != "" ? ", '" : "['") + oRs("fclt_color").Value +  "'";
          myXs += (myXs != ""? ", '" : "") + oRs("fclt_color").Value + " | " + oRs("fclt_xas_").Value;
          oRs.Movenext();
      }
      myColors += "]";
    }

    if (myColors == "")
      myColors = false;

    oRs.Close();
    return myColors;
}

function getGraphAxes(sql)
{
    var kolomnaam;
    var l_url = null;
    var l_xas = {};
    var l_yas = {};
    var l_zas = [];
    var oRs = Oracle.Execute(sql); // eerst een keer voor de kolomnamen

    for (i= 0; i < oRs.Fields.Count; i++)
    {
        var kolomnaam = oRs.Fields(i).Name;

        if (kolomnaam.substring(0,8).toUpperCase() == "FCLT_URL")
        {
            l_url = kolomnaam;
        }
        if (kolomnaam.substring(0,9).toUpperCase() == "FCLT_XAS_")
        {
            l_xas = {kolom: kolomnaam, naam: kolomnaam.substring(9)};
        }
        if (kolomnaam.substring(0,9).toUpperCase() == "FCLT_YAS_")
        {
            l_yas = {nr: 1, kolom: kolomnaam, naam: kolomnaam.substring(9)};
            l_zas.push(l_yas);
        }
        // Alle overige y-assen.
        for (j=2; j < 10; j++)
        {
            if (kolomnaam.substring(0,10).toUpperCase() == "FCLT_YAS"+j+"_")
            {
                l_yas = {nr: j, kolom: kolomnaam, naam: kolomnaam.substring(10)};
                l_zas.push(l_yas);
            }
        }
    }
    oRs.Close();

    var userGraphAxes = { url: l_url
                        , xas: l_xas
                        , yas: l_zas
                        };
    return userGraphAxes;
}

function getGraphData(graphInit, graphAxes)
{
    var sql = "SELECT * FROM (" + graphInit.sql + ")";
    if (graphInit.sql_orderby)
    {
        // overrule de standaard (hieronder): sorteren wat in de kolomnaam fac_usrgraph_orderby(!) staat..
        sql = sql + " ORDER BY " + graphInit.sql_orderby;
    }
    else
    {
        // standaard sorteren op de hoogte y-as waarde (van hoog naar laag, b.v top 10).
        sql = sql + " ORDER BY " + graphAxes.yas[0].kolom + " DESC";
        graphInit.sql_orderby = graphAxes.yas[0].kolom + " DESC"; //Is nu ook voor getColors te gebruiken.
    }
    //
    var l_arr_x = [];
    var l_arr_y = [];
    var l_arr_xy = [];
    var l_arr_url = [];

    var waarde = [];
    var maxrows = graphInit.maxrows

    // Maak een array aan voor alle beschikbare kolommen Y0..Yn
    for (z=0; z < graphAxes.yas.length; z++)
    {
        l_arr_y.push([]);
    }
    var teller = 0;
    var oRs = Oracle.Execute(sql);
    while (!oRs.Eof)
    {
        teller++;

        if (graphAxes.url)
        {
              l_arr_url.push(oRs(graphAxes.url).Value) || "";
        }

        l_x = oRs(graphAxes.xas.kolom).Value;

        // Tekst onder een bar graph inkorten zodat die de opmaak niet verstoort.
        if (graphInit.type == 1 && l_x.length > 20)
        {
            l_x = l_x.substring(0, 17) + "...";
        }

        if (teller > graphInit.maxrows && graphInit.maxrows != 0)
        {
            l_x = safe.jsstring(L("lcl_fac_graph_others"));
            l_arr_x[maxrows-1] = l_x;
            l_arr_xy[maxrows-1] = [l_x, l_arr_y[0][maxrows-1]];
            for (z=0; z < graphAxes.yas.length; z++)
            {
                l_y = oRs(graphAxes.yas[z].kolom).Value;
                l_arr_y[z][maxrows-1] = l_arr_y[z][maxrows-1] + l_y;
            }
        }
        else
        {
            l_arr_x.push(l_x);
            for (z=0; z < graphAxes.yas.length; z++)
            {
                l_y = oRs(graphAxes.yas[z].kolom).Value;
                l_arr_y[z].push(l_y);
            }
            l_y0 = oRs(graphAxes.yas[0].kolom).Value;
            l_arr_xy.push([l_x, l_arr_y[0][teller-1]]);
        }
        oRs.Movenext();
    }
    oRs.Close();

    var userGraphData = { teller: teller
                        , arr_x: l_arr_x
                        , arr_y: l_arr_y
                        , arr_url: l_arr_url
                        , arr_xy: l_arr_xy
                        };
    return userGraphData;
}

function fac_graph_generate (usrgraph_key, fclt_key, params)
{
    var params = params || {};
    var graphInit = getGraphInit(usrgraph_key, fclt_key, params);
    var graphAxes = getGraphAxes(graphInit.sql);
    var graphData = getGraphData(graphInit, graphAxes);
    if (fac_graph_type(usrgraph_key) == 1 || fac_graph_type(usrgraph_key) == 3 || fac_graph_type(usrgraph_key) == 4)
       var graphColors = getGraphColors(graphInit);
    // De sql-componenten moeten er nu uit: anders zijn ze zichtbaar in de grafiek html/js.
    delete graphInit.sql_orderby;
    delete graphInit.sql;

    if (graphData.teller > 0)
    {
%>
        var JSONdata = '<%=safe.jsstring(JSON.stringify(graphInit))%>';
        var l_init = eval('(' + JSONdata + ')');
        var fac_options = eval('(' + l_init.fac_options + ')');

        var l_userColors = <%=(graphColors? graphColors : 'false')%>;

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

        var JSONdata = '<%=safe.jsstring(JSON.stringify(graphData))%>';
        var l_data = eval('(' + JSONdata + ')');
<%
        // Onderstaande variabelen worden gebruikt in fac-options.
%>
        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;

        $.jqplot.config.enablePlugins = true;
        var handler = function(ev, gridpos, datapos, neighbor, plot)
                      {
                        if (neighbor)
                        {
                          // FcltMgr.alert('x:' + neighbor.data[0] + ' y:' + neighbor.data[1]);
                          if (l_data.arr_url[neighbor.pointIndex])
                            FcltMgr.openDetail(l_data.arr_url[neighbor.pointIndex], l_arr_x[neighbor.pointIndex]);
                        }
                      };
        $.jqplot.eventListenerHooks.push(['jqplotClick', handler]);
<%
        switch (graphInit.type)
        {
            case 1: // BarChart
%>
                var l_colors = (l_yas_count == 1?<%=S("udr_graph_colors1")%> : <%=S("udr_graph_colors2")%>);
                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)}
                            , title: l_init.title
                            , seriesColors: (l_userColors? l_userColors : 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>'
                                           }
                            };
                plot1 = $.jqplot( 'myGraph'
                                , l_arr_y
                                , $.extend(true, props, fac_options)
                                );
<%
                break;
            case 2:  // MeterGauge
%>
                var l_x = l_arr_x[0];
                var l_y = l_arr_y[0];
                var limiet0 = l_init.limiet[0];
                var limiet1 = l_init.limiet[1];
                var limiet2 = l_init.limiet[2];
                var limiet3 = l_init.limiet[3];
                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: limiet0
                                                                 , max: limiet3
                                                                 , intervals: [limiet1, limiet2, limiet3]
                                                                 , intervalColors: ['red','orange','green']
                                                                 }
                                              }

                            };
                plot1 = $.jqplot( 'myGraph'
                                , [ [100* l_x / l_y] ]
                                , $.extend(true, props, fac_options)
                                );

<%
                break;
            case 3:  // pie-chart
%>
                var l_colors = <%=S("udr_graph_pie_colors")%>;
                var props = { title: l_init.title
    	                      , seriesColors: (l_userColors? l_userColors : 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'
                                    }
                            };
                plot1 = $.jqplot( 'myGraph'
    	                          , [l_data.arr_xy]
    	                          , $.extend(true, props, fac_options)
                                )
<%
                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 props = { seriesDefaults: { pointLabels: { show: true
                                                             }
                                              }
                            , stackSeries: false
                            , title: l_init.title
                            , seriesColors: (l_userColors? l_userColors : 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>'
                                           }
                            };
                plot1 = $.jqplot( 'myGraph'
                                , l_arr_y
                                , $.extend(true, props, fac_options)
                                );
<%
                break;
            default:
                break;
        }
    } // if teller
}

%>
