Ext.ux.grid.Favs = function(config){
    Ext.apply(this, config);
    Ext.ux.grid.Favs.superclass.constructor.call(this);
};

Ext.extend(Ext.ux.grid.Favs, Ext.util.Observable, {

    favsText: '',
    iconCls: 'icon-heart',
    iconAddCls: 'icon-heart-add',
    iconRemoveCls: 'icon-heart-delete',
    width: 16,
    menuDisabled: true,
    header: '',
    fixed: true,
    position: 'bottom',
    init: function(grid){
        this.grid = grid;
        
        // setup toolbar container if id was given
        if ('string' === typeof this.toolbarContainer) {
            this.toolbarContainer = Ext.getCmp(this.toolbarContainer);
        }
        
        // do our processing after grid render and reconfigure
        grid.onRender = grid.onRender.createSequence(this.onRender, this);
        //		grid.reconfigure = grid.reconfigure.createSequence(this.reconfigure, this);
		
		var config = {
			proxy: new Ext.data.MemoryProxy()
			,fields : grid.store.fields
		}
		this.store = grid.store.groupBy ? new Ext.data.GroupingStore(config) : new Ext.data.Store(config);

		this.originalIconCls = this.grid.iconCls;
		this.originalStore = grid.getStore();
		this.originalView = grid.view;
		this.colModel = grid.getColumnModel();
		
    },
    onRender: function(){

        var panel = this.toolbarContainer || this.grid;
        var tb = 'bottom' === this.position ? panel.bottomToolbar : panel.topToolbar;

        // handle position
        if ('right' === this.align) {
            tb.addFill();
        }
        else {
            if (0 < tb.items.getCount()) {
                tb.addSeparator();
            }
        }
        
		this.addFav = new Ext.Toolbar.Button({
            text: this.addText || ''
            ,iconCls: this.iconAddCls
			,tooltip : 'Click here to add checked items to your favourites.'
			,listeners : {
				'click' : {
					fn : function(btn, e) {
						var selModel = this.grid.getSelectionModel();
						if (selModel.getCount()==0) {
							Ext.Msg.show({
								title : 'Voyeur'
								,msg : 'Please select rows before adding items to your favourites.'
								,buttons : Ext.Msg.OK
								,animEl : btn.getEl()
								,icon : Ext.Msg. ERROR
							})
						}
						else {
							this.store.baseParams = {corpus: this.grid.getCorpus().get('id')};
							var sels = selModel.getSelections();
							this.store.add(sels);
							this.store.totalLength=this.store.getCount();
							if (this.exporter) {
								if (typeof this.exporter == 'string') {
									var vals = [];
									this.store.each(function(record) {
										vals.push(record.get(this.exporter))
									}, this)
									this.store.baseParams[this.exporter] = vals;
								}
								else {
									Ext.apply(this.store.baseParams, this.exporter(this.store.getRange()));
								}
							}
							this.toggleFav.toggle();
							this.toggleFav.getEl().frame("ff0000", 1, {duration : 1})
							this.grid.getView().scrollToTop();
						}
					}
					,scope : this
				}
			}
		})
		this.removeFav = new Ext.Toolbar.Button({
            text: this.removeText || ''
            ,iconCls: this.iconRemoveCls
			,hidden:true
			,tooltip : 'Click here to remove checked items from your favourites.'
			,listeners : {
				'click' : {
					fn : function(btn, e) {
						var selModel = this.grid.getSelectionModel();
						if (selModel.getCount()==0) {
							Ext.Msg.show({
								title : 'Voyeur'
								,msg : 'Please select rows before removing items from your favourites.'
								,buttons : Ext.Msg.OK
								,animEl : btn.getEl()
								,icon : Ext.Msg. ERROR
							})
						}
						selModel.each(function(record){
							this.store.remove(record);
						}, this)
						if (this.store.getCount()==0) {
							this.toggleFav.toggle();
							this.toggleFav.getEl().frame("ff0000", 1, {duration : 1})
						}
					}
					,scope : this
				}
			}
		})
		
		this.toggleFav = new Ext.Toolbar.Button({
            text: this.favsText || ''
            ,iconCls: this.iconCls
            ,enableToggle: true
			,tooltip : 'Click here to toggle the favourites view.'
            ,listeners: {
                'toggle': {
					fn: function(btn, pressed){
						
						if (pressed && this.store.getCount()==0) {
							btn.toggle();
							return Ext.Msg.show({
								title : 'Voyeur'
								,msg : 'This button allows you to toggle between current results and your favourite results. However, you do not yet have any favourite results. To create favourite results, select one or more rows and then click on the add button: <div class="icon-heart-add" style="height: 16px; width: 16px; ">'
								,buttons : Ext.Msg.OK
								,animEl : btn.getEl()
								,icon : Ext.Msg. ERROR
							})
						}
						
						var oldStore = pressed ? this.originalStore : this.store;
						var newStore = pressed ? this.store : this.originalStore;

						this.addFav.setVisible(!pressed);
						this.removeFav.setVisible(pressed);
						this.grid.reconfigure(newStore,this.grid.getColumnModel())
						
						// setting icon class seems to add a new one if an existing one is there – so remove it
						if (this.grid.header) {
							var headerIcon = this.grid.header.child('.x-panel-inline-icon')
							if (headerIcon) {headerIcon.remove();}
							if (pressed || this.originalIconCls) {
								this.grid.setIconClass(pressed ? 'icon-heart' : this.originalIconCls)						
							}							
						}
						
						var paging = null;
						var tb = this.grid.getBottomToolbar();
						if (tb && tb.isXType('paging')) {paging=tb;}
						if (!paging) {
							tb = this.grid.getTopToolbar();
							if (tb && tb.isXType('paging')) {paging=tb;}
						}
						if (paging) {
							paging.bindStore(newStore);
//							paging.unbind(oldStore);
//							paging.bind(newStore);
							paging.onLoad.call(paging,newStore,newStore.getRange(0,newStore.getCount()-1),newStore.lastOptions || {});
						}

					}
					,scope : this
                }
            }
		});
		
        // add menu button
        tb.add(this.toggleFav, this.addFav, this.removeFav);
        
        
        // setup renderer
        if (!this.renderer) {
            this.renderer = function(value, cell, record, row, col, store){
                cell.css += (cell.css ? ' ' : '') + 'icon-heart-add';
                return ''
            }.createDelegate(this);
        }
    }
})
