Ext.namespace("Ext.ux.grid");

Ext.ux.grid.GridSetter = Ext.extend(Ext.util.Observable,{
	
	constructor: function(config)
	{
		config = config || {};
		if(config.columns)
			this.columns = config.columns;
	},
	init: function(grid)
	{
		this.grid = grid;
		if(grid.rendered)
			this.onRender()
		else
			grid.on({
				scope:this,
				render:this.onRender,
				signle:true
			});
	},
	onRender:function()
	{
		var view = this.grid.view;
		var hmenu = view.hmenu;
		this.setMenu = hmenu.add({
			text:'Set',
			scope:this,
			itemId:'RMset',
			handler:function(){
				var col = view.cm.config[view.hdCtxIndex],
				st = this.grid.store,
				sm = this.grid.selModel,
				selIds = this.grid.getSelectedIds(),
				
				hasSelection = selIds.length > 0,
				selCount = selIds.length || this.grid.store.getTotalCount();
				var xyz = col.editor ? col.editor.cloneConfig() : {xtype:'textfield' };
				xyz.fieldLabel = 'Please enter value';
				xyz.ref = 'valueToSet';
				var w = new Ext.Window({
					autoDestroy:false,
					title:"Set '"+col.dataIndex+"' for "+selCount+' rows',
					items:[xyz]
					,layout:'form'
					,height:120,
					width:400
					,labelWidth:130,
					labelAlign:'right',
					padding:'15',
					modal:true
					,
					buttons:[{text:'Ok',
						handler: function(){
						var val = w.valueToSet.getValue();
						val = Ext.isDate(val) ? Ext.util.Format.date(val, w.gridSetter.grid.dateSQL) : val;
						if(hasSelection)
						{
							w.gridSetter.grid.RMconn.request({
								params:{
									action:'setSelection',
									ids: selIds.join(),
									setValue:val,
									setField:col.dataIndex
								},
								scope:w.gridSetter,
								success: function(){
									w.gridSetter.grid.store.reload();
								}
							})
						}
						else
						{
							var bp = w.gridSetter.grid.store.baseParams;
							var lo = w.gridSetter.grid.store.lastOptions;
							bp.addOn = 'setSelection';
							bp.setValue = val;
							bp.setField = col.dataIndex;
							w.gridSetter.grid.store.reload({callback: function(r,opt,s){
								delete bp.addOn;
								delete bp.setValue;
								delete bp.setField;
								try
								{
								delete lo.params.addOn;
								delete lo.params.setValue;
								delete lo.params.setField;
								}
								catch(e){}
							}});
						}
						
					
					
					w.close();
			} },{
				text:'Cancel',handler:function(){
				w.close();
			}
			}]
			,gridSetter: this,
			doClose: function()
			{
					//let's remove the child and hope it does not destroy it :)
					this.items.items[0] = null;
					 this.fireEvent('close', this);
				      //  this.destroy();
			}
			}).show();
		}
		});
		hmenu.on('beforeshow',this.onShow,this);
	},
	onShow: function(filterGrid)
	{
		if(this.columns)
		{
			var view = this.grid.view,
			col = view.cm.config[view.hdCtxIndex];
			if(this.columns.indexOf(col.dataIndex) == -1 )
				 view.hmenu.items.get('RMset').setDisabled(true);
			else
				this.setMenu.setDisabled(false);
		}
	}
});