/*
  backgrid-calendar-cell 1.0.0
*/
(function (root, factory) {

    if (typeof define === 'function' && define.amd) {
        // AMD
        define(["underscore", "backgrid"], factory);
    } else if (typeof exports === 'object') {
        // CommonJS
        module.exports = factory(require("underscore"), require("backgrid"));
    } else {
        // Browser globals
        factory(root._, root.Backgrid);
    }

}(this, function (_, Backgrid) {

    //Fix require config issue with Underscore.
    if (!_)
        _ = this._;

    //Cell which is used only to add a colspan header cell. It will rendered only on the table's header, but not in the body if the
    //body's row class is a ColSpanRow class.
    Backgrid.Extension.ColSpanEmptyCell = Backgrid.Cell.extend({
        notRender: true,
    });

    Backgrid.Extension.MultiLevelHeader = Backgrid.Header.extend({
        levelsCount: 1,
        rowLevels: null,
        initialize: function (options) {
            this.columns = options.columns;
            if (!(this.columns instanceof Backbone.Collection)) {
                this.columns = new Columns(this.columns);
            }

            this.rowLevels = [];

            for (var i = 1; i <= this.levelsCount; i++) {
                this.rowLevels.push(new Backgrid.HeaderRow({
                    columns: this.columns.filter(function (col) {
                        if (col.get('headerCell').prototype.level == i)
                            return col;
                    }),
                    collection: this.collection
                }));
            }
        },
        render: function () {
            var that = this,
                $el = this.$el;
            _.each(this.rowLevels, function (row) {
                $el.append(row.render().$el);
            });
            this.delegateEvents();
            return this;
        },
        remove: function () {
            var args = arguments;
            _.each(this.rowLevels, function (row) {
                row.remove.apply(row, args);
            });
            this.rowLevels = [];
            return Backbone.View.prototype.remove.apply(this, arguments);
        }
    });

    Backgrid.Extension.ColSpanRow = Backgrid.Row.extend({
        render: function () {
            this.$el.empty();

            var fragment = document.createDocumentFragment();
            for (var i = 0; i < this.cells.length; i++) {
                if (!this.cells[i].notRender)
                    fragment.appendChild(this.cells[i].render().el);
            }

            this.el.appendChild(fragment);

            this.delegateEvents();

            return this;
        },
    });
}));
