Ext.define("Ext.ux.folderorganizer.SearchField", {
	extend: "Ext.form.field.Text",
	hideLabel: true,
	width: 180,
	enableKeyEvents: true,
	isFormField: false,
	triggers: {
		clear: {
			cls: "x-form-clear-trigger",
			scope: "this",
			hidden: true,
			handler: "onTrigger1Click"
		},
		search: {
			cls: "x-form-search-trigger",
			scope: "this",
			handler: "onTrigger2Click"
		}
	},
	initComponent: function() {
		var me = this;

		me.emptyText = me.getI18N("searchText");

		me.listeners = me.listeners || {};
		Ext.apply(me.listeners, {
			keydown: function(fld, e) {
				if (e.getKey() == e.ENTER) {
					var value = me.getValue();
					if (value.length == 0) {
						me.onTrigger1Click();
					}
					else if (value.length < 3) {
						me.markInvalid(me.getI18N("min3characters"));
					}
					else {
						me.onTrigger2Click();
					}
				}
			}
		});

		me.callParent();
	},

	/* ----------------------------------------------------------------------------------------------------
	        Clear search field and refresh tree
	     ---------------------------------------------------------------------------------------------------- */
	onTrigger1Click: function() {
		var me = this;

		me.setValue("");
		me.wrapper.treegrid.searchValue = "";

		me.wrapper.treegrid.refresh(true);
		me.getTrigger("clear").hide();
	},

	/* ----------------------------------------------------------------------------------------------------
	        Submit Search
	     ---------------------------------------------------------------------------------------------------- */
	onTrigger2Click: function() {
		var me = this;
		var value = me.getValue().trim();

		if (value.length < 3) {
			me.markInvalid(me.getI18N("min3characters"));
		}
		else {
			me.getTrigger("clear").show();
			me.wrapper.treegrid.searchValue = value;
			me.wrapper.treegrid.search(value);
		}
	},

	/* ----------------------------------------------------------------------------------------------------
	        I18N translation
	     ---------------------------------------------------------------------------------------------------- */
	getI18N: function(key) {
		return ip2.folderorganizer.getTextValue(key);
	}
});
