@using C1.Web.Mvc.Grid

<script>

    $(window).resize(function () {
        relayout(window.__containerWidth, window.__containerHeight);
    });

    $(document).ready(function () {

        relayout()
        if (window.rangeSelector != null) {
            window.rangeSelector.rangeChanged.addHandler(function (s, e) {
                // perform related updates // e.g. modify displayed range of another chart
                refreshAll(Math.round(rangeSelector.min), Math.round(rangeSelector.max));
            });
        }
        refreshAll();
    });

    var inLayoutProgress = false;
    var layoutOptions;
    var layoutOptions1;
    function relayout(containerWidth, containerHeight) {

        var flowLayout = $(".flow-layout");
        if (flowLayout.css("display") == "none") {
            if (flowLayout.children().length != 0)
                moveContent(true);
        if (containerWidth == null)
            containerWidth = getContainerWidth();

        if (containerHeight == null)
            containerHeight = getContainerHeight();

        if (layoutOptions == null) {
            layoutOptions = {
                    fxName_open: "slide",
                    fxSpeed_open: "slow",
                    fxName_close: "slide",
                    fxSpeed_close: "slow",
                spacing_open: 2,
                spacing_close: 2,
                onresize_end: function () {

                    if (layoutOptions1 == null) {
                        layoutOptions1 = {
                                fxName_open: "slide",
                                fxSpeed_open: "slow",
                                fxName_close: "slide",
                                fxSpeed_close: "slow",
                            spacing_open: 2,
                            spacing_close: 2,
                            onresize_end: function () {
                                if (!inLayoutProgress)
                                    invalidateComponents();
                            }
                        }
                    }
                    if (!inLayoutProgress)
                    invalidateComponents();
                    return true;
                }
            };
        }
        inLayoutProgress = true;
        $('#dashboard').outerWidth(containerWidth*0.99);
        $('#dashboard').outerHeight(containerHeight - 200);
        var dashboard = $('#dashboard').layout(layoutOptions);
        var eastWidth = containerWidth * 0.4;// 40%
        dashboard.sizePane("east", eastWidth);

        setTimeout(function () {
            var center1 = $('#center1');
            var dashboardCenter = center1.layout(layoutOptions1);
            var dashboardCenterBelow = $('#center-below').layout(layoutOptions1);
            dashboardCenter.sizePane("south", center1.outerHeight() * 0.5);

            var dashboard = $('#dashboard').layout();
            var eastWidth = dashboard.state.east.size;
            var centerWidth = $('#dashboard').outerWidth() - eastWidth;
            dashboardCenterBelow.sizePane("east", centerWidth * 0.5);

            var least = $("#layout-east");
            var dashboardEast = least.layout(layoutOptions1);
            dashboardEast.sizePane("south", least.outerHeight() * 0.35);
            dashboardEast.sizePane("north", least.outerHeight() * 0.3);
        }, 300);
        invalidateComponents();
            inLayoutProgress = false;
        } else {
            if (flowLayout.children().length == 0)
                moveContent();
            flowLayout.outerWidth(getContainerWidth() * 0.98);

            invalidateComponents();
        }
    }

    function invalidateComponents() {
        var flowLayout = $(".flow-layout");
        if (flowLayout.css("display") == "none") {
            $("#budgetVSProfitChart").height(Math.max(100, $("#budgetVSProfitChart").parent().innerHeight() * 0.9));
            $("#chartSaleTopProd").height(Math.max(100, $("#chartSaleTopProd").parent().height() * 0.9));
            $("#chartSalesVsProfit").outerHeight(Math.max(100, $("#chartSalesVsProfit").parent().innerHeight()));
        }

        var chart = wijmo.Control.getControl("#budgetVSProfitChart");
        chart.refresh();
        chart = wijmo.Control.getControl("#chartSaleTopProd");
        var width = chart.hostElement.clientWidth;
        var angle = null;
        if (width < 250) {
            angle = 90;
        } else if (width < 580) {
            angle = 45;
        }
        chart.axisX.labelAngle = angle;
        chart.refresh();

        var chartSalesVsProfit = wijmo.Control.getControl("#chartSalesVsProfit");
        chartSalesVsProfit.refresh();
        var gridTopSaleCustomer = wijmo.Control.getControl("#gridTopSaleCustomer");
        gridTopSaleCustomer.refresh();

        layoutGauges();
        renderGaugeAxes();
    }

    function refreshAll(start, end) {

        var items = window.rangeSelector._chart.itemsSource.items;
        if (start == null)
            start = items[0].Date;
        if (end == null)
            end = items[items.length - 1].Date;


        refreshData(start, end, '@Url.Action("GetTopData")', function (data) {
            var chartSaleTopProd = wijmo.Control.getControl("#chartSaleTopProd");
            chartSaleTopProd.itemsSource = data[0].items;
            chartSaleTopProd.refresh();

            var gridTopSaleCustomer = wijmo.Control.getControl("#gridTopSaleCustomer");
            gridTopSaleCustomer.itemsSource = data[1].items;

            createGauges("#panGauges1", data[2].items);
            createGauges("#panGauges2", data[3].items);

            invalidateComponents();
        });
    }

    function refreshData(start, end, action, callback) {

        var startDate = new Date(start);
        var endDate = new Date(end);
        $.ajax(action, {
            success: function (data) {
                callback(data);
            },
            data: {
                startDate: (startDate.getMonth() + 1) + "/" + startDate.getDate() + "/" + startDate.getFullYear(),
                endDate: (endDate.getMonth() + 1) + "/" + endDate.getDate() + "/" + endDate.getFullYear()
            },
            dataType: "json"
        });
    }

    var DEFAULT_UNIT = 1000000;//1M
    var BAD_UNIT = 0.0000005;
    var GOOD_UNIT = 0.0000008;
    var DEFAULT_THICKNESS = 0.5;
    var COMPLETE_LEVEL = 0.8;
    var AXIS_UNIT = 20;

    var tt = new wijmo.Tooltip();
    tt.showAtMouse = true;
    function createGauges(target, items) {

        var gaugeElements = $(target + " > .gauge");
        for (var i = 0; i < gaugeElements.size(); i++) {
            var old = wijmo.Control.getControl(gaugeElements.get(i));
            if (old != null)
                old.dispose();
        }

        $.each($(target).find(".gauge-container"), function (i, v) {
            tt.setTooltip(v, null);
        });
        $(target).empty();

        //"#salesVSGoalGauge"
        var panGause = $(target);
        var data = [];
        var max = Number.MIN_VALUE;
        for (var i = 0; i < items.length; i++) {
            var item = items[i];

            var goal = item.Goal / DEFAULT_UNIT;
            var sale = item.Sales / DEFAULT_UNIT;
            var badGoal = item.Goal * BAD_UNIT;
            var goodGoal = item.Goal * GOOD_UNIT;
            max = Math.max(max, sale);

            data.push({
                "goal": goal,
                "sale": sale,
                "badGoal": badGoal,
                "goodGoal": goodGoal

            });
        }

        max = Math.floor(max / AXIS_UNIT) * AXIS_UNIT + AXIS_UNIT;
        for (var i = 0; i < items.length; i++) {
            var item = data[i];

            var container = document.createElement("DIV");
            $(container).addClass("gauge-container");
            tt.setTooltip(container, wijmo.Globalize.format(item.sale, 'C0') + " (M)");
            panGause.append(container);

            // Create the bullet-graph
            var bullet = document.createElement("DIV");
            $(bullet).addClass("bullet-graph");
            $(container).append(bullet);


            var bulletGraph = new wijmo.gauge.BulletGraph(bullet);
            bulletGraph.min = 0;
            bulletGraph.max = max;
            bulletGraph.value = item.sale;
            bulletGraph.bad = item.badGoal;
            bulletGraph.good = item.goodGoal;
            bulletGraph.target = item.goal;
            bulletGraph.thickness = 0.7;

            if (items[i].CompletePrecent < COMPLETE_LEVEL)
                bulletGraph.pointer.color = "red";
            bulletGraph.pointer.thickness = DEFAULT_THICKNESS;
            bulletGraph.face.thickness = 0;

            var title = document.createElement("DIV");
            $(title).addClass("gauge-title");
            $(title).html(items[i].Name);
            $(container).append(title);
        }

        panGause.data("max", max);
    }

    function layoutGauges() {

        var isFlow = $(".flow-layout").css("display") != "none";
        $.each($(".gaugesChart"), function (i, v) {
            var gaugesTotalHeight = !isFlow ? $(v).parent().innerHeight() : 250;
            $(v).outerHeight(gaugesTotalHeight);
            var gauges = $(v).find(".gauge-container");
            var gaugeHeight = (gaugesTotalHeight - $("#lblGauges1").outerHeight()) / (gauges.length + 1); // 1 slot for the axis
            gauges.outerHeight(gaugeHeight);
            gauges.find(".bullet-graph").outerHeight(gaugeHeight);
            gauges.find(".gauge-title").css("top", gaugeHeight / 4);
        });

    }

    function createGaugeAxes(target) {

        var panGause = $(target);
        if (panGause.children().count == 0) return;
        var count = panGause.data("max") / AXIS_UNIT;
        var axisLength = panGause.width() - 100;// 100 padding for title;
        var startLocation = 100;
        var step = axisLength / count;

        $(target).find(".gauge-axis-container").empty();

        var axisContainer = $(target).find(".gauge-axis-container");
        if (axisContainer.length == 0) {
            axisContainer = document.createElement("DIV");
            $(axisContainer).addClass("gauge-axis-container");
        } else {
            axisContainer.empty();
            axisContainer = axisContainer.get(0);
        }
        panGause.append(axisContainer);

        var bottom = $(axisContainer).prev().outerHeight();
        for (var i = 0; i <= count; i++) {
            var axis = document.createElement("DIV");
            $(axis).addClass("gauge-axis-marker");
            $(axis).css("left", (startLocation + i * step) + "px");
            $(axis).css("bottom", (bottom - 5) + "px");
            $(axisContainer).append(axis);

            var axisTitle = document.createElement("SPAN");
            $(axisTitle).html(i * AXIS_UNIT);
            $(axisTitle).addClass("gauge-axis-title");
            $(axisTitle).css("left", (startLocation + i * step - 5) + "px");
            $(axisTitle).css("bottom", (bottom - 25) + "px");
            $(axisContainer).append(axisTitle);
        }
    }

    function renderGaugeAxes() {

        createGaugeAxes("#panGauges1");
        createGaugeAxes("#panGauges2");
        $(".bullet-graph").width($("#panGauges1").width() - 100);
        $.each($(".bullet-graph"), function (index, value) {
            var g = wijmo.Control.getControl(value);
            g.refresh();
        });
    }

    function tooltipTemplate(ht) {
        return "<b>" + ht.name + "</b><br/>" + wijmo.Globalize.format(ht.x, 'MMM') + " " + wijmo.Globalize.format(ht.y, 'C0');
    }

    function moveContent(reverse) {
        if (!reverse) {
            var flow = $(".flow-layout");
            var cb = $("#center-above, #center-below > .ui-layout-center, #center-below > .ui-layout-east,#layout-east > .ui-layout-north,#layout-east > .ui-layout-center,#layout-east > .ui-layout-south").children("DIV");
            for (var i = 0; i < cb.length; i++) {
                flow.append(cb[i]);
            }

            $(".wj-flexchart").height(250);
            invalidateComponents();
        } else {
            var cb = $(".flow-layout").children();
            $("#center-above").append(cb[0]);
            $("#center-below > .ui-layout-center").append(cb[1]);
            $("#center-below > .ui-layout-east").append(cb[2]);
            $("#center-below > .ui-layout-east").append(cb[3]);
            $("#layout-east > .ui-layout-north").append(cb[4]);
            $("#layout-east > .ui-layout-center").append(cb[5]);
            $("#layout-east > .ui-layout-south").append(cb[6]);
        }
    }
</script>

<h3>
    @Resource.DashboardPage_Title
</h3>

<div class="flow-layout">

</div>

<div id="dashboard">
    <div class="ui-layout-center" id="center1">

        <div class="ui-layout-center" id="center-above">
            <c1-flex-chart binding-x="Date" id="budgetVSProfitChart" header="@Resource.BudgetVSProfit_Header" legend-position="Top">
                <c1-flex-chart-axis c1-property="AxisY" format="N1,,M" major-unit="200000" title="(US$ M)"></c1-flex-chart-axis>
                <c1-flex-chart-axis c1-property="AxisX" format="MMM"></c1-flex-chart-axis>
                <c1-flex-chart-title-style c1-property="HeaderStyle" halign="left" font-size="18pt"></c1-flex-chart-title-style>
                <c1-items-source source-collection="@ViewBag.BudgetItemList"></c1-items-source>
                <c1-flex-chart-series binding="Profit" name="@Resource.CurrentYear_Series" chart-type="LineSymbols">
                </c1-flex-chart-series>
                <c1-flex-chart-series binding="ProirProfit" name="@Resource.PriorYear_Series" chart-type="LineSymbols">
                </c1-flex-chart-series>
                <c1-flex-chart-tooltip content="tooltipTemplate"></c1-flex-chart-tooltip>
            </c1-flex-chart>
        </div>

        <div class="ui-layout-south" id="center-below">
            <div class="ui-layout-center" id="center-below-left">

                <c1-flex-chart binding-x="Name" id="chartSaleTopProd" header="@Resource.TopSaleProducts_Header" legend-position="None">
                    <c1-flex-chart-axis c1-property="AxisY" format="N0,," title="(US$ M)"></c1-flex-chart-axis>
                    <c1-flex-chart-axis c1-property="AxisX" overlapping-labels="Auto"></c1-flex-chart-axis>
                    <c1-flex-chart-title-style c1-property="HeaderStyle" halign="left" font-size="18pt"></c1-flex-chart-title-style>
                    <c1-items-source source-collection="@ViewBag.TopSaleProductList"></c1-items-source>
                    <c1-flex-chart-series binding="Sales" chart-type="Column">
                    </c1-flex-chart-series>
                </c1-flex-chart>

            </div>
            <div class="ui-layout-east">
                <div class="caption">
                    @Resource.TopSaleCustomer_Header
                </div>
                <c1-flex-grid auto-generate-columns="false" class="grid" id="gridTopSaleCustomer" auto-sized-column="true"
                              is-read-only="true" allow-sorting="true" selection-mode="@((SelectionMode.Cell))">
                    <c1-flex-grid-column binding="Name" width="*"></c1-flex-grid-column>
                    <c1-flex-grid-column binding="Sales" format="C0" width="*"></c1-flex-grid-column>
                    <c1-flex-grid-column binding="Profit" format="C0" width="*"></c1-flex-grid-column>
                </c1-flex-grid>
            </div>
        </div>
    </div>
    <div class="ui-layout-east" id="layout-east">
        <div class="ui-layout-north">
            <c1-flex-chart binding-x="Date" id="chartSalesVsProfit" header="@DashboardDemo.Resource.SalesVsProfit_Header"
                           legend-position="Bottom">
                <c1-flex-chart-axis c1-property="AxisX" overlapping-labels="Auto" format="MMM"></c1-flex-chart-axis>
                <c1-flex-chart-axis c1-property="AxisY" labels="true" axis-line="false"
                                    format="N0,," title="@(DashboardDemo.Resource.Sale_Series + " (US$ M)")" major-unit="4000000"
                                    position="Right"></c1-flex-chart-axis>
                <c1-flex-chart-title-style c1-property="HeaderStyle" halign="left" font-size="18pt"></c1-flex-chart-title-style>
                <c1-items-source source-collection="@ViewBag.BudgetItemList"></c1-items-source>
                <c1-flex-chart-series binding="Sales" chart-type="Column" name="@DashboardDemo.Resource.Sale_Series">
                </c1-flex-chart-series>
                <c1-flex-chart-series binding="Profit" chart-type="Line" name="@DashboardDemo.Resource.Profit_Series">
                    <c1-flex-chart-axis c1-property="AxisY" min="0"
                                        axis-line="true" format="N1,," major-unit="200000"
                                        title="@(DashboardDemo.Resource.Profit_Series + " (US$ M)")" position="Left"></c1-flex-chart-axis>
                </c1-flex-chart-series>
                <c1-flex-chart-tooltip content="tooltipTemplate"></c1-flex-chart-tooltip>
            </c1-flex-chart>
        </div>

        <div class="ui-layout-center">
            <div id="salesVSGoal" class="gaugesChart">
                <div id="lblGauges1" class="caption">@DashboardDemo.Resource.CategorySales_Header</div>
                <div id="labUnits1" class="caption">@DashboardDemo.Resource.Unit_Text</div>

                <div id="panGauges1">
                </div>
            </div>
        </div>

        <div class="ui-layout-south">
            <div id="regionalSalesVsGoal" class="gaugesChart">
                <div id="lblGauges2" class="caption">@DashboardDemo.Resource.RegionSales_Header</div>
                <div id="labUnits2" class="caption">@DashboardDemo.Resource.Unit_Text</div>

                <div id="panGauges2">
                </div>
            </div>
        </div>
    </div>
</div>
<div>
    @Html.Partial("RangeSelector", ViewBag.DateSaleList as List<SaleItem>)
</div>