/**
 * Toggle switch component used by Ext.field.Toggle
 */
Ext.define("Ext.ux.form.field.slider.Toggle", {

	extend: "Ext.slider.Single",

	xtype: "toggleslider",
	/**
	 * @inheritdoc
	 */
	value: 0,

	cls: Ext.baseCSSPrefix + "toggleslider",

	// TODO:  7.0 remove these two classes once legacy themes that rely on them are removed
	offCls: Ext.baseCSSPrefix + "toggle-off",
	onCls: Ext.baseCSSPrefix + "toggle-on",

	mixins: [
		"Ext.mixin.Mashup"
	],

	requiredScripts: [
		"/portfolio/app/ux/form/field/slider/toggle.css"
	],

	clickToChange: false,

	config: {
		sliderWidth: 40
	},

	listeners: {
		changecomplete: {
			fn: function(i_slider, value) {

				var i_self = this;
				i_self.setValue(value);
			}
		},
		click: {
			element: "el",
			fn: function(i_element) {

				var i_field = this.component;
				i_field.toggle();
			}
		},
		afterrender: {
			fn: function(i_field) {

				var i_innerEl = i_field.innerEl;
				if (i_innerEl) {
					var value = i_field.getValue();

					var b_on = value > 0;
					var s_onCls = i_field.onCls;
					var s_offCls = i_field.offCls;

					i_innerEl.addCls(b_on ? s_onCls : s_offCls);
					i_innerEl.removeCls(b_on ? s_offCls : s_onCls);
				}
			}
		}
	},

	initComponent: function() {

		var i_self = this;

		Ext.apply(i_self, {
			minValue: 0,
			maxValue: 1,
			increment: 1,
			value: i_self.value ? 1 : 0
		});

		var s_fieldLabel = i_self.fieldLabel;

		var n_width = i_self.getSliderWidth();

		if (s_fieldLabel && !i_self.width) {
			n_width = (i_self.labelWidth + i_self.getSliderWidth());
		}

		Ext.applyIf(i_self, {
			width: n_width
		});

		i_self.callParent();

		i_self.on({
			change: "onChange"
		});
	},

	setValue: function(newValue) {

		var i_self = this;
		i_self.callParent(arguments);
	},

	getValue: function() {

		var i_self = this;
		var value = i_self.callParent();

		return value > 0;
	},

	onChange: function(i_self, value) {

		var b_on = value > 0;
		var s_onCls = i_self.onCls;
		var s_offCls = i_self.offCls;

		var i_innerEl = i_self.innerEl;
		i_innerEl.addCls(b_on ? s_onCls : s_offCls);
		i_innerEl.removeCls(b_on ? s_offCls : s_onCls);
	},

	toggle: function() {

		var i_self = this;

		var value = i_self.getValue();
		i_self.setValue((value == 1) ? 0 : 1);

		return i_self;
	}
});
