@using C1.Web.Mvc.Grid
<script type="text/javascript">
    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;

    $(window).resize(function () {
        updateDashboard();
    });

    $(document).ready(function () {
        initNSLayout();

        var categorySalesVsGoal = c1.getService('categorySalesVsGoal'),
            regionSalesVsGoal = c1.getService('regionSalesVsGoal');
        createGauges(".salesVSGoal", categorySalesVsGoal.items);
        createGauges(".regionalSalesVsGoal", regionSalesVsGoal.items);

        updateDashboard();
    });

    function initNSLayout() {
        var wsSplitLayout = c1.getService('wsSplitLayout'),
            nsSplitLayout = c1.getService('nsSplitLayout');

        nsSplitLayout.definition = wsSplitLayout.definition;
        nsSplitLayout.orientation = 1;
        var tiles = [];
        var checkSplitTile = function (item) {
            if (item instanceof c1.nav.split.SplitTile) {
                item.size = null;
                tiles.push(item);
            } else if (item instanceof c1.nav.split.SplitGroup) {
                if (item.children) {
                    item.children.forEach(function (child) {
                        checkSplitTile(child);
                    });
                }
            }
        }
        nsSplitLayout.items.forEach(function (item) {
            checkSplitTile(item);
        });

        nsSplitLayout.items.clear();
        tiles.forEach(function (tile) {
            nsSplitLayout.items.push(tile);
        })
    }

    function resetTileContentsSize() {
        var eleClasses = ['budgetVSProfitChart', 'chartSaleTopProd', 'chartSalesVsProfit'];
        for (var i = 0; i < eleClasses.length; i++) {
            var domEle = document.querySelector('.' + eleClasses[i]);
            if (domEle) {
                domEle.removeAttribute('style');
            }
        }
    }

    function updateDashboard() {
        var dashboard = wijmo.Control.getControl('#dashboard');
        resetTileContentsSize();

        var wsSplitLayout = c1.getService('wsSplitLayout'),
            nsSplitLayout = c1.getService('nsSplitLayout'),
            layout = document.body.clientWidth < 1000 ? nsSplitLayout : wsSplitLayout;

        if (dashboard.layout === layout) {
            dashboard.refresh();
        } else {
            dashboard.layout = layout;
        }
    }

    function refreshAll(start, end) {
        refreshData(start, end, '@Url.Action("GetTopData")', function (data) {
            var top3SellingProducts = c1.getService('top3SellingProducts'),
                top7SaleCustomers = c1.getService('top7SaleCustomers'),
                categorySalesVsGoal = c1.getService('categorySalesVsGoal'),
                regionSalesVsGoal = c1.getService('regionSalesVsGoal');

            top3SellingProducts.sourceCollection = data[0].items;
            top7SaleCustomers.sourceCollection = data[1].items;
            categorySalesVsGoal.sourceCollection = data[2].items;
            regionSalesVsGoal.sourceCollection = data[3].items;
        });
    }

    function tileContentRefreshing(sender, e) {
        var eleCtl = sender.hostElement,
            tileEle = eleCtl.parentElement.parentElement,
            height = $(tileEle).innerHeight();
        if (sender instanceof wijmo.chart.FlexChartBase) {
            height -= 12;
        } else if (sender instanceof wijmo.grid.FlexGrid) {
            height -= 5;
        }
        $(eleCtl).outerHeight(height);
    }

    function gaugeRefreshing(sender, e) {
        var jEleGauge = $(sender.hostElement),
            jEleGaugeContainer = jEleGauge.closest('.gauge-container'),
            jEleTileGauge = jEleGaugeContainer.closest('.gaugesChart'),
            jEleLblGauge = jEleTileGauge.children('.lblGauges').first(),
            jEleTile = jEleTileGauge.closest('.wj-li-content'),
            jEleTitle = jEleGaugeContainer.children('.gauge-title');

        jEleGauge.width(jEleGaugeContainer.parent().width() - 100);
        var gaugesTotalHeight = jEleTile.innerHeight() - 10;
        jEleTileGauge.outerHeight(gaugesTotalHeight);
        var gauges = jEleTileGauge.find(".gauge-container");
        var gaugeHeight = (gaugesTotalHeight - jEleLblGauge.outerHeight()) / (gauges.length + 1);
        jEleGaugeContainer.outerHeight(gaugeHeight);
        jEleGauge.outerHeight(gaugeHeight);
        jEleTitle.css("top", gaugeHeight / 4);
        createGaugeAxes(jEleGaugeContainer.parent());
    }

    function createGauges(target, items) {
        if ($(target).length == 0) {
            return;
        }

        var panGauges = $(target).children('.panGauges').first();

        var gaugeElements = panGauges.find(".wj-gauge");
        for (var i = 0; i < gaugeElements.size(); i++) {
            var gauge = wijmo.Control.getControl(gaugeElements.get(i));
            if (gauge != null)
                gauge.dispose();
        }

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

        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");
            wijmo.addClass(container, "gauge-container");
            tt.setTooltip(container, wijmo.Globalize.format(item.sale, 'C0') + " (M)");
            panGauges.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, {
                min: 0,
                max: max,
                value: item.sale,
                bad: item.badGoal,
                good: item.goodGoal,
                target: item.goal,
                thickness: 0.7,
                refreshing: gaugeRefreshing
            });
            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);
        }
        panGauges.data("max", max);
        createGaugeAxes(panGauges);
    }
    function createGaugeAxes(panGauges) {
        if (panGauges.children().count == 0) return;
        var count = panGauges.data("max") / AXIS_UNIT;
        var axisLength = panGauges.width() - 100;// 100 padding for title;
        var startLocation = 100;
        var step = axisLength / count;

        panGauges.find(".gauge-axis-container").empty();

        var axisContainer = panGauges.find(".gauge-axis-container");
        if (axisContainer.length == 0) {
            axisContainer = document.createElement("DIV");
            $(axisContainer).addClass("gauge-axis-container");
        } else {
            axisContainer.empty();
            axisContainer = axisContainer.get(0);
        }
        panGauges.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 tooltipTemplate(ht) {
        return "<b>" + ht.name + "</b><br/>" + wijmo.Globalize.format(ht.x, 'MMM') + " " + wijmo.Globalize.format(ht.y, 'C0');
    }

    function categorySalesVsGoalChanged(sender, e) {
        createGauges(".salesVSGoal", sender.items);
    }

    function regionSalesVsGoalChanged(sender, e) {
        createGauges(".regionalSalesVsGoal", sender.items);
    }

    function chartSaleTopProdRefreshing(sender, e) {
        tileContentRefreshing(sender, e);
        var width = sender.hostElement.clientWidth;
        var angle = null;
        if (width < 250) {
            angle = 90;
        } else if (width < 580) {
            angle = 45;
        }
        sender.axisX.labelAngle = angle;
    }
</script>

<c1-items-source id="top3SellingProducts" disable-server-read="true"
                 source-collection="@(ViewBag.Top3SellingProducts as List<SaleItem>)"></c1-items-source>
<c1-items-source id="top7SaleCustomers" disable-server-read="true"
                 source-collection="@(ViewBag.Top7SaleCustomers as List<SaleItem>)"></c1-items-source>
<c1-items-source id="categorySalesVsGoal" disable-server-read="true"
                 source-collection="@(ViewBag.CategorySalesVsGoal as List<SaleGoalItem>)"
                 source-collection-changed="categorySalesVsGoalChanged"></c1-items-source>
<c1-items-source id="regionSalesVsGoal" disable-server-read="true"
                 source-collection="@(ViewBag.RegionSalesVsGoal as List<SaleGoalItem>)"
                 source-collection-changed="regionSalesVsGoalChanged"></c1-items-source>


<c1-split-layout id="wsSplitLayout" orientation="Horizontal">
    <c1-split-group orientation="Vertical" size="6*">
        <c1-split-tile show-header="false" size="*">
            <c1-flex-chart binding-x="Date" header="@Resource.BudgetVSProfit_Header"
                           legend-position="Top" refreshing="tileContentRefreshing" class="budgetVSProfitChart">
                <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>
        </c1-split-tile>
        <c1-split-group orientation="Horizontal" size="*">
            <c1-split-tile show-header="false" size="*">
                <c1-flex-chart binding-x="Name" header="@Resource.TopSaleProducts_Header"
                               legend-position="None" refreshing="chartSaleTopProdRefreshing"
                               items-source-id="top3SellingProducts" class="chartSaleTopProd">
                    <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>
            </c1-split-tile>
            <c1-split-tile show-header="false" size="*">
                <div class="caption">
                    @Resource.TopSaleCustomer_Header
                </div>
                <c1-flex-grid auto-generate-columns="false" class="grid" auto-sized-column="true"
                              is-read-only="true" allow-sorting="true"
                              selection-mode="@((SelectionMode.Cell))" items-source-id="top7SaleCustomers">
                    <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>
            </c1-split-tile>
        </c1-split-group>
    </c1-split-group>
    <c1-split-group orientation="Vertical" size="4*">
        <c1-split-tile show-header="false" size="*">
            <c1-flex-chart binding-x="Date" header="@Resource.SalesVsProfit_Header"
                           legend-position="Bottom" refreshing="tileContentRefreshing" class="chartSalesVsProfit">
                <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="@(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="@Resource.Sale_Series">
                </c1-flex-chart-series>
                <c1-flex-chart-series binding="Profit" chart-type="Line" name="@Resource.Profit_Series">
                    <c1-flex-chart-axis c1-property="AxisY" min="0"
                                        axis-line="true" format="N1,," major-unit="200000"
                                        title="@(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>
        </c1-split-tile>
        <c1-split-tile show-header="false" size="*">
            <div class="salesVSGoal gaugesChart">
                <div class="lblGauges caption">@Resource.CategorySales_Header</div>
                <div class="labUnits caption">@Resource.Unit_Text</div>
                <div class="panGauges"></div>
            </div>
        </c1-split-tile>
        <c1-split-tile show-header="false" size="*">
            <div class="regionalSalesVsGoal gaugesChart">
                <div class="lblGauges caption">@Resource.RegionSales_Header</div>
                <div class="labUnits caption">@Resource.Unit_Text</div>
                <div class="panGauges"></div>
            </div>
        </c1-split-tile>
    </c1-split-group>
</c1-split-layout>

<c1-split-layout id="nsSplitLayout" orientation="Vertical"></c1-split-layout>

<div class="flex vertical" style="width:100%;height:100%;overflow:hidden;">
    <div>
        <h3>
            @Resource.DashboardPage_Title
        </h3>
    </div>
    <div class="auto" style="overflow:auto">
        <c1-dashboard-layout id="dashboard" style="height:100%"></c1-dashboard-layout>
    </div>
    <div class="rangeSelector-container">
        @Html.Partial("RangeSelector", ViewBag.RangeSelectorModel as RangeSelectorModel)
    </div>
</div>