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',
	validGrid: true,
	repeatText: this.repeatText || 'Double value in name',
	delimiter: ',',
	anchor: 0,
	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) {
		var css = '.ux-scroll-xy {overflow-y: hidden; overflow-x: hidden;}';
		Ext.util.CSS.createStyleSheet(css);
		this.addClass('ux-scroll-xy');
		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);
		this.fs = new Ext.form.FieldSet({
			title: this.legend,
			width: this.width,
			height: this.height,
			layout: 'fit',
			renderTo: this.el,
			style: "padding:0;",
			tbar: this.tbar
		});

		this.csm = new Ext.grid.CheckboxSelectionModel();
		this.grid = new Ext.grid.EditorGridPanel({
			border: false,
			stripeRows: true,
			width: this.width,
		    enableColumnHide: false,
		    enableHdMenu: false,
			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
			}]
		});
		this.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;
		this.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, 0);
	},
	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);
		}
		this.validate();
	},
	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;
	},
	gridValid : function() {
		var arr = new Array();
		var values = new Array();
		var valid = true;
		var arr = Ext.util.JSON.decode(this.getValue());
		var a;

		Ext.each(arr, function(item, index) {
			values[index] = item['name'];
			if (!item['name'] /* || !item['value'] */) {
					valid = false;
					this.markInvalid(this.blankText);
			}
		}, this);

		for (i = 0; i < values.length; i++) {
			a = 0;
			for (j = 0; j < values.length; j++) {
				if (values[i] && values[j]) {
					if (values[i] == values[j]) {
						if (a >= 1) {
							valid = false;
							this.markInvalid(this.repeatText);
						}
						a++;
					}
				}
			}
		}
		
		return valid;
	},
	setValue: function (value) {
		if (value == '') return false;
		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();
		this.validate();
	},
	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(this.validGrid)
		{
		if(!this.gridValid())
		{
			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();
		this.gridValid();
	},
	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);
