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

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

	alias: [
		"widget.DDSEARCH"
	],

	minChars: 1,
	maxLength: 10,
	valueField: "KEY",
	displayField: "VALUE",
	forceSelection: false,
	typeAhead: false,
	pageSize: 25,
	matchFieldWidth: false,

	config: {
		sqlVoucher: ""
	},

	listeners: {
		keydown: {
			fn: function(i_field, i_event) {

				var n_key = i_event.getKey();
				
				if (i_field.isExpanded) {
					if (n_key == Ext.event.Event.DOWN || n_key == Ext.event.Event.UP) {
						i_event.stopEvent();
					}
				}
			}
		},
		select: {
			fn: function(i_field, i_record, n_number) {

				var a_fields = i_record.getFields();

				Ext.Array.each(a_fields, function(i_recordField) {

					var a_elements = document.getElementsByName(i_recordField.name);

					if (a_elements.length > 0) {

						var i_element = Ext.get(a_elements[0]);
						var i_component = i_element.component;

						var value = i_record.get(i_recordField.name);

						if (i_component) {
							i_component.setValue(value);
						}
						else {
							i_element.dom.value = value;
						}
					}
				});
			}
		}
	},

	initComponent: function() {

		var i_self = this;
		var i_store = i_self.createStore();

		i_self.store = i_store;
		i_self.tpl = i_self.createTemplate();

		i_self.callParent();
	},

	createTemplate: function() {

		var i_template = new Ext.XTemplate(
			"<tpl for=\".\">",
				"<li role=\"option\" class=\"x-boundlist-item\" style=\"text-overflow: ellipsis; white-space: nowrap; overflow:hidden;\">",
					"{VALUE}",
				"</li>",
			"</tpl>"
		);

		return i_template;
	},

	createStore: function() {

		var i_self = this;

		var i_store = Ext.create("Ext.data.Store", {
			fields: [
				{
					name: "KEY",
					type: "auto"
				},
				{
					name: "VALUE",
					type: "auto"
				}
			],
			pageSize: i_self.pageSize || 25,
			proxy: {
				url: "/icecap/DDSQL.aspx?runSql=runsql&sqlVoucher=" + i_self.getSqlVoucher(),
				type: "ajax",
				reader: {
					type: "json"
				}
			}
		});

		return i_store;
	}
});
