Ext.define("Portfolio.dynapp.view.Toolbar", {

	extend: "Ext.toolbar.Toolbar",

	alias: "widget.dynapp.toolbar",

	dock: "top",

	config: {
		menu: null,
		grid: null
	},

	alternateClassName: [
		"Ext.dynapp.view.Toolbar"
	],

	requires: [
		"Ext.ux.themed.Button",
		"Ext.ux.ToolbarDroppable",
		"Ext.ux.grid.filter.Menu"
	],

	initComponent: function() {

		var i_self = this;

		i_self.plugins = i_self.createPlugins();
		i_self.callParent(arguments);

		i_self.add(i_self.createItems());

		i_self.on({
			afterrender: {
				fn: function(i_toolbar) {

					var i_grid = i_toolbar.getGrid();
					var i_header = i_grid.headerCt;

					var s_ddGroup = i_header.reorderer.dragZone.ddGroup;
					i_self.dd.addDDGroup(s_ddGroup);
				},
				buffer: 100
			}
		});

		return i_self;
	},

	createItems: function() {
		var i_self = this;
		var items = [
			{
				xtype: "button",
				itemId: "button-clear",
				text: ip2.i18n({
					da: "Ryd",
					en: "Clear"
				}),
				iconCls: "pf-navigate_cross",
				reorderable: false,
				handler: function(i_button) {
					i_self.clearFilters();
				}
			}
		];
		return items;
	},

	createMenu: function() {
		var i_self = this;
		var i_splitbutton = Ext.widget("filtermenu", {
			text: "Filter",
			reorderable: false,
			toolBar: i_self,
			itemId: "menuFilter"
		});
		i_self.menu = i_splitbutton;
		return i_splitbutton;
	},

	getFilters: function() {
		var i_self = this;
		return i_self.query("splitbutton[isFilter=true]");
	},

	clearFilters: function() {

		var i_self = this;
		var i_grid = i_self.getGrid();
		var i_store = i_grid.getStore();
		var i_proxy = i_store.getProxy();
		var o_extraParams = i_proxy.getExtraParams();
		var a_filters = i_self.getFilters();

		Ext.Array.each(a_filters, function(i_button) {
			if (i_button.overRuleable === null) {
				i_self.remove(i_button);
			}
			else {
				if (i_button.overRuleable) {
					i_self.remove(i_button);
				}
			}
		});

		a_filters = i_self.getFilters();

		delete o_extraParams.where;
		delete o_extraParams.sort;

		var o_sorters = i_store.getSorters();
		o_sorters.clear();
		var a_sorters = [];

		Ext.Array.each(a_filters, function(i_filter) {
			var o_sort = i_filter.getSortInfo();
			a_sorters.push(o_sort);
		});

		if (a_sorters.length > 0) {
			o_sorters.add(a_sorters);
		}
		else {
			if (i_store.clearAndLoad) {
				i_store.clearAndLoad({
					callback: function() {
						i_store.fireEvent("sort", i_store, o_sorters.getRange());
					}
				});
			}
			else {
				i_store.load({
					callback: function() {
						i_store.fireEvent("sort", i_store, o_sorters.getRange());
					}
				});
			}
		}

		//i_self.menu.reset();
	},

	clearStatus: function(i_menu) {

		var i_self = this;
		var a_items = i_menu.items.items;

		Ext.Array.each(a_items, function(i_item) {
			if (i_item.menu !== null) {
				i_item.setIconCls("");
				i_self.clearStatus(i_item.menu);
			}
			else {
				i_item.setIconCls("");
			}
		});
	},

	clearFiltersNoReload: function() {

		var i_self = this;
		var i_grid = i_self.getGrid();
		var i_store = i_grid.getStore();
		var i_proxy = i_store.getProxy();
		var o_extraParams = i_proxy.getExtraParams();
		var a_filters = i_self.getFilters();

		Ext.Array.each(a_filters, function(i_button) {
			if (i_button.overRuleable === null) {
				i_self.remove(i_button);
			}
			else {
				if (i_button.overRuleable) {
					i_self.remove(i_button);
				}
			}
		});

		delete o_extraParams.where;
		delete o_extraParams.sort;
	},

	createWhere: function() {

		var i_self = this;
		var i_grid = i_self.getGrid();
		var i_store = i_grid.getStore();
		var i_proxy = i_store.getProxy();
		var o_extraParams = i_proxy.getExtraParams();
		var a_filters = i_self.getFilters();
		var s_where = "";
		var s_sort = "";
		var n_whereAdded = 0;
		var n_sortAdded = 0;
		var o_sorters = i_store.getSorters();
		var a_sorters = [];

		Ext.Array.each(a_filters, function(i_filter, n_index) {
			var s_value = i_filter.getFilterValue();
			if (s_value) {
				if (n_whereAdded === 0) {
					s_where += s_value;
					n_whereAdded++;
				}
				else {
					s_where += " AND " + s_value;
				}
			}
			a_sorters.push(i_filter.getSortInfo());
		});

		a_sorters = a_sorters.filter(function(o_sort) {
			var b_found = false;
			Ext.Array.each(o_sorters.items, function(i_sorter) {
				if (i_sorter.getProperty() == o_sort.property) {
					if (i_sorter.getDirection() != o_sort.direction) {
						i_sorter.setDirection(o_sort.direction);
					}
					b_found = true;
				}
			});
			return !b_found;
		});
		o_extraParams.where = s_where;
		return a_sorters;
	},

	getWhere: function() {

		var i_self = this;
		var a_filters = i_self.getFilters();
		var s_where = "";
		var n_whereAdded = 0;

		Ext.Array.each(a_filters, function(i_filter, n_index) {
			var s_value = i_filter.getFilterValue();
			if (s_value) {
				if (n_whereAdded === 0) {
					s_where += s_value;
					n_whereAdded++;
				}
				else {
					s_where += " AND " + s_value;
				}
			}
		});

		return s_where;
	},

	getFilterConfig: function() {

		var i_self = this;
		var a_filters = i_self.getFilters();
		var a_configs = [];

		Ext.Array.each(a_filters, function(i_button) {
			var i_config = i_button.getConfig();
			var o_sortInfo = i_button.getSortInfo();
			var a_checkbox = [];
			var a_values = [];

			Ext.Arrayh(i_config.checkboxes, function(i_checkbox) {
				a_checkbox.push(i_checkbox.checked);
			});

			Ext.Array(i_config.fields, function(i_field) {
				if (i_field.fieldtype != "bt") {
					var value = i_field.getValue() || "";
					a_values.push(value);
				}
				else {
					var a_items = i_field.items.items;
					var i_first = a_items[0];
					var i_second = a_items[1];
					var o_value = {
						first: i_first.getValue() || "",
						second: i_second.getValue() || ""
					};
					a_values.push(o_value);
				}
			});

			var o_config = {
				dataIndex: i_button.dataIndex,
				dataType: i_button.dataType,
				dataDateType: i_button.dataDateType || "",
				isString: i_button.isString || false,
				multiSelect: i_button.multiSelect || false,
				sortDirection: o_sortInfo.direction,
				overRuleable: false,
				dmd: i_button.dmd || "",
				checkboxes: a_checkbox,
				fieldValues: a_values,
				notValue: i_button.getNot(),
				text: i_button.text,
				values: i_button.values || []
			};

			a_configs.push(o_config);
		});

		return a_configs;
	},

	applyFilters: function() {

		var i_self = this;
		var i_grid = i_self.grid;
		var i_store = i_grid.getStore();
		var i_proxy = i_store.getProxy();
		var o_extraParams = i_proxy.getExtraParams();
		var a_filters = i_self.getFilters();
		var s_where = "";
		var o_sorters = i_store.getSorters();
		var a_sorters = [];

		var a_where = [];

		Ext.Array.each(a_filters, function(i_filter) {
			var s_value = i_filter.getFilterValue();
			if (s_value) {
				a_where.push(s_value);
			}
			a_sorters.push(i_filter.getSortInfo());
		});

		s_where = a_where.join(" AND ");

		if (i_store.blockLoad) {
			i_store.blockLoad();
		}

		o_sorters.removeAll();

		o_sorters.add(a_sorters);

		o_extraParams.where = s_where;

		i_store.fireEvent("sort", i_store, o_sorters.getRange());

		if (i_store.unblockLoad) {
			i_store.unblockLoad(false);
		}

		if (Ext.isFunction(i_store.clearAndLoad)) {
			i_store.clearAndLoad();
		}
		else {
			i_store.load();
		}
	},

	removeFilter: function(i_filter) {

		var i_self = this;
		i_self.remove(i_filter);

		var i_grid = i_self.getGrid();
		var i_store = i_grid.getStore();
		var o_sorters = i_store.getSorters();
		var o_sort = i_filter.getSortInfo();
		var a_filters = i_self.getFilters();

		var a_removed = o_sorters.items.filter(function(i_sorter) {
			var b_found = false;
			if (i_sorter.getProperty() == o_sort.property) {
				b_found = true;
			}
			return b_found;
		});
		if (a_removed.length > 0 && a_filters.length > 0) {
			i_self.createWhere();
			o_sorters.remove(a_removed);
		}
		else {
			if (a_filters.length > 0) {
				i_self.applyFilters();
			}
			else {
				i_self.clearFilters();
			}
		}
	},

	sortChange: function(i_column) {

		var i_self = this;
		var a_filters = i_self.getFilters();
		var b_found = false;

		Ext.Array.each(a_filters, function(i_filter) {
			if (i_filter.dataIndex == i_column.dataIndex) {
				var o_sort = i_filter.getSortInfo();
				b_found = true;
				if (i_column.sortState !== null) {
					if (o_sort.direction != i_column.sortState) {
						i_filter.changeSort();
					}
				}
			}
		});

		if (!b_found) {
			var i_plugin = i_self.getPlugin("plugin-drop");
			i_plugin.createItem({
				header: i_column
			});
		}
	},

	createPlugins: function() {

		var i_self = this;

		var a_plugins = [
			i_self.createReorderplugin(),
			i_self.createDropPlugin()
		];

		return a_plugins;
	},

	createReorderplugin: function() {

		var i_self = this;

		var o_reorder = {
			pluginId: "plugin-reorderer",
			ptype: "boxreorder",
			removeOnDrop: function(element, i_button) {
				var i_dropped = Ext.getCmp(element.id);
				var b_remove = false;
				if (i_dropped && i_dropped.itemId == "button-clear") {
					b_remove = true;
					i_self.removeFilter(i_button);
				}
				return b_remove;
			},
			listeners: {
				Drop: {
					fn: function(i_self, i_toolbar, component, startIdx, idx) {
						if (startIdx != idx) {
							i_toolbar.applyFilters();
						}
					}
				}
			}
		};

		return o_reorder;
	},

	createDropPlugin: function() {

		var i_self = this;

		var o_dropplugin = {
			pluginId: "plugin-drop",
			ptype: "toolbardroppable",
			canDrop: function(ddSource, event, i_data) {
				if (i_data.header) {
					if (!i_data.header.hasOwnProperty("filterable")) {
						i_data.header.filterable = true;
					}
					if (i_data.header.filterable) {
						var o_header = i_data.header;
						var a_filters = i_self.getFilters();
						var b_result = true;
						Ext.Array.each(a_filters, function(o_filter) {
							if (o_filter.text == o_header.text) {
								b_result = false;
							}
						});
						return b_result;
					}
					else {
						return false;
					}
				}
				else {
					return false;
				}
			},
			createItem: function(i_data) {
				var i_grid = i_self.ownerCt;
				var i_store = i_grid.getStore();
				var i_header = i_data.header;
				var i_model = i_store.getModel();
				var a_fields = i_model.getFields();
				var s_type = "string";
				var a_values = [];

				Ext.Array.each(a_fields, function(i_field) {
					if (i_field.name == i_header.dataIndex) {
						s_type = i_field.datatype;
					}
				});

				var s_datetype = "date";
				var b_string = false;
				var b_mulitiSelect = false;
				var b_like = false;
				var o_dmd = {};

				if (s_type == "int"
					|| s_type == "dec"
					|| s_type == "decimal"
					|| s_type == "decimals"
					|| s_type == "smallInt"
					|| s_type == "float") {
					s_type = "number";
				}

				if (s_type == "char"
					|| s_type == "varchar") {
					s_type = "string";
				}

				if (s_type == "timestamp") {
					s_type = "date";
					s_datetype = "datetime";
				}

				if (i_header.properties && i_header.properties.plugin) {
					var o_plugin;
					eval("o_plugin = " + i_header.properties.plugin);
					if (o_plugin.values) {
						Ext.Array.each(o_plugin.values, function(o_value) {
							var o_record = {
								key: o_value.value,
								value: o_value.key
							};
							a_values.push(o_record);
						});
						s_type = "enum";
						b_mulitiSelect = o_plugin.multiselect || false;
					}
				}

				var o_config = {
					text: i_header.text,
					dataIndex: i_header.filterXpd != null ? i_header.supportProp : i_header.dataIndex,
					dataType: s_type,
					dataDateType: s_datetype,
					isString: b_string,
					multiSelect: b_mulitiSelect,
					sortDirection: i_header.sortState || "ASC",
					overRuleable: true,
					useLike: b_like,
					values: a_values,
					dmd: o_dmd,
					applyFn: function() {
						i_self.applyFilters();
					},
					removeFn: function(i_filter) {
						i_self.removeFilter(i_filter);
					}
				};

				var i_filter = Ext.ux.grid.filter.util.createFilter(o_config);

				i_self.add(i_filter);
				i_self.applyFilters();
			}
		};

		return o_dropplugin;
	}
});
