Ext.define('Ext.ux.stackorganizer.Field', {

	extend: 'Ext.form.FieldContainer',

	alias: ['widget.stackfield'],

	mixins: {
		field: 'Ext.form.field.Field',
		componentController: 'Ext.ux.util.ComponentController'
	},

	refs: [
		{
			ref: 'stackPanel',
			selector: 'stackpanel'
		}
	],

	config: {
		token: 0,
		tokenKey: '__cid__',
		xpd: null,
		supportXpd: null,
		cid: null
	},

	initComponent: function () {

		var i_cmp = this;
		var o_stack;

		i_cmp.initComponentController();

		o_stack = Ext.Object.merge({
			xtype: 'stackpanel',
			border: false
		}, i_cmp.initialConfig);

		var i_stack = Ext.widget("stackpanel", o_stack);
		i_stack.on({
			change: {
				fn: function(i_stack) {
					i_cmp.checkChange();
				}
			},
			doAfterLayout: {
				fn: function(i_stack) {
					var i_widget = i_cmp.up("ip2widget");
					if (i_widget) {
						Ext.Component.updateLayout(i_widget);
					}
				},
				single: true
			}
		});

		Ext.apply(i_cmp, {
			layout: 'fit',
			margin: 0,
			padding: 0
		});

		i_cmp.callParent();

		i_cmp.initField();

		i_cmp.add(i_stack);

		i_cmp.addControls();

		return i_cmp;
	},

	initValue: function () {

		var i_cmp = this;
		var value = i_cmp.value;

		i_cmp.originalValue = value;

		return i_cmp;
	},

	getToken: function () {

		return this.getStackPanel().getToken();
	},

	addControls: function () {

		var i_cmp = this;
		var i_stack = i_cmp.getStackPanel();

		i_stack.on('needcid', function () {
			i_cmp.fireEvent('needcid', i_cmp, i_stack);
		});

		return i_cmp;
	},

	getValue: function () {

		var i_cmp = this;
		var i_stack = i_cmp.getStackPanel();
		var o_value = i_stack.getValue();
		var s_value = i_cmp.rawToValue(o_value);

		return s_value;
	},

	setValue: function (value) {

		var i_cmp = this;
		var i_stack = i_cmp.getStackPanel();

		i_cmp.value = value;

		i_stack.setValue(value);

		return i_cmp;
	},

	valueToRaw: function (s_value) {

		s_value = s_value || "";

		var i_cmp = this;
		var o_value = {};

		if (s_value.length) {
			o_value = Ext.decode(s_value);
		}

		return o_value;
	},

	disable: function() {

		var i_self = this;
		i_self.callParent(arguments);
		if (i_self.isDisabled()) {
			var i_stack = i_self.getStackPanel();
			i_stack.disable();
		}
	},

	enable: function() {

		var i_self = this;
		i_self.callParent(arguments);
		if (!i_self.isDisabled()) {
			var i_stack = i_self.getStackPanel();
			i_stack.enable();
		}
	},

	rawToValue: function (o_value) {

		var i_cmp = this;
		var s_value = '';

		if (Ext.Object.getSize(o_value)) {
			s_value = Ext.encode(o_value);
		}

		return s_value;
	},

	resetOriginalValue: function () {

		var i_cmp = this;
		var i_stack = i_cmp.getStackPanel();
		i_stack.resetOriginalValue();
		i_cmp.originalValue = i_cmp.value = i_cmp.getValue();
	},
	isDirty: function () {

		var i_cmp = this;
		var i_stack = i_cmp.getStackPanel();

		return i_stack.isDirty();
	}
});
