Ext.define("IceCap.ux.form.field.RadioGroup", {

	extend: "Ext.form.RadioGroup",

	alias: [
		"widget.RADIOGROUP"
	],

	config: {
		valueMap: []
	},

	layout: {
		type: "hbox",
		align: "stretch"
	},

	flex: 1,

	defaults: {
		margin: "0 20 0 0"
	},

	initComponent: function() {

		var i_self = this;

		i_self.items = i_self.createButtons();

		i_self.on({
			afterender: {
				fn: function(i_field) {

					var value = i_field.value;

					if (value) {

						i_field.setValue(value);
					}
				}
			},
			specialkey: {
				fn: function(i_field, e) {

					if (e.keyCode == 39 || e.keyCode == 37) {

						var n_index = 0;

						var b_found = false;

						var n_len = i_field.items.length;

						var a_items = i_field.getBoxes();

						Ext,Array.each(a_items, function(i_radio) {
							if (i_radio.innerWrap.id == e.target.id) {
								b_found = true;
							}
							if (!b_found) {
								n_index++;
							}
						});

						if (e.keyCode == 39) {
							n_index++;
						}
						else if (e.keyCode == 37) {
							n_index--;
						}
						if (b_found) {

							var i_radio;

							if (n_index == n_len) {
								i_radio = i_field.items.get(0);
							}
							else {
								if (n_index < 0) {
									i_radio = i_field.items.get(n_len - 1);
								}
								else {
									i_radio = i_field.items.get(n_index);
								}
							}

							i_radio.innerWrap.focus();

							i_field.setValue(i_radio.inputValue);
						}
					}
				}
			}
		});

		i_self.width = null;
		i_self.flex = 1;

		i_self.callParent(arguments);

		return i_self;
	},

	createButtons: function(a_values) {

		var i_self = this;
		var a_values = i_self.getValueMap();
		var a_return = [];

		Ext.Array.each(a_values, function(o_input) {

			var o_radio = {
				inputValue: o_input.key,
				boxLabel: o_input.value,
				name: i_self.name,
				flex: 1
			};
			a_return.push(o_radio);
		});

		return a_return;
	},

	getValue: function() {

		var i_self = this;
		var value = i_self.value;

		var a_items = i_self.getBoxes();

		Ext.Array.each(a_items, function(i_radio) {
			if (i_radio.inputValue == value) {
				value = i_radio.getGroupValue();
			}
		});

		return value;
	},

	setValue: function(value) {

		var i_self = this;

		var a_items = i_self.getBoxes();

		Ext.Array.each(a_items, function(i_radio) {
			if (i_radio.inputValue == value) {
				i_radio.setValue(true);
			}
			else {
				i_radio.setValue(false);
			}
		});

		i_self.value = value;
	},

	setFocus: function() {

		var i_self = this;
		var b_found = false;

		var a_items = i_self.getBoxes();

		Ext.Array.each(a_items, function(i_radio) {
			if (i_radio.checked) {
				b_found = true;
				i_radio.innerWrap.focus();
				i_self.setValue(i_radio.inputValue);
			}
		});

		if (!b_found) {
			var i_radio = i_self.items.get(0);
			i_radio.innerWrap.focus(true);
			i_self.setValue(i_radio.inputValue);
		}
	}
});
