﻿// Control the Silverlight charting

function CHART() { };

CHART.Init = function() {
    //alert("CHART.Init");

    CHART.HaveLiterals = false;
    CHART.LayerID = "";
};

CHART.DefineLiterals = function(data, status) {
    //alert("CHART.DefineLiterals, status = " + status);

    CHART.BuildingDateChart = data.BuildingDateChart;
    CHART.CannotUpdateMap = data.CannotUpdateMap;
    CHART.ClickBar = data.ClickBar;
    CHART.ClickSlice = data.ClickSlice;
    CHART.Count = data.Count;
    CHART.Occurrences = data.Occurrences;
    CHART.OccurrencesPerDate = data.OccurrencesPerDate;
    CHART.Only = data.Only;
    CHART.Remaining = data.Remaining;
    CHART.Top = data.Top;
    //CHART.Total = data.Total;

    CHART.HaveLiterals = true;
    CHART.VisifirePath = "controls/SL.Visifire.Charts_2.2.6.xap";

    // Approximate first 11 pie colors for ColorSet="Visifire1"
    // Use mod function to choose
    CHART.Colors = [];
    CHART.Colors[0] = "#366CB0"   //       Blue = #366CB0
    CHART.Colors[1] = "#D37E25"   //       Gold = #D37E25
    CHART.Colors[2] = "#B13732"   //        Red = #B13732
    CHART.Colors[3] = "#87AA3F"   //      Green = #87AA3F
    CHART.Colors[4] = "#694C8C"   //     Purple = #694C8C
    CHART.Colors[5] = "#2D93AF"   // Light Blue = #2D93AF
    CHART.Colors[6] = "#89A9C2"   //     Silver = #89A9C2
    CHART.Colors[7] = "#007272"   //       Teal = #007272
    CHART.Colors[8] = "#739B00"   //    Greener = #739B00
    CHART.Colors[9] = "#D09D0C"   //    Mustard = #D09D0C
    CHART.Colors[10] = "#C95938"  //       Rust = #C95938
    CHART.Colors[11] = "#7B0509"  //   Dark Red = #7B0509
    CHART.Colors[12] = "#806A98"  //     Violet = #806A98
    CHART.Colors[13] = "#A15000"  //      Brown = #A15000
    CHART.Colors[14] = "#CC9F6F"  //        Tan = #CC9F6F

    CHART.SendDataRequest();
};

CHART.Reset = function() {
    //alert("CHART.Reset");

    CHART.PieChart = null;
    CHART.DateChart = null;
    CHART.SummaryData = null;
    CHART.DateData = null;
    CHART.AllDatesData = null;
    CHART.DateColor = "#FFFFFF";
    CHART.Total = 0;
    CHART.PieIndex = 0;
    CHART.MaxGroups = 10;
    CHART.BarStyle = "";
    CHART.BarLabels = "";
    CHART.LayerName = "Items";
    CHART.LayerQuery = "";
    CHART.WhatQuery = "";
    CHART.WhenQuery = "";
    CHART.DateFormat = "";
    CHART.HaveSubset = false;
    CHART.CanDrilldown = false;

    $("#bar-chart-header").hide();
    $("#bar-chart-data").html("");
    $("#pie-chart-data").html("");
};

CHART.GetChartData = function(lyrID) {
    //alert("CHART.GetChartData");
    CHART.LayerID = lyrID;
    CHART.Reset();

    if (CHART.HaveLiterals) {
        CHART.SendDataRequest();
    } else {
        $.ajax(
    	{
    	    type: "GET",
    	    url: "Data.aspx",
    	    data: "page=chartliterals",
    	    dataType: "json",
    	    error: UIHelper.AjaxError,
    	    success: CHART.DefineLiterals
    	});
    }
};
CHART.SendDataRequest = function() {
    $("#chart-date-summary-button").hide();

    var d = new Date();
    $.ajax(
  	    {
  	        type: "GET",
  	        url: "data.aspx",
  	        data: "page=chart&id=" + CHART.LayerID + "&t=" + d.getTime(),
  	        dataType: "json",
  	        error: CHART.AjaxError,
  	        success: CHART.ProcessChartData
  	    });
};
CHART.AjaxError = function(XMLHttpRequest, status) {
alert("CHART.AjaxError Type = " + status + ", Response = " + XMLHttpRequest.responseText);
    //UIHelper.ShowErrorInfo("Chart Error", XMLHttpRequest.responseXML.getElementsByTagName("body"));
    //my_window = window.open("", "ChartError", "height=500,width=500,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=yes,location=no,status=no");
    //my_window.document.write(XMLHttpRequest.responseText);
};

CHART.ProcessChartData = function (data, status) {
    //alert("CHART.ProcessChartData result = " + data.result + ", value = " + data.message);
    if (data.result == 0) {
        $("#pie-chart-header").html("<span>" + data.message + " </span>");
        CVS.StopProgressBar();

        return;
    }

    // Save the data locally
    CHART.Total = data.result;
    CHART.LayerName = data.name;
    CHART.MaxGroups = data.maxgroups;
    CHART.DateFormat = data.dateformat;
    CHART.BarStyle = data.barstyle;
    CHART.BarLabels = data.barlabels;
    CHART.SummaryData = data.summary;
    CHART.AllDatesData = data.alldates;
    CHART.CanDrilldown = (data.columns > 1);
    CHART.TopGroupsOnly = data.topgroups;

    // Create crime Chart
    CHART.PieChart = new Visifire2(CHART.VisifirePath, "PieChart", 275, 275);
    if (!UIHelper.IsLinkMap) {
        CHART.PieChart.preLoad = function (args) {
            var chart1 = args[0];
            chart1.Series[0].MouseLeftButtonUp = function (e) {
                //                alert("AxisXLabel = " + e.AxisXLabel
                //                    + ", Exploded = " + e.Exploded
                //                    + ", xval = " + e.XValue
                //                    + ", yval = " + e.YValue);
                if (CHART.CanDrilldown) {
                    // Find which slice is selected and use its color for the date chart
                    var selIdx = -1;
                    for (var idx = 0; idx < chart1.Series[0].DataPoints.length; idx++) {
                        if (e.AxisXLabel == chart1.Series[0].DataPoints[idx].AxisXLabel) {
                            if (!e.Exploded) selIdx = idx;
                        } else {
                            chart1.Series[0].DataPoints[idx].SetPropertyFromJs("Exploded", "false");
                        }
                    }
                    if (selIdx == -1) {
                        $("#bar-chart-header").hide();
                        $("#bar-chart-data").html("");
                        $("#chart-date-summary-button").show();
                        CHART.HaveSubset = false;
                        CHART.UpdateMapForAllDates();
                    } else {
                        CHART.BuildDateChart(e.AxisXLabel, selIdx, e.YValue);
                    }
                }
            };
        };
    }

    CHART.ShowPieChart();
    CHART.BuildPieChart();

    // Needed when undoing a drilldown
    CHART.LayerQuery = WHAT.GetLayerQuery(CHART.LayerID);

    $("#chart-date-summary-button").show();

    // Allow another postback request
    CVS.StopProgressBar();
};

CHART.BuildPieChart = function() {
    CHART.SummaryData.sort(CHART.SortByCount);

    var xaml, top, cursor, idx, max;

    if (CHART.CanDrilldown) {
        cursor = "Hand";
    } else {
        cursor = "Arrow";
    }

    if (CHART.SummaryData.length < CHART.MaxGroups) {
        CHART.PieIndex = CHART.SummaryData.length;
        top = "";
    } else {
        CHART.PieIndex = CHART.MaxGroups;
        top = "(" + CHART.Top + " " + CHART.MaxGroups + " " + CHART.Only + ")";
    }

    xaml = '<vc:Chart Theme="Theme2" Width="275" Height="275" ColorSet="Visifire1" Background="#F3F6FF" BorderBrush="#9FC6E9" Watermark="False" xmlns:vc="clr-namespace:Visifire.Charts;assembly=SLVisifire.Charts" >' + "\n" + "\n";
    xaml += '<vc:Chart.Titles>' + "\n";
    xaml += '<vc:Title Text="' + CHART.LayerName + " = " + CHART.Total + '" FontSize="10" />' + "\n";
    xaml += '<vc:Title Text="' + top + '" FontSize="10" />' + "\n";
    xaml += '</vc:Chart.Titles>' + "\n";
    xaml += '<vc:Chart.Legends>';
    xaml += '<vc:Legend Background="#F3F6FF" FontSize="7" LightingEnabled="False"/>';
    xaml += '</vc:Chart.Legends>';
    xaml += '<vc:Chart.Series>' + "\n";
    xaml += '<vc:DataSeries Cursor="' + cursor + '" RenderAs="Pie">' + "\n";
    xaml += '<vc:DataSeries.DataPoints>' + "\n";
    for (idx = 0; idx < CHART.PieIndex; idx++) {
        xaml += '<vc:DataPoint AxisXLabel="' + CHART.SummaryData[idx].Value + '" YValue="' + CHART.SummaryData[idx].Count + '" LabelText="#YValue" ToolTipText="#AxisXLabel (#Percentage%)"/>' + "\n";
    }

    //Do not show remaining if topGroupsOnly flag is set
    if (CHART.SummaryData.length > CHART.MaxGroups && !CHART.TopGroupsOnly) {
        var crntTotal = 0;
        var otherCount = CHART.SummaryData.length - CHART.PieIndex;
        for (idx = CHART.PieIndex; idx < CHART.SummaryData.length; idx++) {
            crntTotal += CHART.SummaryData[idx].Count;
        }
        
        xaml += '<vc:DataPoint AxisXLabel="' + CHART.Remaining + ' ' + otherCount + '" YValue="' + crntTotal + '" LabelText="#YValue" ToolTipText="#AxisXLabel (#Percentage%)"/>' + "\n";
    }

    xaml += '</vc:DataSeries.DataPoints>' + "\n";
    xaml += '</vc:DataSeries>' + "\n";
    xaml += '</vc:Chart.Series>' + "\n";
    xaml += '</vc:Chart>';

    // Set Chart data xml
    CHART.PieChart.setDataXml(xaml);

    // Let's see it
    CHART.PieChart.render("pie-chart-data");
};

CHART.BuildDateChart = function(crime, selIdx, count) {
    //alert("CHART.BuildDateChart = " + crime + ", idx = " + selIdx);
    $("#chart-date-summary-button").hide();
    $("#bar-chart-header").html("<p>" + CHART.BuildingDateChart + "...</p>");
    $("#bar-chart-header").show();
    $("#bar-chart-data").html("");

    var barLabel = "";
    var brushHighlight;
    var canDrillDown = true;
    var colorIdx = selIdx % CHART.Colors.length;
    CHART.DateColor = CHART.Colors[colorIdx];

    // Update the map for this crime type
    CHART.WhatQuery = WHAT.GetChartQuery(crime, CHART.LayerID);
    CHART.WhenQuery = UIHelper.WhenQuery;
    if (CHART.WhatQuery == "") {
        UIHelper.ShowStatusMessage(CHART.CannotUpdateMap, "warning");
        canDrillDown = false;
    } else {
        CHART.HaveSubset = true;
        UIHelper.UpdateChartDrilldownMap();
        $("#report-tab a").unbind("click");
        $("#report-tab a").bind("click", function(e) { UIHelper.SetupReportTab(); });
    }

    switch (CHART.BarLabels) {
        case "inside":
            barLabel = 'LabelEnabled="True" LabelStyle="Inside" LabelText="#YValue"';
            break;

        case "outside":
            barLabel = 'LabelEnabled="True" LabelStyle="Outside" LabelText="#YValue"';
            break;
    }

    // Create date Chart
    CHART.DateChart = new Visifire2(CHART.VisifirePath, "DateChart", 275, 275);
    CHART.DateChart.preLoad = function(args) {
        var chart1 = args[0];
        chart1.Series[0].MouseLeftButtonUp = function(e) {
            CHART.UpdateMapForDate(e.AxisXLabel);
            if (canDrillDown) {
                var brushNormal = '<SolidColorBrush xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Color="' + CHART.DateColor + '" />'
                if (CHART.BarStyle == "column") {
                    brushHighlight = '<LinearGradientBrush xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" StartPoint="0.5,0" EndPoint="0.5,1">';
                } else {
                    brushHighlight = '<LinearGradientBrush xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" StartPoint="1,0.5" EndPoint="0,0.5">';
                }
                brushHighlight += '<GradientStop Color="#FFFFFF00" Offset="0.0"/>'
                   + '<GradientStop Color="' + CHART.DateColor + '" Offset="1.0"/>'
                   + '</LinearGradientBrush>';
                for (var idx = 0; idx < chart1.Series[0].DataPoints.length; idx++) {
                    if (e.AxisXLabel == chart1.Series[0].DataPoints[idx].AxisXLabel) {
                        chart1.Series[0].DataPoints[idx].SetPropertyFromJs("Color", brushHighlight);
                    } else {
                        chart1.Series[0].DataPoints[idx].SetPropertyFromJs("Color", brushNormal);
                    }
                }
            }
        };
    };

    var xaml = '<vc:Chart Theme="Theme2" Width="275" Height="275" ColorSet="Visifire1" Background="#F3F6FF" BorderBrush="#9FC6E9" Watermark="False" xmlns:vc="clr-namespace:Visifire.Charts;assembly=SLVisifire.Charts" >' + "\n" + "\n";
    xaml += '<vc:Chart.Titles>' + "\n";
    xaml += '<vc:Title Cursor="Hand" Text="' + crime + '" FontSize="10"/>' + "\n";
    if (count > 1) {
        xaml += '<vc:Title Text="(' + count + ' ' + CHART.Occurrences + ')" FontSize="10"/>' + "\n";
    }
    xaml += '</vc:Chart.Titles>' + "\n";

    xaml += '<vc:Chart.AxesX>' + "\n";
    xaml += '<vc:Axis Title="' + CHART.OccurrencesPerDate + '" Interval="1" TitleFontSize="8">' + "\n";
    xaml += '<vc:Axis.AxisLabels>' + "\n";
    xaml += '<vc:AxisLabels FontSize="8"/>' + "\n";
    xaml += '</vc:Axis.AxisLabels>' + "\n";
    xaml += '</vc:Axis>' + "\n";
    xaml += '</vc:Chart.AxesX>' + "\n";
    xaml += '<vc:Chart.AxesY>' + "\n";
    xaml += '<vc:Axis Title="' + CHART.Count + '" TitleFontSize="10">' + "\n" + "\n";
    xaml += '<vc:Axis.AxisLabels>' + "\n";
    xaml += '<vc:AxisLabels FontSize="8"/>' + "\n";
    xaml += '</vc:Axis.AxisLabels>' + "\n";
    xaml += '</vc:Axis>' + "\n";
    xaml += '</vc:Chart.AxesY>' + "\n";

    xaml += '<vc:Chart.Series>' + "\n";
    xaml += '<vc:DataSeries Cursor="Hand" RenderAs="' + CHART.BarStyle + '" Color="' + CHART.DateColor + '">' + "\n";
    xaml += '<vc:DataSeries.DataPoints>' + "\n";

    CHART.DateData = CHART.SummaryData[selIdx].Dates;

    var crntTotal = 0;
    var crntDate = CHART.DateData[0].Date;
    for (idx = 0; idx < CHART.DateData.length; idx++) {
        if (CHART.DateData[idx].Date == crntDate) {
            crntTotal++;
        } else {
            //xaml += '<vc:DataPoint AxisXLabel="' + crntDate + '" YValue="' + crntTotal + '" LabelText="#YValue"/>' + "\n";
            xaml += '<vc:DataPoint AxisXLabel="' + crntDate + '" YValue="' + crntTotal + '" ' + barLabel + '/>' + "\n";
            crntTotal = 1;
            crntDate = CHART.DateData[idx].Date;
        }
    }

    xaml += '<vc:DataPoint AxisXLabel="' + crntDate + '" YValue="' + crntTotal + '" ' + barLabel + '/>' + "\n";

    xaml += '</vc:DataSeries.DataPoints>' + "\n";
    xaml += '</vc:DataSeries>' + "\n";
    xaml += '</vc:Chart.Series>' + "\n";
    xaml += '</vc:Chart>';

    //$("#pie-chart-data").hide();
    $("#bar-chart-data").show();

    // Set Chart data xml
    CHART.DateChart.setDataXml(xaml);

    // Let's see it
    CHART.DateChart.render("bar-chart-data");

    $("#bar-chart-header").html("<p>" + CHART.ClickBar + "</p>");
};

CHART.BuildAllDatesChart = function() {
    //alert("CHART.BuildAllDatesChart");
    $("#chart-date-summary-button").hide();
    $("#bar-chart-header").html("<p>" + CHART.BuildingDateChart + "...</p>");
    $("#bar-chart-header").show();
    $("#bar-chart-data").html("");

    var barLabel = "";
    var canDrillDown = true;
    CHART.DateColor = "#33cc33"; // CHART.Colors[colorIdx];

    switch (CHART.BarLabels) {
        case "inside":
            barLabel = 'LabelEnabled="True" LabelStyle="Inside" LabelText="#YValue"';
            break;

        case "outside":
            barLabel = 'LabelEnabled="True" LabelStyle="Outside" LabelText="#YValue"';
            break;
    }

    // Create date Chart
    CHART.DateChart = new Visifire2(CHART.VisifirePath, "AllDateChart", 275, 275);
    CHART.DateChart.preLoad = function(args) {
        var chart1 = args[0];
        chart1.Series[0].MouseLeftButtonUp = function(e) {
            CHART.WhatQuery = CHART.LayerQuery;
            CHART.UpdateMapForDate(e.AxisXLabel);
            if (canDrillDown) {
                var brushNormal = '<SolidColorBrush xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Color="' + CHART.DateColor + '" />'
                var brushHighlight = '<LinearGradientBrush xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" StartPoint="1,0.5" EndPoint="0,0.5">'
                   + '<GradientStop Color="#FFFFFF00" Offset="0.0"/>'
                   + '<GradientStop Color="' + CHART.DateColor + '" Offset="1.0"/>'
                   + '</LinearGradientBrush>';
                for (var idx = 0; idx < chart1.Series[0].DataPoints.length; idx++) {
                    if (e.AxisXLabel == chart1.Series[0].DataPoints[idx].AxisXLabel) {
                        chart1.Series[0].DataPoints[idx].SetPropertyFromJs("Color", brushHighlight);
                    } else {
                        chart1.Series[0].DataPoints[idx].SetPropertyFromJs("Color", brushNormal);
                    }
                }
            }
        };
    };

    var xaml = '<vc:Chart Theme="Theme2" Width="275" Height="275" ColorSet="Visifire1" Background="#F3F6FF" BorderBrush="#9FC6E9" Watermark="False" xmlns:vc="clr-namespace:Visifire.Charts;assembly=SLVisifire.Charts" >' + "\n" + "\n";
    xaml += '<vc:Chart.Titles>' + "\n";
    xaml += '<vc:Title Text=" " FontSize="10" />' + "\n";
    xaml += '</vc:Chart.Titles>' + "\n";

    xaml += '<vc:Chart.AxesX>' + "\n";
    xaml += '<vc:Axis Title="' + CHART.OccurrencesPerDate + '" Interval="1" TitleFontSize="8">' + "\n";
    xaml += '<vc:Axis.AxisLabels>' + "\n";
    xaml += '<vc:AxisLabels FontSize="8"/>' + "\n";
    xaml += '</vc:Axis.AxisLabels>' + "\n";
    xaml += '</vc:Axis>' + "\n";
    xaml += '</vc:Chart.AxesX>' + "\n";
    xaml += '<vc:Chart.AxesY>' + "\n";
    xaml += '<vc:Axis Title="' + CHART.Count + '" TitleFontSize="10">' + "\n";
    xaml += '<vc:Axis.AxisLabels>' + "\n";
    xaml += '<vc:AxisLabels FontSize="8"/>' + "\n";
    xaml += '</vc:Axis.AxisLabels>' + "\n";
    xaml += '</vc:Axis>' + "\n";
    xaml += '</vc:Chart.AxesY>' + "\n";

    xaml += '<vc:Chart.Series>' + "\n";
    xaml += '<vc:DataSeries Cursor="Hand" RenderAs="Bar" Color="' + CHART.DateColor + '">' + "\n";
    xaml += '<vc:DataSeries.DataPoints>' + "\n";

    for (idx = 0; idx < CHART.AllDatesData.length; idx++) {
        xaml += '<vc:DataPoint AxisXLabel="' + CHART.AllDatesData[idx].Date + '" YValue="' + CHART.AllDatesData[idx].Count + '" ' + barLabel + '/>' + "\n";
    }

    xaml += '</vc:DataSeries.DataPoints>' + "\n";
    xaml += '</vc:DataSeries>' + "\n";
    xaml += '</vc:Chart.Series>' + "\n";
    xaml += '</vc:Chart>';

    $("#bar-chart-data").show();

    // Set Chart data xml
    CHART.DateChart.setDataXml(xaml);

    // Let's see it
    CHART.DateChart.render("bar-chart-data");

    $("#bar-chart-header").html("<p>" + CHART.ClickBar + "</p>");
};

CHART.UpdateMapForDate = function(date) {
    // Format = 040609040609 (date range mmddyymmddyy)

    //alert("CHART.UpdateMapForDate = " + date);
    var when = "||";
    var pos = CHART.DateFormat.indexOf("mm");
    var mdy = date.substr(pos, 2);
    pos = CHART.DateFormat.indexOf("dd");
    mdy += date.substr(pos, 2);
    pos = CHART.DateFormat.lastIndexOf("y");
    mdy += date.substr(pos - 1, 2);

    //var mdy = date.substr(0, 2) + date.substr(3, 2) + date.substr(8, 2)

    if (WHEN.IsValid) when = WHEN.TimeSelection + "|" + WHEN.TimeType + "|" + WHEN.DOWSelection;

    CHART.WhenQuery = mdy + mdy + "|" + when;
    if (CHART.WhatQuery == "") {
        UIHelper.ShowStatusMessage(CHART.CannotUpdateMap, "warning");
    } else {
        UIHelper.UpdateChartDrilldownMap();
        $("#report-tab a").unbind("click");
        $("#report-tab a").bind("click", function(e) { UIHelper.SetupReportTab(); });

        $("#chart-all-dates-button").show();
    }
};

CHART.UpdateMapForAllDates = function() {
    //alert("CHART.UpdateMapForAllDates");
    if (CHART.WhatQuery == "") return;

    if (!CHART.HaveSubset) CHART.WhatQuery = CHART.LayerQuery;
    CHART.WhenQuery = UIHelper.WhenQuery;
    UIHelper.UpdateChartDrilldownMap();
    $("#report-tab a").unbind("click");
    $("#report-tab a").bind("click", function(e) { UIHelper.SetupReportTab(); });

    $("#chart-all-dates-button").hide();
};

CHART.ShowPieChart = function()
{
    // If returning from a drilldown query (date chart) return map to full query
//    if (CHART.HaveSubset) {
//        CHART.HaveSubset = false;
//        CHART.WhatQuery = UIHelper.WhatQuery;
//        CHART.WhenQuery = UIHelper.WhenQuery;
//        UIHelper.UpdateChartDrilldownMap();
//        $("#report-tab a").unbind("click");
//        $("#report-tab a").bind("click", function(e) { UIHelper.SetupReportTab(); });
//    }

    $("#chart-all-dates-button").hide();
    //$("#bar-chart-data").hide();
    if (UIHelper.IsLinkMap || !CHART.CanDrilldown) {
        $("#pie-chart-header").html("");
    } else {
        $("#pie-chart-header").html("<p>" + CHART.ClickSlice + "</p>");
    }
    //$("#pie-chart-data").show();
};

CHART.SortByCount = function(a, b)
{
    if (a.Count == b.Count) {
        return 0;
    } else {
        return (a.Count > b.Count) ? -1 : 1;
    }

};

CHART.SortByCrime = function(a, b)
{
    if (a.Col1 == b.Col1) {
        return 0;
    } else {
        return (a.Col1 < b.Col1) ? -1 : 1;
    }

};

CHART.SortByDate = function(a, b)
{
    if (a.Col2 == b.Col2) {
        return 0;
    } else {
        return (a.Col2 < b.Col2) ? -1 : 1;
    }

};
