Ext.define("Portfolio.designer.ui.views.grid.view.Manager", {

	extend: "Ext.panel.Panel",

	layout: "fit",

	alias: "widget.designer.ui.views.grid.view.manager",

	config: {
		designer: null,
		entityManager: null,
		entity: null,
		grids: [],
		tabPanel: null,
		actionbar: null,
		required: false,
		newColumns: 0,
		newRelations: 0
	},

	requires: [
		"Portfolio.designer.ui.domainModelEntityGridLayout",
		"Portfolio.designer.ui.views.grid.controller.Manager"
	],

	controller: "designer.ui.views.grid.controller.manager",

	listeners: {
		deleteView: {
			fn: function(i_grid) {

				var i_self = this;

				var s_view = i_grid.getUiView();
				var a_grids = i_self.getGrids();
				var a_remove = [];

				Ext.Array.each(a_grids, function(i_grid, index) {
					if (i_grid.getUiView() == s_view) {
						a_remove.push(i_grid);
						return false;
					}
				});

				Ext.Array.each(a_remove, function(i_remove) {
					Ext.Array.remove(a_grids, i_remove);
				});

				i_self.setGrids(a_grids);
			}
		},
		newColumns: {
			fn: function(i_manager, n_columns) {

				var i_self = this;

				i_self.setNewColumns(n_columns);

				var a_grids = i_self.getGrids();

				Ext.Array.each(a_grids, function(i_grid) {
					i_grid.fireEvent("newColumns", i_grid);
				});
			}
		},
		newRelations: {
			fn: function(i_manager, n_relations) {

				var i_self = this;

				i_self.setNewRelations(n_relations);

				var a_grids = i_self.getGrids();

				Ext.Array.each(a_grids, function(i_grid) {
					i_grid.fireEvent("newRelations", i_grid);
				});
			}
		},
		updateColumn: {
			fn: function (s_old, s_new) {

				var i_self = this;
				var a_grids = i_self.getGrids();

				Ext.Array.each(a_grids, function (i_grid) {
					i_grid.fireEvent("updateColumn", s_old, s_new);
				});
			}
		},
		updateRelation: {
			fn: function(i_manager, i_record) {

				var i_self = this;

				var a_grids = i_self.getGrids();

				Ext.Array.each(a_grids, function(i_grid) {
					i_grid.fireEvent("updateRelation", i_grid, i_record);
				});
			}
		},
		removeColumn: {
			fn: function(s_column) {
				var i_self = this;

				var a_grids = i_self.getGrids();

				Ext.Array.each(a_grids, function (i_grid) {
					i_grid.fireEvent("removeColumn", s_column);
				});
			}
		},
		removeRelation: {
			fn: function(i_manager, s_entity) {

				var i_self = this;

				var a_grids = i_self.getGrids();

				Ext.Array.each(a_grids, function(i_grid) {
					i_grid.fireEvent("removeRelation", i_grid, s_entity);
				});
			}
		}
	},

	initComponent: function() {

		var i_self = this;
		i_self.callParent(arguments);
		i_self.add(i_self.createLayout());
		i_self.addDocked(i_self.createToolbar());

		return i_self;
	},

	createLayout: function() {

		var i_self = this;
		var o_entity = i_self.getEntity();

		if (!o_entity.hasOwnProperty("ui")) {

			Ext.apply(o_entity, {
				ui: {
					girds: {
						portfolio: {}
					}
				}
			});
		}

		if (!o_entity.ui.hasOwnProperty("grids")) {

			Ext.apply(o_entity.ui, {
				grids: {
					portfolio: {}
				}
			});
		}

		if (!o_entity.ui.grids.hasOwnProperty("portfolio")) {

			Ext.apply(o_entity.ui.grids, {
				portfolio: {}
			});
		}

		var a_items = [];

		var i_tabpanel = Ext.widget("tabpanel", {
			layout: "fit",
			plugins: [
				"tabreorderer"
			]
		});

		i_self.setTabPanel(i_tabpanel);

		Ext.Object.each(o_entity.ui.grids, function(s_key, o_values) {

			var i_panel = i_self.createView(s_key, o_values);
			a_items.push(i_panel);
		});

		i_tabpanel.add(a_items);

		i_tabpanel.setActiveTab(0);

		return i_tabpanel;
	},

	createView: function(s_key, o_config) {

		var i_self = this;
		var i_controller = i_self.getController();
		var i_designer = i_self.getDesigner();
		var i_entityManager = i_self.getEntityManager();
		var o_entity = i_self.getEntity();
		var a_grids = i_self.getGrids();

		o_config = o_config || {
			from: [],
			drop: "",
			columns: [],
			uiFeatures: {},
			features: {},
			extraParams: {},
			editMode: "tab",
			plugins: null,
			rowmodel: "rowmodel",
			mode: "MULTI",
			menu: {
				main: "",
				path: {},
				event: ""
			}
		};

		var o_menu = o_config.menu ||  {
			main: "",
			path: "",
			event: ""
		};

		var a_columns = Ext.clone(Ext.Array.from(o_config.columns));
		var a_extra = Ext.clone(Ext.Array.from(o_config.extraColumns));

		a_columns = a_columns.concat(a_extra);

		a_columns.sort(function(a, b) {
			var n_a = (Ext.isNumber(a.sequence) ? a.sequence : 0);
			var n_b = (Ext.isNumber(b.sequence) ? b.sequence : 0);

			return n_a - n_b;
		});

		var i_grid = Ext.widget("ip2DomainModelEntityGridLayout", {
			designer: i_designer,
			manager: i_self,
			entityManager: i_entityManager,
			entity: o_entity,
			uiView: s_key,
			uiColumns: a_columns,
			sort: o_config.sort || "",
			required: i_self.getRequired(),
			flex: 1,
			pageSize: o_config.pageSize || 100,
			purgePageCount: o_config.hasOwnProperty("purgePageCount") ? o_config.purgePageCount : 5,
			split: true
		});

		var i_panel = Ext.widget("form", {
			title: s_key,
			layout:  {
				type: "hbox",
				align: "stretch"
			},
			closable: s_key != "portfolio",
			itemId: "form-" + i_grid.getUiView(),
			listeners: {
				activate: {
					fn: function() {
						var i_store = i_grid.getStore();
						i_store.loadPage(1);
					},
					single: true,
					buffer: 10
				},
				beforeclose: {
					fn: function(i_panel) {

						ip2.messageBox({
							icon: Ext.MessageBox.INFO,
							title: ip2.i18n({
								da: "Advarrelse",
								en: "Warning"
							}),
							message: ip2.i18n({
								da: "<strong>Vil du slette dette view...<strong>",
								en: "<strong>Do you want to delete this view...<strong>"
							}),
							yesFn: function() {
								i_self.fireEvent("deleteView", i_grid);
								i_panel.destroy();
							},
							yesText: ip2.i18n({
								da: "Ok",
								en: "OK"
							}),
							cancelText: ip2.i18n({
								da: "Annuller",
								en: "Cancel"
							})
						});

						return false;
					},
					scope: this
				}
			}
		});

		var a_as = o_config.as || [];
		var a_from = o_config.from || [];
		var o_drop = o_config.drop || "";
		var o_extra = o_config.extraParams;
		var o_feature = Ext.Object.merge({}, o_entity.uiFeatures, o_config.features);

		var a_editData = [
			{
				value: "tab",
				key: "Tab"
			},
			{
				value: "window",
				key: ip2.i18n({
					da: "Vindue",
					en: "Window"
				})
			}
		];

		var a_selData = [
			{
				value: "rowmodel",
				key: ip2.i18n({
					da: "Række",
					en: "Row"
				})
			},
			{
				value: "spreadsheet",
				key: ip2.i18n({
					da: "Regneark",
					en: "Spreadsheet"
				})
			}
		];

		var a_selModeTypeData = [
			{
				value: "SINGLE",
				key: ip2.i18n({
					da: "Enkel",
					en: "Single"
				})
			},
			{
				value: "MULTI",
				key: ip2.i18n({
					da: "Flere",
					en: "Multi"
				})
			}
		];

		var a_plugins = [
			{
				value: "clipboard",
				key: ip2.i18n({
					da: "Udklipsholder",
					en: "Clipboard"
				})
			}
		];

		var a_features = [
			{
				value: "grouping",
				key: ip2.i18n({
					da: "Gruppering",
					en: "Grouping"
				})
			}
		];

		var a_gridPlugins = [
			{
				value: "entity-grid-summary",
				key: ip2.i18n({
					da: "Summering",
					en: "Summary"
				})
			}
		];

		var i_editStore = Ext.create("Ext.data.Store", {
			fields: [
				{
					type: "string",
					name: "value"
				},
				{
					type: "string",
					name: "key"
				}
			],
			proxy: {
				type: "memory"
			}
		});

		var i_selModelStore = Ext.create("Ext.data.Store", {
			fields: [
				{
					type: "string",
					name: "value"
				},
				{
					type: "string",
					name: "key"
				}
			]
		});

		var i_selModeTypeStore = Ext.create("Ext.data.Store", {
			fields: [
				{
					type: "string",
					name: "value"
				},
				{
					type: "string",
					name: "key"
				}
			]
		});

		var i_rowPluginStore = Ext.create("Ext.data.Store", {
			fields: [
				{
					type: "string",
					name: "value"
				},
				{
					type: "string",
					name: "key"
				}
			]
		});

		var i_festureStore = Ext.create("Ext.data.Store", {
			fields: [
				{
					type: "string",
					name: "value"
				},
				{
					type: "string",
					name: "key"
				}
			],
			data: a_features
		});

		var i_gridPluginStore = Ext.create("Ext.data.Store", {
			fields: [
				{
					type: "string",
					name: "value"
				},
				{
					type: "string",
					name: "key"
				}
			]
		});

		i_editStore.loadData(a_editData);
		i_selModelStore.loadData(a_selData);
		i_selModeTypeStore.loadData(a_selModeTypeData);
		i_rowPluginStore.loadData(a_plugins);
		i_gridPluginStore.loadData(a_gridPlugins);

		var i_editmode = Ext.widget("combobox", {
			name: "editMode",
			valueField: "value",
			displayField: "key",
			queryMode: "local",
			editable: false,
			forceSelection: true,
			fieldLabel: ip2.i18n({
				da: "Redigering",
				en: "Editing"
			}),
			store: i_editStore,
			value: o_config.editMode || "tab"
		});

		var i_gridPlugins = Ext.widget("combobox", {
			name: "gridplugins",
			valueField: "value",
			displayField: "key",
			queryMode: "local",
			editable: false,
			forceSelection: false,
			multiSelect: true,
			fieldLabel: ip2.i18n({
				da: "Plugin",
				en: "Plugin"
			}),
			store: i_gridPluginStore,
			value: o_config.gridplugins,
			triggers: {
				clear: {
					cls: Ext.baseCSSPrefix + "form-clear-trigger",
					handler: "clearValue",
					weigth: 1,
					scope: "this"
				},
				picker: {
					weight: 2,
					handler: "onTriggerClick",
					scope: "this"
				}
			},
			listeners: {
				afterrender: {
					fn: function (i_field) {
						var value = i_field.getValue();
						if (i_field.inputEl) {
	
							if (Ext.isEmpty(value)) {
								i_field.getTrigger("clear").hide();
							}
							else {
								i_field.getTrigger("clear").show();
							}
	
							if (i_field.readOnly) {
								i_field.setIconCls("");
								i_field.getTrigger("clear").hide();
							}
						}
					},
					single: true
				},
				change: {
					fn: function(i_field, value) {
						if (i_field.inputEl) {
							if (!value || (value && value.length === 0)) {
								i_field.allQuery = "";
								i_field.clearValue();
								i_field.getTrigger("clear").hide();
							}
							else {
								i_field.allQuery = i_field.lastQuery;
								if (!i_field.readOnly) {
									i_field.getTrigger("clear").show();
								}
							}
						}
					}
				},
				enable: {
					fn: function(i_field) {
	
						var s_value = i_field.getValue();
	
						i_field.getTrigger("clear")[s_value ? "show" : "hide"]();
					},
					buffer: 10
				},
				disable: {
					fn: function(i_field) {
						i_field.getTrigger("clear").hide();
					},
					buffer: 10
				},
				writeablechange: {
					fn: function(i_field, b_readOnly) {
	
						var s_value = i_field.getValue();
	
						if (s_value) {
							i_field.getTrigger("clear")[b_readOnly ? "hide" : "show"]();
						}
						else {
							i_field.getTrigger("clear").hide();
						}
					},
					buffer: 10
				}
			}
		});

		var i_features = Ext.widget("combobox", {
			name: "extfeatures",
			valueField: "value",
			displayField: "key",
			queryMode: "local",
			editable: false,
			forceSelection: false,
			multiSelect: true,
			fieldLabel: ip2.i18n({
				da: "Features",
				en: "Features"
			}),
			store: i_festureStore,
			value: o_config.extfeatures || null,
			triggers: {
				clear: {
					cls: Ext.baseCSSPrefix + "form-clear-trigger",
					handler: "clearValue",
					weigth: 1,
					scope: "this"
				},
				picker: {
					weight: 2,
					handler: "onTriggerClick",
					scope: "this"
				}
			},
			listeners: {
				afterrender: {
					fn: function (i_field) {
						var value = i_field.getValue();
						if (i_field.inputEl) {
	
							if (Ext.isEmpty(value)) {
								i_field.getTrigger("clear").hide();
							}
							else {
								i_field.getTrigger("clear").show();
							}
	
							if (i_field.readOnly) {
								i_field.setIconCls("");
								i_field.getTrigger("clear").hide();
							}
						}
					},
					single: true
				},
				change: {
					fn: function(i_field, value) {
						if (i_field.inputEl) {
							if (!value || (value && value.length === 0)) {
								i_field.allQuery = "";
								i_field.clearValue();
								i_field.getTrigger("clear").hide();
							}
							else {
								i_field.allQuery = i_field.lastQuery;
								if (!i_field.readOnly) {
									i_field.getTrigger("clear").show();
								}
							}
						}
					}
				},
				enable: {
					fn: function(i_field) {
	
						var s_value = i_field.getValue();
	
						i_field.getTrigger("clear")[s_value ? "show" : "hide"]();
					},
					buffer: 10
				},
				disable: {
					fn: function(i_field) {
						i_field.getTrigger("clear").hide();
					},
					buffer: 10
				},
				writeablechange: {
					fn: function(i_field, b_readOnly) {
	
						var s_value = i_field.getValue();
	
						if (s_value) {
							i_field.getTrigger("clear")[b_readOnly ? "hide" : "show"]();
						}
						else {
							i_field.getTrigger("clear").hide();
						}
					},
					buffer: 10
				}
			}
		});

		var i_rowPlugins = Ext.widget("combobox", {
			name: "plugins",
			valueField: "value",
			displayField: "key",
			queryMode: "local",
			editable: false,
			forceSelection: false,
			disabled: o_config.rowmodel !== "spreadsheet",
			multiSelect: true,
			fieldLabel: ip2.i18n({
				da: "Plugin",
				en: "Plugin"
			}),
			store: i_rowPluginStore,
			value: o_config.rowmodel == "spreadsheet" ? o_config.plugins : null,
			triggers: {
				clear: {
					cls: Ext.baseCSSPrefix + "form-clear-trigger",
					handler: "clearValue",
					weigth: 1,
					scope: "this"
				},
				picker: {
					weight: 2,
					handler: "onTriggerClick",
					scope: "this"
				}
			},
			listeners: {
				afterrender: {
					fn: function (i_field) {
						var value = i_field.getValue();
						if (i_field.inputEl) {
	
							if (Ext.isEmpty(value)) {
								i_field.getTrigger("clear").hide();
							}
							else {
								i_field.getTrigger("clear").show();
							}
	
							if (i_field.readOnly) {
								i_field.setIconCls("");
								i_field.getTrigger("clear").hide();
							}
						}
					},
					single: true
				},
				change: {
					fn: function(i_field, value) {
						if (i_field.inputEl) {
							if (!value || (value && value.length === 0)) {
								i_field.allQuery = "";
								i_field.clearValue();
								i_field.getTrigger("clear").hide();
							}
							else {
								i_field.allQuery = i_field.lastQuery;
								if (!i_field.readOnly) {
									i_field.getTrigger("clear").show();
								}
							}
						}
					}
				},
				enable: {
					fn: function(i_field) {
	
						var s_value = i_field.getValue();
	
						i_field.getTrigger("clear")[s_value ? "show" : "hide"]();
					},
					buffer: 10
				},
				disable: {
					fn: function(i_field) {
						i_field.getTrigger("clear").hide();
					},
					buffer: 10
				},
				writeablechange: {
					fn: function(i_field, b_readOnly) {
	
						var s_value = i_field.getValue();
	
						if (s_value) {
							i_field.getTrigger("clear")[b_readOnly ? "hide" : "show"]();
						}
						else {
							i_field.getTrigger("clear").hide();
						}
					},
					buffer: 10
				}
			}
		});

		var i_rowmodel = Ext.widget("combobox", {
			name: "rowmodel",
			valueField: "value",
			displayField: "key",
			queryMode: "local",
			editable: false,
			forceSelection: true,
			fieldLabel: ip2.i18n({
				da: "Type",
				en: "Type"
			}),
			store: i_selModelStore,
			value: o_config.rowmodel || "rowmodel",
			listeners: {
				change: {
					fn: function(i_field, value) {

						i_rowPlugins[value === "rowmodel" ? "disable" : "enable" ]();
						i_rowPlugins.setValue(null);
					}
				}
			}
		});

		var i_rowmode = Ext.widget("combobox", {
			name: "mode",
			valueField: "value",
			displayField: "key",
			queryMode: "local",
			editable: false,
			forceSelection: true,
			fieldLabel: ip2.i18n({
				da: "Selektion",
				en: "Selection"
			}),
			store: i_selModeTypeStore,
			value: o_config.mode || "MULTI"
		});

		var i_main = Ext.widget("textfield", {
			name: "main",
			fieldLabel: "Main",
			regex: new RegExp("^\\w+(?:\\.\\w+)*$"),
			value: o_menu.main
		});

		var i_path = Ext.widget("acetextarea", {
			name: "path",
			mode: "json",
			asJson: true,
			fieldLabel: ip2.i18n({
				da: "Sti",
				en: "Path"
			}),
			value: o_menu.path
		});

		var i_event = Ext.widget("textfield", {
			name: "event",
			fieldLabel: ip2.i18n({
				da: "Event",
				en: "Event"
			}),
			emptyText: "beforemenu",
			value: o_menu.event
		});

		var i_west = Ext.widget("panel", {
			minWidth: 400,
			width: 400,
			bodyPadding: 10,
			split: true,
			autoScroll: true,
			layout: "anchor",
			defaults: {
				anchor: "100%"
			},
			items: [
				{
					xtype: "fieldset",
					title: "Standard",
					collapsible: true,
					collapsed: true,
					layout: "anchor",
					defaults: {
						labelWidth: 80,
						anchor: "100%"
					},
					items: [
						{
							xtype: "i18ntextfield",
							name: "title",
							fieldLabel: ip2.i18n({
								da: "Title",
								en: "Title"
							}),
							value: o_config.hasOwnProperty("title") ? o_config.title : ""
						},
						{
							xtype: "checkbox",
							name: "sortable",
							fieldLabel: ip2.i18n({
								da: "Sorterbar",
								en: "Sortable"
							}),
							value: o_config.hasOwnProperty("sortable") ? o_config.sortable : true,
							handler: function (i_field, b_checked) {

								var i_filterBar = i_grid.getFilterBar();
								i_filterBar.clearFilters();

								var a_columns = i_grid.getColumnManager().getColumns();

								Ext.Array.each(a_columns, function (i_column) {
									i_column.sortable = b_checked;
								});
							}
						},
						{
							xtype: "checkbox",
							name: "remoteSort",
							fieldLabel: ip2.i18n({
								da: "Server sortering",
								en: "Server sorting"
							}),
							value: o_config.hasOwnProperty("remoteSort") ? o_config.remoteSort : true
						},
						{
							xtype: "checkbox",
							name: "autoParseContent",
							fieldLabel: ip2.i18n({
								da: "Auto parse indhold",
								en: "Auto parse content"
							}),
							value: o_config.hasOwnProperty("autoParseContent") ? o_config.autoParseContent : false
						},
						{
							xtype: "checkbox",
							name: "listable",
							fieldLabel: ip2.i18n({
								da: "Vis i oversigt",
								en: "Show i overview"
							}),
							value: o_config.hasOwnProperty("listable") ? o_config.listable : false
						},
						{
							xtype: "checkbox",
							name: "editable",
							fieldLabel: ip2.i18n({
								da: "Inline redigering",
								en: "Inline editing"
							}),
							value: o_config.hasOwnProperty("editable") ? o_config.editable : false
						},
						{
							xtype: "textfield",
							fieldLabel: "System Object Name",
							name: "sysname",
							value: o_config.sysname || ""
						},
						i_editmode,
						{
							xtype: "numberfield",
							name: "pageSize",
							fieldLabel: "Page size",
							minValue: 100,
							value: o_config.hasOwnProperty("pageSize") ? o_config.pageSize : 100,
							listeners: {
								change: {
									fn: function (i_field, n_value) {
										i_grid.setPageSize(n_value);
									},
									buffer: 500
								}
							}
						},
						{
							xtype: "numberfield",
							name: "purgePageCount",
							fieldLabel: "Purge Page Count",
							minValue: 0,
							value: o_config.hasOwnProperty("purgePageCount") ? o_config.purgePageCount : 5,
							listeners: {
								change: {
									fn: function(i_field, n_value) {
										i_grid.setPurgePageCount(n_value);
									},
									buffer: 500
								}
							}
						},
						i_gridPlugins,
						i_features
					]
				},
				{
					xtype: "fieldset",
					title: ip2.i18n({
						da: "Række",
						en: "Row"
					}),
					collapsible: true,
					collapsed: true,
					layout: "anchor",
					defaults: {
						labelWidth: 80,
						anchor: "100%"
					},
					items: [
						i_rowmodel,
						i_rowPlugins,
						i_rowmode
					]
				},
				{
					xtype: "fieldset",
					title: ip2.i18n({
						da: "Menu",
						en: "Menu"
					}),
					collapsible: true,
					collapsed: true,
					layout: "anchor",
					defaults: {
						labelWidth: 80,
						anchor: "100%"
					},
					items: [
						i_main,
						i_path,
						i_event
					]
				}
			]
		});

		var i_south = Ext.widget("panel", {
			bodyPadding: 10,
			split: true,
			flex: 1,
			layout: {
				type: "hbox",
				align: "stretch"
			},
			defaults: {
				margin: "0 5 0 0"
			},
			items: [
				{
					xtype: "container",
					layout: {
						type: "vbox",
						align: "stretch"
					},
					flex: 2,
					items: [
						{
							xtype: "panel",
							title: "SQL",
							layout: "fit",
							flex: 1,
							items: [
								{
									xtype: "acetextarea",
									name: "as",
									value: a_as,
									mode: "sql",
									asArray: true,
									readOnly: i_self.getRequired(),
									listeners: {
										keydown: {
											element: "el",
											fn: function(i_event) {

												if (i_event.ctrlKey === true) {

													if (i_event.getKey() == Ext.event.Event.R) {

														i_event.stopEvent();

														var i_target = Ext.get(i_event.currentTarget);
														var i_field = i_target.component;

														var a_values = i_field.getValue();

														a_values = Ext.Array.from(a_values);

														var a_current = i_grid.getColumnManager().getColumns();

														i_controller.onSqlPreview(a_values.join(" "), function(o_result) {

															i_controller.onShowPreview(o_result, a_current, function(a_columns, n_state) {
																i_controller.onTransferColumns(a_columns, i_grid, n_state);
															});
														});
													}
												}
											}
										}
									}
								}
							],
							listeners: {
								afterrender: {
									fn: function(i_panel) {

										var i_header = i_panel.getHeader();

										var a_items = [];

										var i_runButton = Ext.widget({
											xtype: "button",
											iconCls: "pf-media_fast_forward",
											tooltip: "<strong>Preview sql result<br>(ctrl + r)</strong>",
											handler: function(i_button) {

												var i_field = i_panel.down("acetextarea");

												var a_values = i_field.getValue();

												a_values = Ext.Array.from(a_values);

												var a_current = i_grid.getColumnManager().getColumns();

												i_controller.onSqlPreview(a_values.join(" "), function(o_result) {

													i_controller.onShowPreview(o_result, a_current, function(a_columns, n_state) {
														i_controller.onTransferColumns(a_columns, i_grid, n_state);
													});
												});
											},
											listeners: {
												afterrender: {
													fn: function(i_button) {

														var i_style = window.getComputedStyle(i_header.el.dom, null);

														var s_color = i_style.getPropertyValue("background-color");

														i_button.el.dom.style.setProperty("background-color", s_color, "important");
														i_button.el.dom.style.setProperty("border", "none", "important");
													}
												}
											}
										});

										a_items.push(i_runButton);

										i_header.items.insert(1, a_items);
									}
								}
							}
						},
						{
							xtype: "fieldset",
							title: "Sql from",
							layout: "fit",
							flex: 1,
							collapsible: true,
							collapsed: true,
							hidden: true,
							items: [
								{
									xtype: "acetextarea",
									name: "from",
									value: a_from,
									mode: "sql",
									asArray: true,
									readOnly: i_self.getRequired()
								}
							]
						}
					]
				},
				{
					xtype: "container",
					layout: "fit",
					flex: 1,
					hidden: true,
					items: [
						{
							xtype: "fieldset",
							title: "Drop Config",
							layout: "fit",
							region: "center",
							flex: 1,
							collapsible: true,
							items: [
								{
									xtype: "acetextarea",
									name: "drop",
									value: o_drop,
									mode: "json",
									asJson: true,
									useWorker: false,
									readOnly: i_self.getRequired()
								}
							]
						}
					]
				},
				{
					xtype: "container",
					layout: {
						type: "accordion"
					},
					flex: 1,
					margin: "0 0 0 0",
					items: [
						{
							xtype: "panel",
							title: ip2.i18n({
								da: "Features",
								en: "Features"
							}),
							layout: "fit",
							flex: 1,
							items: [
								{
									xtype: "acetextarea",
									name: "features",
									value: o_feature,
									mode: "json",
									asJson: true,
									useWorker: false,
									readOnly: i_self.getRequired()
								}
							]
						},
						{
							xtype: "panel",
							title: ip2.i18n({
								da: "Ekstra parameter",
								en: "Extra parameter"
							}),
							layout: "fit",
							flex: 1,
							items: [
								{
									xtype: "acetextarea",
									name: "extraParams",
									value: o_extra,
									mode: "json",
									asJson: true,
									useWorker: false,
									readOnly: i_self.getRequired()
								}
							]
						}
					]
				}
			]
		});

		i_panel.add(i_west);

		i_panel.add({
			xtype: "container",
			bodyPadding: 10,
			flex: 1,
			split: true,
			layout: {
				type: "vbox",
				align: "stretch"
			},
			items: [
				i_grid,
				i_south
			]
		});

		a_grids.push(i_grid);

		return i_panel;
	},

	createToolbar: function() {

		var i_self = this;
		var i_tabpanel = i_self.getTabPanel();

		var i_toolbar = Ext.widget("toolbar", {
			dock: "top",
			items: [
				{
					xtype: "button",
					text: ip2.i18n({
						da: "Tilføj view",
						en: "Add view"
					}),
					iconCls: "pf-add",
					disabled: i_self.getRequired(),
					handler: function(i_button) {

						var i_window = Ext.widget("window", {

							width: 400,
							title: ip2.i18n({
								da: "Nyt view",
								en: "New view"
							}),
							layout: "fit",
							modal: true,
							items: [
								{
									xtype: "form",
									layout: "anchor",
									bodyPadding: 10,
									defaults: {
										anchor: "100%"
									},
									items: [
										{
											xtype: "textfield",
											fieldLabel: "Name",
											name: "view",
											fieldStyle: {
												textTransform: "lowercase"
											},
											maskRe: /[a-zA-Z_-]/,
											listeners: {
												afterrender: {
													fn: function(i_field) {
														i_field.focus();
													},
													buffer: 10
												},
												specialKey: {
													fn: function(i_field, i_event) {

														if (i_event.getKey() == i_event.ENTER) {

															var i_window = i_field.up("window");
															var i_formpanel = i_window.down("form");
															var i_form = i_formpanel.getForm();
															var o_values = i_form.getValues();

															i_window.close();

															var s_value = o_values.view.toLowerCase();

															var i_panel = i_self.createView(s_value);
															var i_active = i_tabpanel.add(i_panel);
															i_tabpanel.setActiveTab(i_active);
														}
													}
												}
											}
										}
									]

								}
							],
							buttons: [
								{
									xtype: "button",
									text: "Ok",
									handler: function(i_button) {

										var i_window = i_button.up("window");
										var i_formpanel = i_window.down("form");
										var i_form = i_formpanel.getForm();
										var o_values = i_form.getValues();

										i_window.close();

										var s_value = o_values.view.toLowerCase();

										var i_panel = i_self.createView(s_value);
										var i_active = i_tabpanel.add(i_panel);
										i_tabpanel.setActiveTab(i_active);
									}
								},
								{
									xtype: "button",
									text: "Cancel",
									handler: function(i_button) {

										var i_window = i_button.up("window");
										i_window.close();
									}
								}
							]
						});

						i_window.show();
					}
				}
			]
		});

		i_self.setActionbar(i_toolbar);
		return i_toolbar;
	},

	doSave: function(o_entity) {

		var i_self = this;
		var a_grids = i_self.getGrids();

		if (!o_entity.ui) {
			o_entity.ui = {};
		}

		var o_old = o_entity.ui.grids;

		o_entity.ui.grids = {};

		Ext.Array.each(a_grids, function(i_grid) {

			var a_return = [];
			var a_extra = [];

			var i_store = i_grid.getStore();

			var a_columns = i_grid.getColumnManager().getColumns() || [];

			if (a_columns.length === 0) {
				a_columns = i_grid.columns;
			}

			var n_index = 0;

			Ext.Array.each(a_columns, function(i_column) {

				if (!i_column.hidden) {

					var o_column = {};

					var a_keys = Ext.Object.getKeys(i_column.config);

					Ext.Array.each(a_keys, function(s_key) {
						var value = i_column.config[s_key];
						if (!Ext.grid.Column.prototype.hasOwnProperty(s_key)) {
							o_column[s_key] = value;
						}
					});

					if (i_column.from) {
						if (!Ext.String.startsWith(i_column.from, "(") && !Ext.String.endsWith(i_column.from, ")")) {
							o_column.as = i_column.from + "_" + i_column.name;
						}
					}

					var o_columnConfig = Ext.apply({}, o_column.columnConfig);

					o_column = Ext.applyIf(o_column, o_columnConfig);

					if (i_column.width) {
						o_column.width = i_column.width;
						delete o_column.flex;
					}
					else {
						o_column.flex = i_column.flex;
						delete o_column.width;
					}

					Ext.Object.each(o_column, function(s_key, value) {

						if (!value) {
							delete o_column[s_key];
						}
						if (Ext.isFunction(value)) {
							delete o_column[s_key];
						}

						if (value instanceof Ext.Component) {
							delete o_column[s_key];
						}
					});

					delete o_column.dataIndex;
					delete o_column.header;
					delete o_column.entity;
					delete o_column.menuDisabled;
					delete o_column.draggable;
					delete o_column.dataOnly;
					delete o_column.headerText;
					delete o_column.columnConfig;


					if (!o_column.hide) {
						delete o_column.hide;
					}

					Ext.apply(o_column, {
						hidden: i_column.hidden,
						showned: i_column.showned !== undefined ? i_column.showned : true,
						hide: i_column.dataOnly !== undefined ? i_column.dataOnly : false,
						isTitle: i_column.isTitle || false,
						sequence: n_index
					});

					if (o_column.mapping) {
						a_extra.push(o_column);
					}
					else {
						a_return.push(o_column);
					}

					n_index++;

				}
			});

			var i_panel = i_self.down("#form-" + i_grid.getUiView());
			var i_form = i_panel.getForm();
			var o_values = i_form.getFieldValues();

			if (o_values.as) {
				if (Ext.isString(o_values.as)) {
					o_values.as = o_values.as.split("\n");
				}
			}

			if (o_values.features) {
				if (Ext.isString(o_values.features)) {
					o_values.features = Ext.decode(o_values.features, true) || {};
				}
			}
			else {
				delete o_values.features;
			}

			if (o_values.extraParams) {
				if (Ext.isString(o_values.extraParams)) {
					o_values.extraParams = Ext.decode(o_values.extraParams, true) || {};
				}
			}
			else {
				delete o_values.extraParams;
			}

			var o_menu = Ext.apply({}, {
				main : o_values.main,
				path: o_values.path,
				event: o_values.event
			});

			delete o_values.main;
			delete o_values.path;
			delete o_values.event;

			var o_sorters = i_store.getSorters();
			var a_sort = [];

			Ext.Array.each(o_sorters.items, function(o_sort) {

				var s_property = o_sort.getProperty();

				var o_found = Ext.Array.findBy(a_columns, function(i_column) {
					return i_column.dataIndex == s_property && !i_column.hidden;
				});

				if (!o_found) {
					o_found = Ext.Array.findBy(a_extra, function(o_column) {
						return o_column.name == s_property && !o_column.hidden;
					});
				}

				if (o_found) {
					var s_sorter = o_sort.getProperty() + " " + o_sort.getDirection();
					a_sort.push(s_sorter);
				}
			});

			var i_filterBar = i_grid.getFilterBar();
			var a_filters = i_filterBar.getFilterConfig();

			var o_view = o_old[i_grid.getUiView()] || Ext.apply({}, {
				features: {
					menu: {}
				}
			});

			var o_ui = Ext.Object.merge({}, o_view, o_values, {
				menu: o_menu,
				columns: a_return,
				extraColumns: a_extra,
				sort: a_sort.join(", "),
				filters: a_filters
			});

			if (!o_values.as) {
				delete o_ui.as;
			}

			if (!o_values.plugins) {
				delete o_ui.plugins;
			}

			if (!o_values.gridplugins) {
				delete o_ui.gridplugins;
			}

			if (!o_values.extfeatures) {
				delete o_ui.extfeatures;
			}

			o_entity.ui.grids[i_grid.getUiView()] = o_ui;
		});

		return o_entity;
	}
});
