Ext.define("Ext.ux.form.field.ComboTable", {
	extend: "Ext.form.field.ComboBox",
	alias: "widget.combotable",

	schema: "",
	table: "",
	isLoaded: false,
	queryParam: "query",

	initComponent: function() {

		var i_self = this;
		Ext.apply(i_self, {
			queryMode: 'remote',
			displayField: "key",
			valueField: "value",
			triggerAction: 'all',
			minChars: 1,
			typeAhead: false,
			maxLength: 1000,
			displayTpl: i_self.getDisplayTemplate(),
			tpl: i_self.getItemTemplate()
		});
		var i_model;
		if (Ext.ClassManager.isCreated("model.Table")) {
			i_model = Ext.ClassManager.get("model.Table");
		}
		else {
			var i_model = Ext.define("model.Table", {
				extend: "Ext.data.Model",
				fields: [
					{ name: "key", type: "auto" },
					{ name: "value", type: "auto" }
				],
				idProperty: "key",
				proxy: {
					url: "ip2-services/ip2Services.aspx",
					type: "ajax",
					reader: {
						type: 'json',
						rootProperty: "rows",
						totalProperty: "totalRows"
					}
				}
			});
		}
		var i_store = Ext.create('Ext.data.Store', {
			model: i_model,
			remoteSort: true,
			autoLoad: false,
			autoSync: false,
			pageSize: 100
		});
		i_store.on({
			load: {
				fn: function(store, records) {
					if (!i_self.isLoaded) {
						i_self.isLoaded = true;
						if (i_self.value) {
							i_self.setValue(i_self.value);
						}
					}
				}
			},
			beforeload: {
				fn: function(store) {
					var i_proxy = store.getProxy();
					var o_extraParams = i_proxy.getExtraParams();

					Ext.apply(o_extraParams, {
						plugin: 'DB2',
						func: 'getDataModels',
						lib: i_self.schema,
						limit: -1
					});
				}
			}
		});
		i_self.store = i_store;
		i_self.callParent();
		i_self.on({
			afterrender: {
				fn: function(item) {
					var store = item.getStore();
					store.load();
				}
			}
		});

		return i_self;
	},

	getWhereTemplate: function(o_options) {

		var i_self = this;
		var o_values = {
			library: o_options.library,
			file: o_options.file
		};
		var i_tpl = Ext.create('Ext.XTemplate',
			'<tpl for=".">',
				i_self.where,
			'</tpl>'
		);
		var div = document.createElement("div");
		var i_compiled = i_tpl.compile();
		div = i_compiled.overwrite(div, o_values);
		var s_value = div.data;
		delete div;
		return s_value;
	},

	getDisplayTemplate: function() {

		var i_self = this;

		var i_template = Ext.create('Ext.XTemplate',
			'<tpl for=".">',
				'{[this.renderer(values.key)]}',
			'</tpl>',
			{
				renderer: function(s_key) {
					return ip2.i18n(s_key);
				}
			}
		);
		return i_template;
	},

	getItemTemplate: function() {

		var i_self = this;

		var i_template = Ext.create('Ext.XTemplate',
			'<tpl for=".">',
				'<li role="option" class="x-boundlist-item">',
					'{[this.renderer(values.key)]}',
				'</li>',
			'</tpl>',
			{
				renderer: function(s_key) {
					return ip2.i18n(s_key);
				}
			}
		);
		return i_template;
	}
});
