/// <reference path="../GeneratedArtifacts/viewModel.js" />
/// <reference path="../Scripts/c1ls-4.0.20142.37.js" />

if (typeof c1ls === "undefined") {
    window.location.href = "http://bit.ly/c1ls-nuget";
}

// http://bit.ly/c1ls-grid
//
myapp.GridUnboundColumn.WijmoGrid_render = function (element, contentItem) {

    var table = $("<table/>");
    table.appendTo($(element));

    contentItem.value.oncollectionchange = function () {
        var grid = c1ls.getGridContent(table, contentItem);

        var region = grid.FindColumn("Region");
        region.allowSort = false;
        region.readOnly = true;

        region.cellFormatter = function (args) {
            if (args.row.type & wijmo.grid.rowType.data) {
                var obj = grid.GetRowEntity(args.row.dataRowIndex);
                args.$container.empty().append(RegionFromFIPS(obj.FIPS));
                return true;
            }
        };

        var year = grid.FindColumn("Year");
        year.dataFormatString = "d0";

        var value = grid.FindColumn("Value");
        value.dataFormatString = "c0";

        table.wijgrid({
            // initialization
            columns: grid.Columns,
            data: grid.Rows(),

            // editing
            editingMode: "none",
            afterCellUpdate: grid.OnCellUpdate,
            currentCellChanged: grid.OnCellChanged,

            // sorting
            allowSorting: true,
            sorting: grid.Sorting,

            // filtering
            showFilter: false,
            filtering: grid.Filtering,

            // selection
            selectionMode: "singleRow",
            showRowHeader: grid.ShowRowHeader,
            showSelectionOnRender: false,
            cellClicked: grid.OnCellClicked,
            cellStyleFormatter: grid.OnCellFormat
        });
    };

    c1ls.renderControl(contentItem);
};

var FarWest = [53, 41, 6, 32, 2, 15];
var GreatLakes = [55, 26, 17, 18, 39];
var MidEast = [36, 34, 10, 24, 11, 42];
var NewEngland = [23, 33, 50, 25, 44, 9];
var Plains = [38, 46, 27, 31, 19, 20, 29];
var RockyMountain = [30, 16, 56, 49, 8];
var Southeast = [5, 22, 28, 1, 21, 47, 54, 51, 37, 45, 13, 12];
var Southwest = [4, 35, 48, 40];

function RegionFromFIPS(fips) {
    if (FarWest.indexOf(fips) >= 0) {
        return "Far West";
    }
    else if (GreatLakes.indexOf(fips) >= 0) {
        return "Great Lakes";
    }
    else if (MidEast.indexOf(fips) >= 0) {
        return "Mideast";
    }
    else if (NewEngland.indexOf(fips) >= 0) {
        return "New England";
    }
    else if (Plains.indexOf(fips) >= 0) {
        return "Plains";
    }
    else if (RockyMountain.indexOf(fips) >= 0) {
        return "Rocky Mountain";
    }
    else if (Southeast.indexOf(fips) >= 0) {
        return "Southeast";
    }
    else if (Southwest.indexOf(fips) >= 0) {
        return "Southwest";
    }
    else {
        return "";
    }
}
