Ext.define("Ext.ux.form.field.IconPicker", {
	extend: "Ext.form.field.Text",
	alias: "widget.ux.form.field.iconpicker",

	editable: false,
	emptyText: ip2.i18n({
		da: "Url til ikon",
		en: "URL to icon"
	}),

	triggers: {
		search: {
			cls: Ext.baseCSSPrefix + "form-search-trigger",
			handler: "onSearchClick",
			weight: 1,
			scope: "this"
		}
	},

	requires: [
		"Ext.ux.file.util.Handler"
	],

	initComponent: function() {

		var i_self = this;

		// WE DO NOT WANT TO BE ABLE TO WRITE ANYTHING INTO THE FIELD
		//BUT ONLY USE THE PICKER...
		if (i_self.editable) {
			i_self.editable = false;
		}

		i_self.callParent();

		if (i_self.getValue()) {
			i_self.setIconCls(i_self.getCSS(i_self.getValue()));
		}

		return i_self;
	},

	onSearchClick: function() {

		var i_self = this;

		var i_window = Ext.widget("window", {
			title: ip2.i18n({
				da: "Server ikoner",
				en: "Server icons"
			}),
			layout: "fit",
			items: [],
			width: 865,
			height: 655,
			bodyPadding: 5
		});

		var i_dataview = Ext.widget("ux.icon.view.panel", {
			layout: "fit",
			actionFn: function (s_path) {
				i_self.setValue(s_path);
				i_self.setIconCls(i_self.getCSS(s_path));
				i_window.close();
			}
		});

		i_window.add(i_dataview);

		i_window.show();
	},

	getCSS: function(value) {
		var i_cmp = this;
		var s_name = i_cmp.getId() + "-css";
		var o_css = Ext.util.CSS.getRule("." + s_name);
		var a_value = value.split(".");
		var i_date = new Date();
		var n_time = i_date.getTime();
		var s_extensions = a_value.pop().toLowerCase();
		if (!o_css) {
			var s_url = value;
			if (Ext.ux.file.util.Handler.imageExtension.indexOf(s_extensions) == -1) {
				s_url = Ext.ux.file.util.Handler.getUrlByExtension(value);
			}
			var s_css = "." + s_name + "{" +
				"background-image: url(\"" + s_url + "\") !important;" +
				"background-size: 16px;" +
				"padding-left : 25px !important;" +
				"}";
			o_css = Ext.util.CSS.createStyleSheet(s_css, s_name);
		}
		else {
			if (Ext.ux.file.util.Handler.imageExtension.indexOf(s_extensions) == -1) {
				o_css.style.setProperty("background-image", "url(\"" + Ext.ux.file.util.Handler.getUrlByExtension(value) + "\")");
			}
			else {
				o_css.style.setProperty("background-image", "url(\"" + value + "?_dc=" + n_time + "\")");
			}
		}
		return s_name;
	}
});
