Ext.define("Portfolio.ux.form.field.MarkdownField", {

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

	xtype: "portfolio-ux-form-field-markdownfield",

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

	requiredScripts: [
		"//cdn.jsdelivr.net/simplemde/latest/simplemde.min.css",
		"//cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"
	],

	alias: [
        "widget.ux-markdownfield",
        "widget.markdown",
	],

	alternateClassName: [
		"Ext.ux.markdown.Field"
    ],

	listeners: {
		render: {
			fn: function() {

				var i_self = this;

				var i_simpleMDE = new SimpleMDE({
					element: i_self.inputEl.el.dom,
					status: false,
					spellChecker: false
				});

				i_self.setSimpleMDE(i_simpleMDE);

				var i_codemirror = i_simpleMDE.codemirror;

				i_codemirror.on("change", function () {

					i_self.value = i_simpleMDE.value();

					if (i_self.value != i_self.lastValue) {

						i_self.lastValue = i_self.value;

						i_self.fireEvent("change", i_self, i_self.value, i_self.lastValue);
						i_self.onChange(i_self.value, i_self.lastValue);
					}
				});

				i_simpleMDE.gui.toolbar.style.border = "none";

				i_codemirror.getWrapperElement().style.border = "none";
				i_codemirror.getWrapperElement().style.borderTop = "1px solid #ddd";

				i_codemirror.getWrapperElement().style.setProperty("height", "auto");

				i_codemirror.getWrapperElement().style.setProperty("min-height", "80px");
				i_codemirror.getScrollerElement().style.setProperty("min-height", "80px");

				i_simpleMDE.value(i_self.getValue());

			}
		},
		resize: {
			fn: function() {

				var i_self = this;
				var i_inputEl = i_self.bodyEl;
				var i_simpleMDE = i_self.getSimpleMDE();

				var n_height = (i_inputEl.getHeight(true) - i_simpleMDE.gui.toolbar.clientHeight);

				var i_codemirror = i_simpleMDE.codemirror;
				var i_wrapper = i_codemirror.getWrapperElement();
				var i_scroller = i_codemirror.getScrollerElement();

				i_wrapper.style.maxHeight = i_scroller.style.maxHeight = n_height + "px";
				i_wrapper.style.paddingBottom = i_wrapper.style.paddingTop = "1px";
			}
		}
	},

	config: {
		simpleMDE: null
	},

	initComponent: function() {

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

	isDirty: function() {

		var i_self = this;
		var i_simpleMDE = i_self.getSimpleMDE();

		var s_originalValue = i_self.originalValue;
		var s_value = i_simpleMDE.value();

		return s_value != s_originalValue;
	},

	getValue: function() {

		var i_self = this;

		var s_value = i_self.value;

		var i_simpleMDE = i_self.getSimpleMDE();

		if (i_simpleMDE) {
			s_value = i_simpleMDE.value();
		}

		return s_value;
	},

	getSubmitValue: function() {

		var i_self = this;

		return i_self.getValue();
	}
});
