Ext.define("Ext.ux.mailChimp.SearchPanel", {
	extend: "Ext.form.Panel",
	alias: ["widget.mailchimpsearchpanel"],
	border: false,
	bodyPadding: 10,
	defaults: {
		xtype: "textfield",
		labelAlign: "left",
		labelWidth: 120,
		width: 500
	},
	layout: {
		type: "anchor"
	},
	initComponent: function() {
		var me = this;

		me.items = [{
			xtype: "fieldcontainer",
			itemId: "fieldcontainer",
			layout: "hbox",
			hideLabel: true,
			width: "100%",
			defaults: {
				xtype: "textfield",
				labelWidth: 50
			},
			items: [{
				xtype: "mailchimplistcombo",
				name: "listid",
				itemId: "listid",
				width: 500,
				listeners: {
					select: function() {
						me.setSearchEnable();
					}
				}
			},{
				xtype: "splitter",
				width: 15,
				style: "display:none;"
			},{
				xtype: "textfield",
				fieldLabel: ip2.i18n({ da: "Søg", en: "Search" }),
				name: "search",
				itemId: "search",
				width: 500,
				disabled: true,
				enableKeyEvents: true,
				listeners: {
					keypress: function(field, eventObject) {
						if (eventObject.getKey() == eventObject.ENTER) {
							if (field.getValue().length > 0) {
								me.submitSearch("search-members");
							}
							else {
								me.submitSearch();
							}
						}
					}
				},
				triggers: {
					clear: {
						weight: 1,
						cls: "x-form-clear-trigger",
						scope: "this",
						handler: "onTrigger1Click"
					},
					search: {
						weight: 1,
						cls: "x-form-search-trigger",
						scope: "this",
						handler: "onTrigger2Click"
					}
				},
				onTrigger1Click: function() {
					this.setValue("");

					me.submitSearch();
				},
				onTrigger2Click: function() {
					if (this.getValue().length > 0) {
						me.submitSearch("search-members");
					}
					else {
						me.submitSearch();
					}
				}
			},{
				xtype: "splitter",
				width: 15,
				style: "display:none;"
			},{
				xtype: "checkbox",
				hideLabel: true,
				boxLabel: ip2.i18n({ da: "Udmeldte", en: "Unsubscribed" }),
				name: "unsubscribed",
				itemId: "unsubscribed",
				disabled: true,
				listeners: {
					change: function(field) {
						me.submitSearch();
					}
				}
			}]
		}];

		me.callParent();
	},
	setSearchEnable: function() {
		var me = this;

		me.nextSibling("grid").setButtonsEnable();

		me.down("#unsubscribed").enable();
		me.down("#search").enable();

		me.submitSearch();
	},
	setSearchDisable: function() {
		var me = this;

		me.nextSibling("grid").setButtonsDisable();

		me.down("#unsubscribed").disable();
		me.down("#search").disable();
	},
	submitSearch: function(action) {
		var me = this;

		var params = {
			action: (action) ? action : "members",
			listid: me.down("#listid").getValue(),
			status: (me.down("#unsubscribed").getValue() == true) ? "unsubscribed" : "subscribed",
			search: me.down("#search").getValue()
		};

		me.nextSibling("grid").fireEvent("search", params);
	}
});
