var Grid = Class.create();

Grid.prototype = {

    selectionChanged : function() {},

    initialize : function(pager, checkboxObserver) {
        this._changeHandlers = new Array();
        this._disposedHandlers = new Array();
        this._checkboxObserver = checkboxObserver;
        this._checkboxObserver.selectionChanged = function() {
            this._changeHandlers.each(function(handler){
                handler();
            });
        }.bind(this);
    },

    attachChangeHandler : function(handler) {
        this._changeHandlers.push(handler);
    },

    attachDisposedHandler : function(handler) {
        this._disposedHandlers.push(handler);
    },

/*
* Returns an array of {id, argument}
*/
    getSelectedItems : function() {
        return this._checkboxObserver.getCheckedItems();
    },

    dispose : function() {
        this._disposedHandlers.each(function(handler) {
            handler();
        });
    },

    update : function() {},

    highlightRow : function(cbId) {        
        var options = {
                    delay: 1,
                    duration:   4.0,
                    startcolor: "#F9B849"
                }
        new Effect.Parallel(
            [
                    new Effect.Highlight($(cbId).ancestors()[0], options)
                    ,new Effect.Highlight($(cbId).ancestors()[1], options)
            ],
            options
        );
    }
}

Grid.CheckBoxObserver = Class.create();

Grid.CheckBoxObserver.prototype = {

    selectionChanged : function() {},

    initialize : function() {
        this._items = new Hash();
        this._checkedItems = new Hash();
    },

    dispose : function() {
        delete this._checkedItems;
        delete this._items;
        this._allItemId = null;
        this.initialize();
    },

    getCheckedItems: function() {
        return this._checkedItems.values();
    },

    setAllItem : function(itemId) {
        this._allItemId = itemId;
    },

    addItem : function(item) {
        this._items[item.id] = item;
    },

    allItemClick : function() {
        this._checkedItems = new Hash();

        var check = $F(this._allItemId) == "on";
        this._items.values().each(function(item) {
            $(item.id).checked = check;
        }.bind(this));

        if (check) this._checkedItems = this._checkedItems.merge(this._items);

        this.selectionChanged();
    },

    itemClick : function(control, argument) {

        control = $(control);
        if (control.checked) {
            this._checkedItems[control.id] = this._items[control.id];
        }
        else {
            this._checkedItems.remove(control.id);
        }

        $(this._allItemId).checked = this._items.size() == this._checkedItems.size();

        this.selectionChanged();
    }
}