﻿$(document).ready(function() {
    $('.graph_wrapper').each(function() {
        var $this = $(this),    //a div that wrappes the entire control
            $div_container = $this.find('div[id$=_container]'),  //div, that will contain the chart
            $hid_url = $this.find(':hidden[id$=_url]'), //hidden field containing the url for retrieving data
            graph_url = $hid_url.val(), //url for retrieving data
            $div_info = $this.find('div[id$=_info]');   //div for displaying hover/click info

        var responseHandler = function(obj, status) {
            if (obj && status == 'success') {
                if (obj && obj.GraphDataLists) {
                    var options = {},
                        dataSeries = [],
                        dataList,
                        xaxis = 'xaxis',
                        yaxis = 'yaxis';

                    //set grid
                    options.grid = {
                        autoHighlight: obj.AutoHighlight,
                        clickable: obj.Clickable,
                        hoverable: obj.Hoverable,
                        mouseActivateRadius: obj.MouseActivateRadius,
                        borderWidth: obj.BorderWidth
                    };
                    if (obj.GridColor) {
                        options.grid.tickColor = obj.GridColor;
                    };
                    if (obj.BorderColor) {
                        options.grid.color = obj.BorderColor;
                    };
                    //set legend
                    options.legend = {
                        show: obj.ShowLegend,
                        position: obj.LegendPosition,
                        noColumns: obj.LegendColumns || Math.ceil(obj.GraphDataLists.length / 2.0)
                    };

                    //set data series
                    for (var i = 0; i < obj.GraphDataLists.length; i++) {
                        dataList = obj.GraphDataLists[i];

                        //set axis
                        xaxis = 'xaxis';
                        yaxis = 'yaxis';
                        if (dataList.AxisX == 2) {
                            xaxis = 'x2axis';
                        };
                        if (dataList.AxisY == 2) {
                            yaxis = 'y2axis';
                        };
                        options[xaxis] = options[xaxis] || {};
                        options[yaxis] = options[yaxis] || {};
                        if (typeof (dataList.MinValueX) != 'undefined' && typeof (dataList.MaxValueX) != 'undefined' && dataList.MinValueX != dataList.MaxValueX) {
                            options[xaxis].min = dataList.MinValueX;
                            options[xaxis].max = dataList.MaxValueX;
                        };
                        if (typeof (dataList.MinValueY) != 'undefined' && typeof (dataList.MaxValueY) != 'undefined' && dataList.MinValueY != dataList.MaxValueY) {
                            options[yaxis].min = dataList.MinValueY;
                            options[yaxis].max = dataList.MaxValueY;
                        };
                        //DP: yes, I know it's ugly to use new Function()... but here I need a function that's not a closure
                        if (dataList.AxisTickFormatX) {
                            options[xaxis].tickFormatter = new Function('value', 'axis', 'return \'{0}\'.format(value)'.format(dataList.AxisTickFormatX));
                        };
                        if (dataList.AxisTickFormatY) {
                            options[yaxis].tickFormatter = new Function('value', 'axis', 'return \'{0}\'.format(value)'.format(dataList.AxisTickFormatY));
                        };

                        //init default options for graph
                        dataList.options = {
                            lines: { show: false },
                            points: { show: false },
                            bars: { show: false },
                            label: '',
                            xaxis: dataList.AxisX,
                            yaxis: dataList.AxisY,
                            data: []
                        };

                        //set options based on settings specified
                        //graph type (line, point, bar)
                        if (dataList.GraphType.match(/line/)) {
                            dataList.options.lines = {
                                show: true,
                                lineWidth: dataList.LineWidth || 2,
                                fill: dataList.Fill,
                                fillColor: dataList.FillColor
                            };
                        };
                        if (dataList.GraphType.match(/point/)) {
                            dataList.options.points = {
                                show: true,
                                radius: dataList.PointRadius || 3,
                                fill: dataList.Fill,
                                fillColor: dataList.FillColor
                            };
                        };
                        if (dataList.GraphType.match(/bar/)) {
                            dataList.options.bars = {
                                show: true,
                                barWidth: dataList.BarWidth || 1,
                                align: dataList.BarAlign,
                                fill: dataList.Fill,
                                fillColor: dataList.FillColor
                            };
                        };
                        //graph color
                        if (dataList.Color) {
                            dataList.options.color = dataList.Color;
                        };
                        //check if x axis is date/time format
                        if (dataList.DataTypeX && dataList.DataTypeX.match(/^(time|date)$/i)) {
                            //this is a global setting, not dataseries specific
                            options[xaxis].mode = 'time';
                            options[xaxis].timeformat = dataList.DateFormat || '%d.%m.%y';
//                            options[xaxis] = {
//                                mode: 'time',
//                                timeformat: dataList.DateFormat || '%d.%m.%y'
//                            };
                        };
                        //labels for legend
                        if (dataList.Title) {
                            dataList.options.label = dataList.Title;
                        };

                        //extract data
                        var point;
                        for (var j = 0; j < dataList.DataPoints.length; j++) {
                            point = dataList.DataPoints[j];
                            dataList.options.data[dataList.options.data.length] = [point.X, point.Y];
                        };

                        dataSeries[dataSeries.length] = dataList.options;
                    };

                    //draw the graphs
                    $.plot($this, dataSeries, options);

                    //bind hover/click events
                    if (obj.Clickable) {
                        $div_container.bind('plotclick', function(e, pos, item) {
                            alert('click');
                            if ($div_info.length) {
                                if (item) {
                                    var x = item;
                                };
                            };
                        });
                    };

                    if (obj.Hoverable) {
                        $div_container.bind('plotclick', function(e, pos, item) {
                            alert('hover');
                        });
                    };
                };
            } else {
                $this.html('<img src="/Images/Common/personal_graph_sample.png" alt="personal graph sample" style="width: 620px;" />');
            };
        };

        //retrieve the graph data from server
        var date = new Date();
        $.getJSON(graph_url, { time: '{0}{1}{2}'.format(date.getDate(), date.getHours(), date.getMinutes()) }, responseHandler);
    });
});