@using DashboardModel

@using C1.Web.Mvc.Grid

<script>

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

    $(document).ready(function () {

        var options = {
            spacing_open: 2,
            spacing_close: 2,
            onresize_end: function () {
                invalidateComponents();
                return true;
            }
        };
        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));
            });
        }
    });

    var inited;
    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 (inited)
                                        invalidateComponents();
                                }
                            }
                        }
                        if (!inited) {
                            var least = $("#layout-east");
                            var dashboardEast = least.layout(layoutOptions1);
                            dashboardEast.sizePane("south", least.outerHeight() * 0.5);
                        }
                        invalidateComponents();
                        inited = true;
                        return true;
                    }
                };
            }

            $('#dashboard').width(containerWidth * 0.99);
            $('#dashboard').height(containerHeight * 0.75);
            var dashboard = $('#dashboard').layout(layoutOptions);
            dashboard.sizePane("east", $('#dashboard').width() * 0.4);
        } else {
            if (flowLayout.children().length == 0)
                moveContent();
            flowLayout.outerWidth(getContainerWidth() * 0.95);
            invalidateComponents();
        }
    }

    function invalidateComponents() {
        var flowLayout = $(".flow-layout");
        if (flowLayout.css("display") == "none") {
            $("#chartOpportunities").height($("#chartOpportunities").parent().height() - 10);
            $("#chartRegionSale").height($("#chartRegionSale").parent().height() - 10);
        }

        $("#pivotGrid").width($("#pivotGrid").parent().width() * 0.98);
        var pivotGrid = wijmo.Control.getControl("#pivotGrid");
        pivotGrid.invalidate();
        
        var chartOpportunities = wijmo.Control.getControl("#chartOpportunities");
        chartOpportunities.refresh();

        var chartRegionSales = wijmo.Control.getControl("#chartRegionSale");
        chartRegionSales.refresh();
    }

    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("GetAnalysisData")', function (data) {
            var chartOpportunities = wijmo.Control.getControl("#chartOpportunities");
            chartOpportunities.itemsSource = minSale(data[1].items)  > 0 ? data[1].items : null;

            var chartRegionSales = wijmo.Control.getControl("#chartRegionSale");
            chartRegionSales.itemsSource = data[0].items;
        });
    }

    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",
            type: "POST"
        });
    }

    function minSale(list) {
        var min = Number.MAX_VALUE;
        $.each(list, function (i, v) {
            if (min > v.Sales)
                min = v.Sales;
        });
        return min;
    }

    function moveContent(reverse) {
        if (!reverse) {
            var flow = $(".flow-layout");
            var cb = $("#dashboard > .ui-layout-west,#dashboard > .ui-layout-center, #layout-east > .ui-layout-center, #layout-east > .ui-layout-south").children("DIV");
            for (var i = 0; i < cb.length; i++) {
                flow.append(cb[i]);
            }
        } else {
            var cb = $(".flow-layout").children();
            $("#layout-east > .ui-layout-south").append(cb[4]);
            $("#layout-east > .ui-layout-center").append(cb[3]);
            $("#dashboard > .ui-layout-center").append(cb[2]);
            $("#dashboard > .ui-layout-west").append(cb[1]);
            $("#dashboard > .ui-layout-west").append(cb[0]);
        }
    }
</script>

<h3>
    @Resources.DashboardDemo.AnalysisPage_Title
</h3>

@(Html.C1().PivotEngine().Id("indexEngine").Bind(ViewBag.ProductWiseSaleCollection as List<ProductsWiseSaleItem>)
        .RowFields(pfcb => pfcb.Items("Category", "Product"))
        .ColumnFields(cfcb => cfcb.Items("Region"))
        .ValueFields(vfcb => vfcb.Items("Sale")))


<div class="flow-layout">

</div>

<div id="dashboard">
    <div class="ui-layout-west">
        <div class="caption">@Resources.DashboardDemo.ProductWise_Header</div>

        @Html.C1().PivotPanel().ItemsSourceId("indexEngine")
    </div>
    <div class="ui-layout-center">

        @Html.C1().PivotGrid().ItemsSourceId("indexEngine").Id("pivotGrid").AutoSizeMode(AutoSizeMode.None)
    </div>
    <div class="ui-layout-east" id="layout-east">
        <div class="ui-layout-center">

            @(Html.C1().TreeMap().Id("chartRegionSale")
                            .DataLabel(l => l.Content("{name}"))
                            .Bind(ViewBag.RegionSales as List<ProductsWiseSaleItem>)
                            .Binding("Sale")
                            .BindingName("Region, Category")
                            .HeaderStyle(x =>
                            {
                                x.Halign("left");
                            })
                            .Header(@Resources.DashboardDemo.CategoryRegion_Sale)
                            .Tooltip(c =>
                            {
                                c.Content("<b>{name}</b><br />{value:c0}");
                            })
            )

        </div>
        <div class="ui-layout-south">

            @(Html.C1().FlexChart().Id("chartOpportunities")
                            .Bind(ViewBag.OpportunityItemList as List<Opportunity>)
                            .BindingX("LevelName")
                            .ChartType(C1.Web.Mvc.Chart.ChartType.Funnel)
                            .Series(sers =>
                            {
                                sers.Add().Name(Resources.DashboardDemo.Sale_Series).Binding("Sales");
                            }).AxisY(y =>
                            {
                                y.Position(C1.Web.Mvc.Chart.Position.None);
                            }).HeaderStyle(x =>
                            {
                                x.Halign("left");
                            }).Legend(C1.Web.Mvc.Chart.Position.Bottom)
                            .Header(@Resources.DashboardDemo.Opportunities_Header)
                            .DataLabel(x =>
                            {
                                x.Position(C1.Web.Mvc.Chart.LabelPosition.Center);
                                x.Content("{y:C0}");
                            }).Options(x =>
                            {
                                x.Funnel(o =>
                                {
                                    o.NeckHeight(0.2f);
                                });
                            }).Tooltip(t =>
                            {
                                t.Content("<b>{name}</b><br />{x} {value:c0}");
                            })
            )
        </div>
    </div>
</div>
<div>
    @Html.Partial("RangeSelector", ViewBag.DateSaleList as List<SaleItem>)
</div>
