/// <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.GridEditingRow.WijmoGrid_render = function (element, contentItem) {

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

    contentItem.value.oncollectionchange = function () {
        var grid = c1ls.getGridContent(table, contentItem, { autoHide: false });
        contentItem.screen.WijmoGrid = grid;

        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: true,
            showSelectionOnRender: false,
            cellClicked: grid.OnCellClicked,
            cellStyleFormatter: grid.OnCellFormat
        });
    };

    c1ls.renderControl(contentItem);
};

myapp.GridEditingRow.AddNew_canExecute = function (screen) {
    return screen.Products.isLoaded;
};

myapp.GridEditingRow.AddNew_execute = function (screen) {
    myapp.showAddEditProduct(screen.Products.addNew(), {
        afterClosed: function (addEditScreen, navigationAction) {
            if (navigationAction === msls.NavigateBackAction.commit) {
                screen.WijmoGrid.EntityChanged(msls.EntityState.added);
            }
        }
    });
};

myapp.GridEditingRow.DeleteSelected_canExecute = function (screen) {
    $(".msls-header").removeClass("slidedown");
    $(".msls-footer").removeClass("slideup");
    return screen.Products.selectedItem != null;
};

myapp.GridEditingRow.DeleteSelected_execute = function (screen) {
    screen.Products.deleteSelected();
    screen.WijmoGrid.EntityChanged(msls.EntityState.deleted);
};