Ext.define('Ext.ux.folderorganizer.PropertyGrid', {
	extend: 'Ext.grid.property.Grid',
	sortableColumns: false,
	border: '0 0 0 1',
	initComponent: function() {
		var me = this;

		me.setProperties();

		me.dockedItems = [{
			xtype: 'toolbar',
			dock: 'bottom',
			items: [{
				xtype: 'tbfill' 
			},{
				xtype: 'button',
				text: me.getI18N('save'),
				handler: function(button) {
					var propertygrid = button.up('propertygrid');

					propertyGrid.wrapper.fireEvent('propertychange', propertygrid.record, propertygrid.action, propertygrid.parentRecord);

					if (propertygrid) propertygrid.hide();
				} 
			},{
				xtype: 'button',
				text: me.getI18N('cancel'),
				handler: function(button) {
					var propertygrid = button.up('propertygrid');
					if (propertygrid) propertygrid.hide();
				} 
			}]
		}];

		me.listeners = {
			propertychange: function(source, recordId, value) {
				if (me.record) {
					me.record.set(recordId, value);
				}
			}
		}
    
		me.callParent();
	},
	display: function(action, record, parentRecord) {
		var me = this;

		me.action = action;
		me.record = record;
		me.parentRecord = parentRecord || null;

		me.setPropertyValue(record);

		me.show();

		me.editingPlugin.startEditByPosition({ row: 0, column: 0 });    
	},
	setProperties: function() {
		var me = this;
    
		me.source = {},
		me.propertyNames = {},
		me.customEditors = {};

		if (me.fields) {
			// Use fields with title property
			for (var i = 0; i < me.fields.length; i++) {
				if (me.fields[i].title) {
					me.addPropertyField(me.fields[i]);
				}
			}

			// if source still empty, use all fields
			if (Ext.isEmpty(me.source)) {
				for (var i = 0; i < fields.length; i++) {
					me.addPropertyField(fields[i]);
				}
			}
		}
	},
	addPropertyField: function(field) {
		if (field.groupColumn) return;

		var me = this;

		if (field.type.type == 'int') {
			me.customEditors[field.name] = 'numberfield';
		}
		else {
			me.customEditors[field.name] = 'textfield';
		}

		me.source[field.name] = me.getDefaultValue(field.name);

		me.propertyNames[field.name] = (field.title) ? field.title : field.name;
	},
	setPropertyValue: function(record) {
		var me = this;

		me.suspendEvents();
    
		var properties = {};
		for (var key in me.source) {
			properties[key] = (record) ? record.data[key] : me.getDefaultValue(key);
		};

		me.setSource(properties);

		me.resumeEvents();
	},
	getDefaultValue: function(fieldName) {
		switch (this.customEditors[fieldName]) {
			case 'numberfield':
				return 0;
				break;
			default:
				return '';
				break;
		}
	},
	getI18N: function(key) {
		return ip2.folderorganizer.getTextValue(key);
	}
});
