Ext.ns("Ext.ux.grid.plugins");

Ext.ux.grid.plugins.AutoConfigureGrid = Ext.extend(Ext.util.Observable, {
    
    init : function(grid){

        // If no columns defined, setup an empty column model
        if(!grid.colModel) {
            grid.colModel = new Ext.grid.ColumnModel([]);
        }
        
        // register to the store's metachange event
        if(grid.store){
            grid.store.on("metachange", this.onMetaChange, grid);
        }
    },    

    onMetaChange : function(store, meta) {
        if(meta.columns) {
            
            var cols = meta.columns;
            for(var i=0, len = cols.length; i<len; i++) {
                var col = cols[i];
                var renderer = col.renderer;
                if(renderer && renderer.indexOf(".") > 0) {
                    col.renderer = eval(renderer);
                }
            }
            
            this.colModel.setConfig(cols);

            // Re-render grid
            if(this.rendered){
                this.view.refresh(true);
            }
        }
    }
});

Ext.apply(Ext.StoreMgr, {
	types : Ext.apply({},{
		jsonstore: Ext.data.JsonStore,
		simplestore:Ext.data.SimpleStore
	}),
  
	lookup: function(id) {
		if (typeof id == "object" && !id.load && id.xtype) {
			return new this.types[id.xtype](id);
		}
		return typeof id == "object" ? id : this.get(id);
	}
});
// Support for xtype based store
Ext.grid.GridPanel.prototype.initComponent = Ext.grid.GridPanel.prototype.initComponent.createInterceptor(function() {
		if (typeof this.store == "object" && !this.store.load && this.store.xtype) {
			this.destroyStore = true;
		}
		this.store = Ext.StoreMgr.lookup(this.store);
});
Ext.grid.GridPanel.prototype.onDestroy = Ext.grid.GridPanel.prototype.onDestroy.createInterceptor(function() {
if (this.destroyStore === true && this.store) {
		this.store.destroy();
	}
});

// Support for xtype based store
Ext.form.ComboBox.prototype.initComponent = Ext.form.ComboBox.prototype.initComponent.createInterceptor(function() {
	if (typeof this.store == "object" && !this.store.load && this.store.xtype) {
		this.destroyStore = true;
	}
	this.store = Ext.StoreMgr.lookup(this.store);
}
);
Ext.form.ComboBox.prototype.onDestroy = Ext.form.ComboBox.prototype.onDestroy.createInterceptor(function() {
if (this.destroyStore === true && this.store) {
		this.store.destroy();
	}
});