Ext.define("Ext.ux.form.field.i18n.ComboMarkdownField", {

	extend: "Ext.form.field.Picker",

	alias: "widget.i18ncombomarkdownfield",

	mixins: {
		keyMapping: "Ext.ux.util.KeyMapping"
	},

	triggers: {
		"switch": {
			cls: "flatui i18n-field-active",
			weight: 1,
			scope: "this",
			tooltip: ip2.i18n({
				da: "Klik her for at ændre til normalt tekstboks",
				en: "Click here to change to a normal textarea"
			}),
			handler: function() {

				var i_self = this;
				i_self.fireEvent("i18ntriggercombo", i_self, false);
			}
		},
		picker: {
			cls: "x-form-arrow-trigger",
			weight: 2,
			handler: "onTriggerClick",
			scope: "this"
		}
	},

	matchFieldWidth: true,

	defaultLanguage: "",

	languages: null,

	first: true,

	i18nTriggerType: "disable",

	initComponent: function () {

		var i_cmp = this;
		var o_config = i_cmp.initialConfig;
		var s_defaultLanguage;

		i_cmp.defaultLanguage = i_cmp.defaultLanguage || wsh.i18n.getPrimary() || "en";

		i_cmp.callParent(arguments);

		i_cmp.initKeyMapping();

		i_cmp.on({
			afterrender: {
				fn: function(item) {

					var i_inputEl = item.inputEl;
					var o_size = i_inputEl.getSize();
					i_inputEl.setStyle({
						visibility: "hidden",
						display: "none"
					});

					var o_uiConfig = {
						renderTo: Ext.getBody(),
						border: false,
						hidden: true
					};

					if (i_cmp.actions) {
						o_uiConfig.actions = i_cmp.actions;
					}
					if (i_cmp.textareaConfig) {
						o_uiConfig.textareaConfig = i_cmp.textareaConfig;
					}

					var i_markdownfield = Ext.widget("markdown", o_uiConfig);
					i_cmp._markdown = i_markdownfield;

					i_markdownfield.getEl().insertAfter(i_inputEl);
					i_markdownfield.setSize(o_size);
					i_markdownfield.setVisible(true);

					var i_textarea = i_markdownfield.getTextarea();
					i_textarea.inputEl.setStyle({
						"padding-left": "28px"
					});
					i_textarea.on({
						change: {
							fn: function(i_textarea, value) {
								i_cmp.checkChange();
							}
						}
					});

					Ext.DomHelper.insertAfter(i_textarea.inputEl,
						"<div class=\"" + i_cmp.iconFieldCls + i_cmp.defaultLanguage +
						"\" style=\"position: absolute; top: 2px; left: 1px; width: 28px; height: 18px;\"></div>"
					);

					i_cmp._markdown = i_markdownfield;
					if (i_cmp.value) {
						i_markdownfield.setValue(i_cmp.value);
						i_textarea.resetOriginalValue();
					}
				}
			},
			resize: {
				fn: function(item, width, height) {
					if (item._markdown) {
						item._markdown.hide();
						var o_size = {};
						var n_triggerWidth = 0;
						var o_triggers = item.getTriggers();
						ip2.each(o_triggers, function(i_trigger) {
							n_triggerWidth = n_triggerWidth + i_trigger.el.getWidth();
						});
						o_size.width = width - n_triggerWidth;
						o_size.height = height;
						item._markdown.setSize(o_size);
						item._markdown.show();
					}
				}
			},
			expand: {
				fn: function() {
					var i_picker = this.getPicker();
					var i_fields = i_picker.getFields();
					var n_total = 0;

					i_fields.each(function (i_field) {
						n_total += i_cmp.getHeight();
						var n_height = i_cmp.getHeight();
						i_field.setHeight(n_height);
						i_field.fireEvent("resize", i_field, i_field.getWidth(), i_field.getHeight());
					});

					i_picker.setHeight(n_total);
				}
			},
			specialkey: {
				fn: function(i_self, event) {

					var s_key = event.getKey();

					var i_picker;
					var i_field;

					switch (s_key) {
						case event.TAB:
							if (i_self.isExpanded) {
								event.stopPropagation();
								event.preventDefault();

								i_picker = i_self.getPicker();
								i_field;

								i_field = i_picker.getField(event.shiftKey ? -1 : 0);

								if (i_field) {
									i_field.focus();
								}

								return false;
							}
							break;
						default: break;
					}
				}
			}
		});

		return i_cmp;
	},

	collapseIf: function(e) {
		var i_self = this;
		var i_picker = i_self.picker;
		if (!i_self.isDestroyed && !e.within(i_picker.el, false, true)) {
			i_self.collapse();
		}
	},

	initValue: function () {

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

		if (value == null) {
			value = "";
		}

		i_cmp.value = value;

		i_cmp.callParent(arguments);
	},

	createEmptyValue: function() {

		var i_cmp = this;
		var a_languages = this.languages;

		var o_value = {};

		Ext.Array.each(a_languages, function (s_language) {
			o_value[s_language] = i_cmp.processRawValue("");
		});

		return o_value;
	},

	createFields: function () {

		var i_cmp = this;

		var a_fields = [];

		ip2.each(i_cmp.languages, function (s_language, n_index) {

			if (s_language != i_cmp.defaultLanguage) {

				var i_field = Ext.widget("textfield", {
					itemId: s_language,
					isFormField: false,
					anchor: "100%",
					fieldStyle: "border-bottom: 0 none;" + i_cmp.iconFieldStyle,
					inputStyle: "",
					margin: 0,
					value: "",
					setValue: function(value) {

						var item = this;
						if (item._markdown) {
							item._markdown.setValue(value);
						}
						item.value = value;
					},
					getValue: function() {

						var i_field = this;
						var s_value = i_field.value || "";
						if (i_field._markdown) {
							s_value = i_field._markdown.getValue();
						}
						return s_value;
					},
					listeners: {
						afterrender: function(item) {
							var o_uiConfig = {
								renderTo: Ext.getBody(),
								border: false,
								hidden: true
							};

							if (i_cmp.actions) {
								o_uiConfig.actions = i_cmp.actions;
							}
							if (i_cmp.textareaConfig) {
								o_uiConfig.textareaConfig = i_cmp.textareaConfig;
							}

							var i_markdownfield = Ext.widget("markdown", o_uiConfig);
							item._markdown = i_markdownfield;
							var i_inputEl = item.inputEl;
							var size = i_inputEl.getSize();
							i_inputEl.setStyle({
								visibility: "hidden",
								display: "none"
							});

							i_markdownfield.getEl().insertAfter(i_inputEl);
							i_markdownfield.setSize(size);

							var i_textarea = i_markdownfield.getTextarea();
							i_textarea.on({
								change: {
									fn: function(i_textarea, value) {
										i_cmp.checkChange();
									}
								}
							});
							i_markdownfield.setVisible(true);
							i_textarea.inputEl.setStyle({
								"padding-left": "28px"
							});
							Ext.DomHelper.insertAfter(i_textarea.inputEl,
								"<div class=\"" + i_cmp.iconFieldCls + item.itemId +
								"\" style=\"position: absolute; top: 2px; left: 1px; width: 28px; height: 18px;\"></div>"
							);
						},
						resize: {
							fn: function(item, width, height) {
								if (item._markdown) {
									item._markdown.hide();
									var o_size = {};
									var n_triggerWidth = 0;
									var o_triggers = item.getTriggers();
									ip2.each(o_triggers, function(i_trigger) {
										n_triggerWidth = n_triggerWidth + i_trigger.el.getWidth();
									});
									o_size.width = width - n_triggerWidth;
									o_size.height = height;
									item._markdown.setSize(o_size);
									item._markdown.show();
								}
							}
						},
						specialkey: function (i_self, event) {

							var b_shift = event.shiftKey;
							var key = event.getKey();

							switch (key) {
								case event.UP:
								case event.DOWN:

									b_shift = key == event.UP;

								case event.TAB:

									event.stopPropagation();
									event.preventDefault();

									var nextFocus = b_shift ? i_self.previousSibling() : i_self.nextSibling();

									if (!nextFocus) {
										nextFocus = i_cmp;
									}

									nextFocus.focus();
									break;
								case event.ESC:

									i_cmp.collapse();
									i_cmp.focus();
									break;
								default: break;
							}
						}
					}
				});

				if (n_index == 1) {
					i_field.on("afterrender", function () {
						i_field.inputEl.setStyle("border-top", "0 none");
					}, i_field, { single: true });
				}

				a_fields.push(i_field);
			}
		});

		return a_fields;
	},

	createPicker: function () {

		var i_cmp = this;
		var i_picker;
		var a_fields;

		var a_fields = this.createFields();

		i_picker = i_cmp.picker = Ext.create("Ext.container.Container", {
			pickerField: i_cmp,
			ownerCt: i_cmp.ownerCt,
			renderTo: Ext.getBody(),
			floating: true,
			hidden: true,
			shadow: true,
			border: true,
			padding: 0,
			layout: "fit",
			styles: "border-top: 0 none",
			componentCls: i_cmp.iconClassName,
			getFields: function () {

				var i_container = this.down("#fieldscontainer");

				return i_container ? i_container.items : false;
			},
			getField: function (value) {

				var i_self = this;
				var i_container = i_self.down("#fieldscontainer");
				var i_field;

				if (Ext.typeOf(value) == "string") {
					i_field = i_container.down("#" + value);
				}
				else if (Ext.typeOf(value) == "number") {

					if (value < 0) {
						var n_len = i_container.items.getCount();
						value = n_len + value;
					}

					i_field = i_container.items.getAt(value);
				}

				return i_field;
			},
			fields: a_fields,
			items: [
				{
					xtype: "container",
					itemId: "fieldscontainer",
					layout: "anchor",
					autoScroll: false,
					styles: {
						owerflow: "hidden"
					},
					items: a_fields
				}
			]
		});

		return i_picker;
	},

	checkChange: function () {

		var i_cmp = this;

		if (!i_cmp.suspendCheckChange) {

			var newVal = i_cmp.getValue();
			var oldVal = i_cmp.lastValue;

			if (Ext.isObject(newVal)) {
				newVal = Ext.encode(newVal);
			}

			if (Ext.isObject(oldVal)) {
				oldVal = Ext.encode(oldVal);
			}

			if (!i_cmp.isEqual(newVal, oldVal) && !i_cmp.isDestroyed) {
				i_cmp.lastValue = newVal;
				i_cmp.fireEvent("change", i_cmp, newVal, oldVal);
				i_cmp.onChange(newVal, oldVal);
			}
		}
	},

	isDirty: function () {

		var i_cmp = this;
		var b_disabled = i_cmp.disabled;
		var value = i_cmp.getValue();
		var originalValue = i_cmp.originalValue;

		var s_value = Ext.encode(value);
		var s_original = originalValue ? Ext.encode(originalValue) : "";

		return !b_disabled && !i_cmp.isEqual(s_value, s_original);
	},

	processValue: function (o_value) {

		var i_cmp = this;

		if (typeof o_value == "string") {
			o_value = this.parseOrSingle(o_value);
		}

		Ext.Object.each(o_value, function (s_language, s_value) {
			o_value[s_language] = i_cmp.processRawValue(s_value);
		});

		return o_value;
	},
	valueToRaw: function (s_value) {

		var o_value = this.parseOrSingle(s_value);

		s_value = o_value[this.defaultLanguage];

		return s_value || "";
	},

	getSubmitValue: function () {

		return Ext.encode(this.getValue());
	},

	getValue: function () {

		var i_cmp = this;
		var s_raw;
		var o_value;

		s_raw = i_cmp.value || "";

		if (i_cmp._markdown) {
			s_raw = i_cmp._markdown.getValue();
		}

		o_value = i_cmp.getJsonValues(s_raw);

		return o_value;
	},
	setValue: function (s_value) {

		if (Ext.isObject(s_value)) {
			s_value = Ext.encode(s_value);
		}

		var i_cmp = this;
		var o_value = s_value;

		if (Ext.isString(s_value) && s_value != "") {
			o_value = this.parseOrSingle(s_value);
			if (!Ext.isObject(o_value)) {
				var o_temp = {};
				o_temp[i_cmp.defaultLanguage] = o_value;
				o_value = o_temp;
			}
		}

		if (o_value == "" || o_value == null) {
			o_value = this.createEmptyValue();
		}
		else {
			if (!Ext.isObject(o_value)) {
				o_value = i_cmp.processValue(s_value);
			}
		}

		i_cmp.setPickerValue(o_value);

		i_cmp.value = o_value[i_cmp.defaultLanguage];
		if (i_cmp._markdown) {
			i_cmp._markdown.setValue(i_cmp.value);
		}

		if (i_cmp.first) {
			i_cmp.first = false;
			i_cmp.originalValue = i_cmp.getValue();
		}

		if (Ext.isObject(i_cmp.originalValue)) {
			var s_emptyvalue = Ext.encode(i_cmp.createEmptyValue());
			var s_original = Ext.encode(i_cmp.originalValue);
			if (s_emptyvalue == s_original) {
				i_cmp.resetOriginalValue();
			}
		}

		return i_cmp;
	},

	getJsonValues: function (s_raw) {

		var i_cmp = this;
		var i_picker = i_cmp.getPicker();
		var i_fields = i_picker.getFields();
		var o_value = {};

		o_value[i_cmp.defaultLanguage] = s_raw;

		if (i_fields) {
			i_fields.each(function (i_field) {

				var s_value = i_field.getValue();

				o_value[i_field.itemId] = s_value;
			});
		}

		o_value = i_cmp.processValue(o_value);

		return o_value;
	},

	parseOrSingle: function (value) {

		var i_cmp = this;
		var o_value;

		if (Ext.isString(value)) {

			o_value = Ext.decode(value, true);

			if (!o_value) {
				o_value = i_cmp.createEmptyValue();
				o_value[i_cmp.defaultLanguage] = value;
			}
		}

		if (o_value == null) {
			o_value = value;
		}

		return o_value;
	},

	setPickerValue: function (o_value) {

		var i_cmp = this;
		var i_picker = i_cmp.getPicker();
		var i_fields = i_picker.getFields();

		if (i_fields) {
			i_fields.each(function (i_field) {

				var s_value = o_value[i_field.itemId];
				s_value = i_cmp.processRawValue(s_value);

				i_field.setValue(s_value);
			});
		}

		return i_cmp;
	}
});
