Ext.define("Ext.ux.form.field.CollectionPicker", {
	extend: "Ext.form.field.ComboBox",
	alias: "widget.collectionpickerfield",

	config: {
		xpd: "",
		displayField: "value",
		valueField: "key",
		values: null
	},

	initComponent: function() {

		var i_self = this;
		i_self.init();
		Ext.apply(i_self, {
			queryMode: "local",
			triggerAction: 'all',
			displayTpl: i_self.getDisplayTemplate(),
			tpl: i_self.getItemTemplate(),
			maxLength: 1000,
			store: Ext.create("Ext.data.Store", {
				fields: [
					{ name: i_self.getValueField(), type: "int" },
					{ name: i_self.getDisplayField(), type: "auto" }
				],
				idProperty: i_self.getValueField(),
				data: i_self.getValues()
			})
		});
		i_self.callParent();
		return i_self;
	},

	init: function() {

		var i_self = this;
		var s_xpd = i_self.getXpd();
		var o_xpd = ip2.resource.get(s_xpd);

		i_self.setXpd(o_xpd);

		var a_data = i_self.getValues();

		if (!a_data) {
			i_self.setValues(i_self.getRecords());
		}
	},

	getDisplayTemplate: function() {

		var i_self = this;
		var o_xpd = i_self.getXpd();
		var o_collections = o_xpd.collections;

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

					var s_value = s_key;

					if (s_key) {

						Ext.Object.each(o_collections, function(s_collection) {
							var o_collection = o_collections[s_collection];
							if (o_collection.id == s_key) {
								s_value = ip2.xpd.translate(o_xpd, o_collection.title);
								return false;
							}
						});
					}
					return s_value;
				}
			}
		);
		return i_template;
	},

	getItemTemplate: function() {

		var i_self = this;
		var o_xpd = i_self.getXpd();
		var o_collections = o_xpd.collections;

		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) {

					s_value = s_key;

					if (s_key) {

						var s_value = s_key;

						Ext.Object.each(o_collections, function(s_collection) {
							var o_collection = o_collections[s_collection];
							if (o_collection.id == s_key) {
								s_value = ip2.xpd.translate(o_xpd, o_collection.title);
								return false;
							}
						});
					}
					return s_value;
				}
			}
		);
		return i_template;
	},

	getRecords: function() {

		var i_self = this;
		var a_data = [];
		var o_xpd = i_self.getXpd();
		var o_collections = o_xpd.collections;

		Ext.Object.each(o_collections, function(s_collection) {
			if (s_collection !== "all") {
				var o_collection = o_collections[s_collection];
				var o_value = {
					key: o_collection.id,
					value: o_collection.title
				};
				a_data.push(o_value);
			}
		});

		o_xpd = i_self.getXpd();

		Ext.Array.each(a_data, function(o_data) {
			o_data.value = ip2.xpd.translate(o_xpd, o_data.value);
		});

		return a_data;
	}
});
