﻿(function ($) {

    var _ChartIndex = 0;

    $.fn.charttable = function (options) {
        return this.each(function () {
            var l_Table;
            var l_TableDiv;
            var l_ChartId;
            var l_ChartDiv;
            var l_ToggleDataLink;

            l_Table = $(this);
            l_ChartId = 'chart' + (++_ChartIndex);
            l_ChartDiv = $('<div id="' + l_ChartId + '" class="chart"></div>');

            l_TableDiv = l_Table.wrap('<div id="chartdata' + _ChartIndex + '"></div>')
            l_TableDiv.hide();
            l_TableDiv.before(l_ChartDiv);

            //l_ToggleDataLink = $('<a href="#" style="position:relative; top:-1.5em; left:4px;">Show/Hide Data</a>');
            l_ToggleDataLink = $('<a href="#" style="">Show/Hide Data</a>');
            l_ToggleDataLink.click(function () { $(l_TableDiv).toggle(); return false; });
            l_TableDiv.before(l_ToggleDataLink);

            // table first row is header
            // table first col is series labels
            // table second col is series values

            /*
            var chart = new Highcharts.Chart({
            chart: {
            renderTo: l_ChartId,
            defaultSeriesType: 'column'
            },
            title: {
            text: 'Data extracted from a HTML table in the page'
            },
            xAxis: {
            categories: ['Apples', 'Pears', 'Plums', 'Bananas', 'Oranges']
            },
            yAxis: {
            title: {
            text: 'Units'
            }
            },
            tooltip: {
            formatter: function() {
            return '<b>'+ this.series.name +'</b><br/>'+
            this.y +' '+ this.x.toLowerCase();
            }
            },
            plotOptions: {
            column: {
            data: 'datatable',
            // define a custom data parser function for both series
            dataParser: function(data) {
            var table = document.getElementById(data),
            // get the data rows from the tbody element
            rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr'),
            // define the array to hold the real data
            result = [], 
            // decide which column to use for this series
            column = { 'Jane': 0, 'John': 1 }[this.options.name];
								
            // loop through the rows and get the data depending on the series (this) name
            for (var i = 0; i < rows.length; i++) {						
            result.push(
            parseInt(
            rows[i].getElementsByTagName('td')[column]. // the data cell
            innerHTML
            )
            );
            }
            return result;
            }
            }
            },
            series: [{
            name: 'Jane'
            }, {
            name: 'John'
            }]
            });
		
            */
            if (l_Table.hasClass('chart-ly')) {
                //alert('pies');

                chart = new Highcharts.Chart({
                    chart: {
                        renderTo: l_ChartId//,
                        //margin: [50, 200, 60, 170]
                    },
                    credits: {
                        enabled: false
                    },
                    title: {
                        text: '' // could be the closest <hx>, or table title tag
                    },
                    plotArea: {
                        shadow: null,
                        borderWidth: null,
                        backgroundColor: null
                    },
                    tooltip: {
                        formatter: function () {
                            return '<b>' + this.point.name + '</b>: ' + this.y; // +' %';
                        }
                    },
                    plotOptions: {
                        pie: {
                            allowPointSelect: true,
                            dataLabels: {
                                enabled: true,
                                formatter: function () {
                                    return this.point.y;
                                },
                                color: 'white',
                                style: {
                                    font: '11px Trebuchet MS, Verdana, sans-serif'
                                }
                            }
                        }
                    },
                    /*legend: {
                    layout: 'vertical',
                    style: {
                    left: 'auto',
                    bottom: 'auto',
                    right: '50px',
                    top: '100px'
                    }
                    },*/
                    series: [{
                        type: 'pie',
                        name: 'Browser share',
                        /*data: [
                        ['Firefox',   44.2],
                        ['IE7',       26.6],
                        {
                        name: 'IE6',
                        y: 20,
                        sliced: true,
                        selected: true
                        },
                        ['Chrome',    3.1],
                        ['Safari',    2.7],
                        ['Opera',     2.3],
                        ['Mozilla',   0.4]
                        ]*/
                        dataParser: function (data) {
                            //alert('dataParsercalled');
                            /*var table = document.getElementById(data),
                            // get the data rows from the tbody element
                            rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr'),
                            // define the array to hold the real data
                            result = [], 
                            // decide which column to use for this series
                            column = { 'Jane': 0, 'John': 1 }[this.options.name];
								
                            // loop through the rows and get the data depending on the series (this) name
                            for (var i = 0; i < rows.length; i++) {
                            result.push(
                            parseInt(
                            rows[i].getElementsByTagName('td')[column]. // the data cell
                            innerHTML
                            )
                            );
                            }
                            return result;
                            */
                            l_Results = [];

                            $('tr:gt(0)', l_Table).each(function () {
                                l_Results.push([$('td:eq(0)', this).text(), parseFloat($('td:eq(1)', this).text())]);
                            });
                            //l_Results.push(['first', 20]);
                            //l_Results.push(['second', 50]);
                            //l_Results.push(['third', 70]);
                            //l_Results.push(50);
                            //l_Results.push(80);

                            return l_Results;
                        }

                    }]
                });


            } else if (l_Table.hasClass('chart-xsy')) {
                //alert('lines');




                //l_ChartInfo.series = [];
                var l_XAxisLabels = [];
                var l_SeriesLabels = [];
                var l_Points = []; //= new Object();// = [];
                var l_RemoveRows = [];

                var l_debug = false;
                $('tr:gt(0)', l_Table).each(function () {
                    var l_Row = $(this)
                    var l_Cells = l_Row.children('td, th');
                    if (l_Cells.size() < 3) { l_RemoveRows.push(l_Row); return; }

                    var l_XLabel = $(l_Cells.get(0)).text();
                    if (IsEmptyString(l_XLabel)) { l_RemoveRows.push(l_Row); return; }
                    if ($.inArray(l_XLabel, l_XAxisLabels) < 0) l_XAxisLabels.push(l_XLabel);

                    var l_SeriesLabel = $(l_Cells.get(1)).text();
                    if (IsEmptyString(l_SeriesLabel)) { l_RemoveRows.push(l_Row); return; }
                    if ($.inArray(l_SeriesLabel, l_SeriesLabels) < 0) l_SeriesLabels.push(l_SeriesLabel);

                    var l_YValue = parseValue($(l_Cells.get(2)).text());
                    if (IsEmptyString(l_YValue)) {
                        l_YValue = null;
                    } else {
                        //parse it
                        if (isNaN(l_YValue)) { l_RemoveRows.push(l_Row); return; }
                        l_YValue = parseFloat(l_YValue);
                        if (isNaN(l_YValue)) { l_RemoveRows.push(l_Row); return; }
                    }

                    l_Points.push([l_SeriesLabel, l_XLabel, l_YValue]);
                    //l_Points[l_SeriesLabel][l_XLabel] = l_YValue;

                    /*
                    if(l_debug) return;
                    alert(l_SeriesLabel + ' - ' + l_XLabel + ' - ' + l_YValue);
                    l_debug=true;
                    */
                    //alert($(l_Cells.get(0)).text());
                    //for (var i = 0; i < l_Values.length; i++) { if (l_Values[i] === l_Value) { return; } }   // already exists

                });


                for (var l_RemoveRowIndex = l_RemoveRows.length - 1; l_RemoveRowIndex >= 0; l_RemoveRowIndex--) {
                    var l_RemoveRow = l_RemoveRows[l_RemoveRowIndex];
                    l_RemoveRow.remove();
                    //alert('removerow' + l_RemoveRow);
                }


                var l_XAxisTitle = ''; //'Order Date';//Text:$('th:eq(0),td:eq(0)', $('tr:eq(0)', l_Table)).text()
                var l_YAxisTitle = ''; //'Sales';
                var l_SeriesTitle = ''; //'Affiliate';


                var l_ChartInfo = {
                    credits: {
                        enabled: false
                    },
                    chart: {
                        renderTo: l_ChartId,
                        defaultSeriesType: 'line'/*,
					margin: [50, 250, 100, 80]*/
                    },
                    title: {
                        //FIX: todo text: l_SeriesTitle + ' ' + l_YAxisTitle + ' by ' + l_XAxisTitle,
                        text: '',
                        style: {
                            margin: '10px auto 0 auto'
                        }
                    },
                    /*subtitle: {
                    text: 'Source: WorldClimate.com',
                    style: {
                    margin: '0 100px 0 0' // center it
                    }
                    },*/
                    xAxis: {
                        title: {
                            text: l_XAxisTitle
                        },
                        categories: l_XAxisLabels,
                        labels: {
                            rotation: -45,
                            align: 'right',
                            style: {
                                font: 'normal 11px Verdana, sans-serif'
                            }
                        }
                    },
                    yAxis: {
                        title: {
                            text: l_YAxisTitle
                        },
                        plotLines: [{
                            value: 0,
                            width: 1,
                            color: '#A0A0A0'
                        }]
                    },
                    tooltip: {
                        formatter: function () {
                            return '' +
								'<table>' +
								'<tr><th>' + l_SeriesTitle + ':</th><td>' + this.series.name + '</td></tr>' +
								'<tr><th>' + l_XAxisTitle + ':</th><td>' + this.x + '</td></tr>' +
								'<tr><th>' + l_YAxisTitle + ':</th><td>' + this.y + '</td></tr>' +
								'</table>';
                        }
                        //,formatter: function() { return '' + this.series.name + '<br />' + this.x + ': <b>' + this.y + '</b>'; }
                    },
                    /*legend: {
                    layout: 'vertical',
                    style: {
                    left: 'auto',
                    bottom: 'auto',
                    right: '10px',
                    top: '50px'
                    }
                    },*/
                    series: []
                };



                //l_ChartInfo.chart.defaultSeriesType = 'column';
                //l_ChartInfo['chart']['defaultSeriesType'] = 'column';
                //l_ChartInfo['plotOptions']['column']['stacking'] = 'normal';		

                l_SeriesLabels.sort();
                for (var l_SeriesIndex = 0; l_SeriesIndex < l_SeriesLabels.length; l_SeriesIndex++) {
                    l_SeriesLabel = l_SeriesLabels[l_SeriesIndex];

                    var l_Series = {
                        name: l_SeriesLabel,
                        data: []
                    };
                    for (var l_XIndex = 0; l_XIndex < l_XAxisLabels.length; l_XIndex++) { l_Series.data.push(null); }
                    l_ChartInfo.series.push(l_Series);
                }

                for (var l_PointIndex = 0; l_PointIndex < l_Points.length; l_PointIndex++) {
                    var l_Point = l_Points[l_PointIndex];
                    var l_SeriesIndex = $.inArray(l_Point[0], l_SeriesLabels);
                    var l_XIndex = $.inArray(l_Point[1], l_XAxisLabels);
                    l_ChartInfo.series[l_SeriesIndex].data[l_XIndex] = l_Point[2];
                }

                //// each series has just 1 value
                //l_ChartInfo.chart.defaultSeriesType = 'pie';
                //l_ChartInfo.series = [l_ChartInfo.series[8]];

                //l_ChartInfo.chart.defaultSeriesType = 'column';
                //l_ChartInfo.series = [l_ChartInfo.series[6], l_ChartInfo.series[8]];

                //l_ChartInfo.chart.defaultSeriesType = 'bar';  // needs to be a tall graph
                //l_ChartInfo.series = [l_ChartInfo.series[6]];


                //for (var l_YIndex = 0; l_YIndex < l_Points.length; l_YIndex++) {
                /*			var l_YIndex = $.inArray(l_SeriesLabel, l_SeriesLabels);
                var l_Point = l_Points[l_YIndex];
                if (l_Point[0] === l_SeriesLabel){
                //var l_X = ;
                l_Series.data[$.inArray(l_Point[1], l_XAxisLabels)] = l_Point[2];
                }
                //l_Series.data.push(null);
                //}			
                */


                if (l_Table.hasClass('chart-column-stacked')) {
                    $.extend(true, l_ChartInfo, {
                        chart: {
                            defaultSeriesType: 'column'
                        },
                        plotOptions: {
                            column: {
                                stacking: 'normal'
                            }
                        },
                        tooltip: {
                            formatter: function () {
                                return '<b>' + this.x + '</b><br/>' + this.series.name + ': ' + this.y + '<br/>' + 'Total: ' + this.point.stackTotal;
                            }
                        }
                    });
                } else if (true) {
                    $.extend(true, l_ChartInfo, {
                        plotOptions: {
                            line: {
                                lineWidth: 1,
                                marker: {
                                    enabled: false,
                                    states: {
                                        hover: {
                                            enabled: true
                                        }
                                    }   
                                }
                            }
                        }
                    });


                }


                chart = new Highcharts.Chart(l_ChartInfo);






                /*
                alert("Series = " + l_SeriesLabels.length);
                alert("X Labels = " + l_XAxisLabels.length);
                alert("Points = " + l_Points.length);
                */



                /*
                var l_SeriesLabels = getUniqueValues(l_Table, 0);
                var l_XAxisLabels = getUniqueValues(l_Table, 1);

                l_ChartInfo.xAxis = {
                title: { text:'Order Date' }, //Text:$('th:eq(0),td:eq(0)', $('tr:eq(0)', l_Table)).text()
                categories: l_XAxisLabels,

                labels: {
                rotation: -45,
                align: 'right',
                style: {
                font: 'normal 11px Verdana, sans-serif'
                }
                }
                };
				
                l_ChartInfo.yAxis = {
                title: {
                text: 'Sales'
                },
                plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
                }]
                };
                //alert(l_ChartInfo.xAxis.title.text);
                //alert($('th:eq(0),td:eq(0)', $('tr:eq(0)', l_Table)).text());
                */

                /*			
                l_SeriesLabels.sort();
				
                //for each row
                //  parse series
                //  parse xaxis
                //  parse value

				
                l_Series.data = [];
			
                var l_DataPoint = { x:3, y:20 };
                l_Series.data.push(l_DataPoint);

                l_DataPoint = { x:4, y:25 };
                l_Series.data.push(l_DataPoint);

                l_DataPoint = { x:1, y:30 };
                l_Series.data.push(l_DataPoint);

                l_DataPoint = { x:2, y:null };
                l_Series.data.push(l_DataPoint);


                //var l_DataPoint = 5;//{ 5 };
                //l_Series.data.push(l_DataPoint);
			
                l_ChartInfo.series.push(l_Series);
                */







                /*,
                series: [{
                name: 'Tokyo',
                data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
                }, {
                name: 'New York',
                data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
                }, {
                name: 'Berlin',
                data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
                }, {
                name: 'London',
                data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
                }]*/
                /*
                function getSelectFilter(colIdx, header) {
                var html = "<select id='filter_" + colIdx + "' class='filter'><option value=''>" + options['selectOptionLabel'] + "</option>";
                var cells = rows.find('td:nth-child(' + (colIdx + 1) + ')');
                var values = [];
                $.each(cells, function() {
                var txt = $(this).text();
                if (!txt || txt === '&nbsp;') { return; }
                for (var i = 0; i < values.length; i++) { if (values[i] === txt) { return; } } // Contains
                values.push(txt);
                });
                values.sort();
                $.each(values, function() {                
                html += '<option value="' + this.replace('"','&#034;') + '">' + this + '</option>';
                });
                html += '</select>';
                return html;
                }
                */

            }


        });
    };

    function IsEmptyString(Value) {
        if (Value === null) return true;
        if (typeof (Value) != 'string') return undefined;
        if (Value.length === 0) return true;
        Value = Value.replace(/\s/g, '');
        return (Value.length === 0);
    }

    function getUniqueValues(l_Table, l_ColumnIndex) {
        var l_Values = [];

        $('td:nth-child(' + (l_ColumnIndex + 1) + ')', l_Table).each(function () {
            var l_Value = parseValue($(this).text());
            for (var i = 0; i < l_Values.length; i++) { if (l_Values[i] === l_Value) { return; } }   // already exists
            l_Values.push(l_Value);
        });
        return l_Values;
    }

    function parseValue(Text) {
        if (!isNaN(Text)) {
            var l_FloatValue = parseFloat(Text);
            if (!isNaN(l_FloatValue)) return l_FloatValue;
        }
        var l_DateValue = Date.parse(Text);
        if (!isNaN(l_DateValue)) return Text; //FIX:? l_DateValue;

        return Text;
    }


    // col1: label
    // col2: yaxis
    // chart types: pie, column


    // col1: label
    // col2: xaxis
    // col3: yaxis
    // chart types: xyline, scatter, etc..

})(jQuery);


