Ext.ns('Ext.ux.form');	
Ext.ux.form.OptionsGrid = Ext.extend(Ext.form.Field, {
	removeRowText: this.removeRowText || 'Remove',
	clearRowText: this.removeRowText || 'Clear',
	addRowText: this.addRowText || 'Add',
	addRowTooltip: this.addTooltip || 'Add a new row',
	addRowIconCls: this.addIconCls || 'addOption',
	removeRowTooltip: this.removeTooltip || 'Remove the selected item',
	clearRowTooltip: this.removeTooltip || 'Clear the all item',
	removeRowIconCls: this.removeIconCls || 'removeOption',  
	clearRowIconCls: this.clearIconCls || 'clearOption', 
	headerRowName: this.headerRowName || 'Name', 
	headerRowValue: this.headerRowValue || 'Value',
	delimiter: ',',
	minSelections: 0,
	enableJson: true,
	firstSeparator: '|',
	secondSeparator: ',',
	valueField: 1,
	blankText: Ext.form.TextField.prototype.blankText,
	maxSelections: Number.MAX_VALUE,
	minSelectionsText: this.minSelectionsText || 'Minimum {0} item(s) required',
	maxSelectionsText: this.maxSelectionsText || 'Maximum {0} item(s) allowed',
	confirmDelete: this.confirmDelete || 'Are you sure you want to carry out the operation?',
	warningDelete: this.warningDelete || 'at least a selection of information, delete!',
	defaultAutoCreate: {
		tag: "div"
	},
	initComponent: function (config) {
		Ext.apply(this, config);
		Ext.apply(this.initialConfig, config);
		Ext.ux.form.OptionsGrid.superclass.initComponent.apply(this, arguments);
		this.addEvents({
			'dblclick': true,
			'click': true,
			'change': true
		});
	},
	onRender: function (ct, position) {
		Ext.ux.form.OptionsGrid.superclass.onRender.call(this, ct, position);
		var fs = this.fs = new Ext.form.FieldSet({
		 title: this.legend,
		 width: this.width,
		 height: this.height - 10,
		 renderTo: this.el,
		 style: "padding:0;",
		 tbar: this.tbar
		 });
		//this.csm = new Ext.grid.RowSelectionModel({singleSelect: false });
		this.csm = new Ext.grid.CheckboxSelectionModel();
		this.grid = new Ext.grid.EditorGridPanel({
			border: false,
			height: this.height - 10,
			stripeRows: true,
			layout: 'fit',
	         viewConfig: {
               forceFit: true
           },
			loadMask: true,
			clicksToEdit: 1,			
			store: new Ext.data.SimpleStore({
				fields: [this.valueName, this.valueData]
			}),
			cm: new Ext.grid.ColumnModel({
				menuDisabled: true,
				columns: [
				{
					header: this.headerRowName,
					id: this.valueName,
					name: 'name',
					dataIndex: 'name',
					editor: new Ext.form.TextField({
						allowBlank: false
					})
				},
				{
					header: this.headerRowValue,
					id: this.valueData,
					name: 'value',
					dataIndex: 'value', 
					editor: new Ext.form.TextField({
						allowBlank: false
					})
				}]
			}),
			sm: this.csm,
			bbar: ['->', 
				{
					text: this.addRowText,
					tooltip: this.addRowTooltip,
					iconCls: this.addRowIconCls,					
					scope: this,
					handler: this.setRecord
				},
				'-',
				{
					text: this.removeRowText,
					tooltip: this.removeRowTooltip,
					iconCls: this.removeRowIconCls, 					
					scope: this,
					handler: this.removeRecord
				},
				'-',
				{
					text: this.clearRowText,
					tooltip: this.clearRowTooltip,
					iconCls: this.clearRowIconCls, 					
					scope: this,
					handler: this.clearRecords
				}
			]
		});
		fs.add(this.grid);
		this.hiddenName = this.name || Ext.id();
		var hiddenTag = {
			tag: "input",
			type: "hidden",
			value: "",
			name: this.hiddenName
		};
		this.grid.on('click', this.onViewClick, this);
		this.hiddenField = this.el.createChild(hiddenTag);
		this.hiddenField.dom.disabled = this.hiddenName != this.name;
		fs.doLayout();
	},
	afterRender: function () {
		Ext.ux.form.OptionsGrid.superclass.afterRender.call(this);
	},
	setRecord: function  () {
		var n = this.grid.getStore().getCount();
		var rec = this.grid.getStore().recordType;
		var p = new rec({id: n + 1});
		this.grid.stopEditing();
		this.grid.store.insert(n, p);
		this.grid.startEditing(n, 1);	
	},
	removeRecord: function (grid, rowIndex, e) {
		this.grid.stopEditing();
		var selections = this.grid.getSelectionModel();
		var records = selections.getSelections();
		if (typeof(records) == 'undefined' || parseInt(records.length) == 0) {
			Ext.MessageBox.alert('warning',this.warningDelete);
		} else {
			Ext.MessageBox.confirm('prompt box', this.confirmDelete, function (btn) {
				if (btn == 'yes') {
					if (records) {
						Ext.each(records, this.grid.store.remove, this.grid.store);
						this.hiddenField.dom.value = this.getValue();
					}
				}
			},this);	
		}
		
	},	
	getValue: function () {
		var data = new Array();
		if (this.grid.store.getRange().length != 0) {
			Ext.each(this.grid.store.getRange(), function (item, index) {
				data[index] = item.data;
			}, this);
			return Ext.util.JSON.encode(data);
		}
		return null;
	},
	setValue: function (value) {
		if(!this.enableJson){
		var records = new Array();
		var vv = new Array();
		value = value.split(this.firstSeparator);
		Ext.each(value, function (item, index) {
			vv = item.split(this.secondSeparator);
			records[index] = new Array();
			records[index]['name'] = vv[0]; 
			records[index]['value'] = vv[1];
		}, this);
		}
		else{
			var records = Ext.util.JSON.decode(value);
		}
		var rec = this.grid.getStore().recordType;
		Ext.each(records, function (item, index) {	
		this.grid.store.insert(index, new rec(item));
		}, this);
		this.validate();
	},
	clearRecords: function () {
		this.grid.store.removeAll();
		this.hiddenField.dom.value = this.getValue();
	},
	validateValue: function (value) {
		value = this.grid.store.getRange();
		if (value.length < 1) {
			if (this.allowBlank) {
				this.clearInvalid();
				return true;
			}
			else {
				this.markInvalid(this.blankText);
				return false;
			}
		}
		if (value.length < this.minSelections) {
			this.markInvalid(String.format(this.minSelectionsText, this.minSelections));
			return false;
		}
		if (value.length > this.maxSelections) {
			this.markInvalid(String.format(this.maxSelectionsText, this.maxSelections));
			return false;
		}
		return true;
	},
	onViewClick: function (vw, index, node, e) {
		this.fireEvent('change', this, this.getValue(), this.hiddenField.dom.value);
		this.hiddenField.dom.value = this.getValue();
		this.fireEvent('click', this, e);
		this.validate();
	},
	disable: function() {
		this.disabled = true;
		this.hiddenField.dom.disabled = true;
		this.grid.disable();
	},
	enable: function() {
		this.disabled = false;
		this.hiddenField.dom.disabled = false;
		this.grid.enable();
	}
});
Ext.reg('optionsgrid', Ext.ux.form.OptionsGrid);