Ext.define("Portfolio.center.view.Main", {

	xtype: "portfolio-centertabs",

	extend: "Ext.tab.Panel",

	layout: "fit",

	region: "center",

	minTabWidth: 100,

	stateId: "portfolio-center-main",

	stateful: false,

	requires: [
		"Ext.ux.BoxReorderer",
		"Ext.ux.TabReorderer",
		"Ext.ux.TabCloseMenu"
	],

	plugins: [
		"tabclosemenu",
		"tabreorderer"
	],

	config: {
		dropZone: null,
		applications: new Ext.util.Collection(),
		addCount: 0,
		appQue: new Ext.util.Collection(),
		activateTab: 0,
		windows: []
	},

	stateEvents: [
		"add",
		"remove",
		"tabchange",
		"stateupdate"
	],

	ui: "centertabs",

	listeners: {
		afterrender: {
			fn: function(i_tabpanel) {

				var i_self = i_tabpanel;

				var i_tabBar = i_tabpanel.getTabBar();

				var i_dropzone = new Ext.dd.DropZone(i_tabBar.getEl(), {
					ddGroup: "tree2fav",
					getTargetFromEvent: function(i_event) {
						return i_tabBar;
					},
					onNodeOver: function(i_target, i_soruce, i_event, o_data) {

						var s_return = Ext.dd.DropZone.prototype.dropAllowed;
						var a_records = o_data.records;

						var a_tabs = i_target.items.getRange();

						var b_allowed = true;

						Ext.Array.each(a_tabs, function(i_tab) {

							if (i_event.within(i_tab.getEl())) {
								b_allowed = false;
								return false;
							}
						});

						Ext.Array.each(a_records, function(i_node) {
							if (!i_node.isLeaf()) {
								b_allowed = false;
								return false;
							}
						});

						if (!b_allowed) {
							s_return = Ext.dd.DropZone.prototype.dropNotAllowed;
						}

						return s_return;
					},
					onNodeDrop: function(i_target, i_source, i_event, o_data) {

						var a_tabs = i_target.items.getRange();

						var b_found = false;

						Ext.Array.each(a_tabs, function(i_tab) {

							if (i_event.within(i_tab.getEl())) {
								b_found = true;
								return false;
							}
						});

						if (!b_found) {
							var a_records = o_data.records;
							var i_record = a_records[0];
							i_self.fireEvent("startapplication", i_record);
						}

						return !b_found;
					}
				});

				i_self.setDropZone(i_dropzone);

				i_self.initKeys();
			},
			buffer: 100
		},
		applicationReady: {
			fn: function (i_panel, i_child, b_window) {

				var i_self = this;
				var n_count = i_self.getAddCount();
				var i_appQue = i_self.getAppQue();
				var n_activate = i_self.getActivateTab();

				if (i_child) {
					i_appQue.add(i_child);
				}

				n_count--;

				if (n_count === 0) {

					var a_items = i_appQue.getRange();

					if (Ext.isBoolean(b_window) && b_window) {

						i_self.detachApplication(a_items, false);

					}
					else {

						Ext.suspendLayouts();

						i_self.add(a_items);

						if (a_items.length == 1) {

							i_child = a_items[0];

							if (i_child) {
								if (i_child.startActive) {
									i_self.setActiveTab(i_child);
								}
							}
						}
						else {
							i_self.setActiveTab(n_activate);
						}

						Ext.Array.each(a_items, function (i_item) {

							i_item.tab.on({
								afterrender: {
									fn: function () {
										i_item.tab.tt = Ext.create("Ext.tip.ToolTip", {
											target: i_item.tab.getEl(),
											html: "",
											anchor: true,
											defaultAlign: "b50-t50",
											showDelay: 10,
											listeners: {
												beforeshow: {
													fn: function (i_tip) {

														var i_collection = i_self.items.getRange();

														var n_index = i_collection.indexOf(i_item);

														if (n_index > - 1) {
															i_tip.update("Alt + " + (n_index + 1));
														}
														else {
															return false;
														}

													}
												}
											}
										});
									},
									single: true
								},
								dblclick: {
									element: "el",
									fn: function (i_event) {
										i_self.fireEvent("toWindow", i_item);
									}
								}
							});
						});

						i_self.setActivateTab(0);

						Ext.resumeLayouts(true);

						i_self.fireEvent("applicationAdded", i_self, a_items);
					}

					i_appQue.clear();
				}

				i_self.setAddCount(n_count);
			}
		},
		startapplication: {
			fn: function(i_record, b_window) {

				var i_self = this;
				var i_applications = i_self.getApplications();

				var o_properties;
				var o_data;

				var a_values = Ext.Array.from(i_record);

				var n_addCount = i_self.getAddCount();

				n_addCount = n_addCount + a_values.length;

				i_self.setAddCount(n_addCount);

				Ext.Array.each(a_values, function(i_record) {

					if (i_record.isModel) {
						o_properties = Ext.apply({}, i_record.get("properties") || {});
						o_data = i_record.getData();

						if (Ext.Object.isEmpty(o_properties)) {
							o_properties = o_data;
						}
					}
					else {
						o_data = o_properties = Ext.apply({}, i_record);
					}

					var s_url = o_data.url || o_properties.url || o_data.link;
					var s_title = Portfolio.util.Handler.i18n(o_properties.title || o_data.text || o_data.title);

					if (o_properties.hasOwnProperty("startActive")) {
						o_data.startActive = o_properties.startActive;
					}
					else {
						o_data.startActive = Ext.isBoolean(o_data.startActive) ? o_data.startActive : true;
					}

					if (Ext.isObject(s_title)) {
						s_title = Portfolio.util.Handler.i18n(s_title);
					}

					var i_child;
					var b_forced = o_data.force || false;

					if (!b_forced) {

						Ext.Array.each(i_applications.getRange(), function(o_config) {

							var o_configData = o_config.data || {};
							var o_configProperties = o_configData.properties || {};

							var s_configData = Ext.encode(o_configData);
							var s_configProperties = Ext.encode(o_configProperties);

							var s_data = Ext.encode(o_data);
							var s_properties = Ext.encode(o_properties);

							if (Ext.Object.isEmpty(o_configProperties) && Ext.Object.isEmpty(o_properties)) {
								if (s_data == s_configData) {
									i_child = o_config.active;
								}
								else if (o_configData.url == s_url) {
									i_child = o_config.active;
								}
							}
							else {
								if (s_properties == s_configProperties) {
									i_child = o_config.active;
								}
								else if (s_url && o_configData.url == s_url) {

									var o_temp = i_record.isModel ? Ext.clone(o_properties) : Ext.clone(o_data);
									var o_configClone = i_record.isModel ? Ext.clone(o_configProperties) : Ext.clone(o_configData);

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

										if (Ext.isPrimitive(value)) {
											if (Ext.isEmpty(value)) {
												delete o_temp[s_key];
											}
										}
										else if (Ext.isArray(value)) {
											if (value.length === 0) {
												delete o_temp[s_key];
											}
										}
										else if (Ext.isObject(value)) {
											if (Ext.Object.isEmpty(value)) {
												delete o_temp[s_key];
											}
										}
									});

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

										if (Ext.isPrimitive(value)) {
											if (Ext.isEmpty(value)) {
												delete o_configClone[s_key];
											}
										}
										else if (Ext.isArray(value)) {
											if (value.length === 0) {
												delete o_configClone[s_key];
											}
										}
										else if (Ext.isObject(value)) {
											if (Ext.Object.isEmpty(value)) {
												delete o_configClone[s_key];
											}
										}
									});

									var s_temp = Ext.encode(o_temp);
									var s_clone = Ext.encode(o_configClone);

									if (s_temp == s_clone) {
										i_child = o_config.active;
									}
									else {
										delete o_temp.url;
										delete o_temp.link;

										if (Ext.Object.isEmpty(o_temp)) {
											i_child = o_config.active;
										}
										else {

											delete o_configClone.url;

											if (Ext.Object.isEmpty(o_configClone)) {
												i_child = o_config.active;
											}
										}
									}
								}
								else if (s_data == s_configProperties) {
									i_child = o_config.active;
								}
								else if (s_properties == s_configProperties) {
									i_child = o_config.active;
								}
							}

							if (i_child) {
								return false;
							}
						});
					}
					else {
						o_properties.force = b_forced;
					}

					if (!i_child) {

						Portfolio.util.Handler.mask();

						if (s_url) {

							var s_params = s_url.split("?").pop();
							var o_params = Ext.urlDecode(s_params);

							if (/\B#\w+/.test(s_url)) {
								n_addCount--;
								i_self.setAddCount(n_addCount);

								Portfolio.Router.instance.redirectTo(s_url, true);
							}
							else if (!/\.(js|widget)/.test(s_url)) {

								if (o_data.target == "_blank") {

									window.open(s_url, "_blank");

									Portfolio.util.Handler.unmask();
								}
								else {
									Ext.require("Portfolio.ux.container.Iframe", function() {

										var i_created = Ext.widget("portfolio-ux-container-iframe", {
											title: s_title,
											src: s_url,
											closable: true
										});

										i_self.afterRequire(i_created, o_data, b_window);
									});
								}
							}
							else if (/\.(widget)/.test(s_url)) {

								if (/\.*portfolioMenu/.test(s_url)) {
									Ext.require("Portfolio.menu.view.Editor", function() {
	
										var i_created = Ext.widget("portfolio-menu-editor", {
											title: s_title,
											dmd: "dmd/portfolio.dmd",
											entity: "NAVMNUET00",
											viewName: "portfolio",
											context: "grid",
											parentID: "MNUPNTTKN",
											childID: "MNUMNUTKN",
											closable: true
										});
	
										i_self.afterRequire(i_created, o_data, b_window);
									});
								}
								else {
									i_child = ip2.callWidget(o_properties);

									if (i_child) {

										if (i_child.addDocked) {

											if (o_properties.hasOwnProperty("allowLink")) {

												if (o_properties.allowLink) {

													var a_items = [
														{
															xtype: "tbfill"
														},
														{
															xtype: "button",
															iconCls: "pf-link",
															itemId: "button-link",
															handler: function(i_button) {

																var s_name = s_url.split(".").shift();

																var i_window = Ext.widget("link.window", {
																	model: {
																		widget: {
																			name: s_name
																		}
																	}
																});

																i_window.show();
															}
														}
													];

													var i_toolbar = Ext.widget("toolbar", {
														dock: "bottom",
														items: a_items,
														itemId: "linkbar"
													});

													i_child.addDocked(i_toolbar);
												}
											}
										}

										s_title = s_title || ip2.i18n(i_child.getTitle());
										i_child.setTitle(s_title);
										i_self.afterRequire(i_child, o_data, b_window);
									}
									else {
										Portfolio.util.Handler.unmask();
									}
								}
							}
							else if (/(run-dmd.js).*/.test(s_url)) {

								Ext.require("Portfolio.entity.view.Panel", function() {

									var i_created = Ext.widget("portfolio-entity-panel", {
										title: s_title,
										dmd: {
											path: o_params.dmd || "dmd/webshop.dmd",
											entityName: o_params.entity
										},
										uiName: o_params.view || "portfolio",
										defaultFilter: o_params.filter,
										defaultCollection: o_params.collection,
										closable: true
									});

									i_self.afterRequire(i_created, o_data, b_window);
								});
							}
							else if (/(run-dmd-tree).*/.test(s_url)) {

								Ext.require("Portfolio.entity.view.Tree", function() {

									var i_created = Ext.widget("portfolio-entity-tree", {
										title: s_title,
										dmd: o_params.dmd,
										entity: o_params.entity,
										viewName: o_params.view || "portfolio",
										parentID: o_params.parentID,
										childID: o_params.childID,
										textProperty: o_params.textProperty,
										sequence: o_params.sequence,
										closable: true
									});

									i_self.afterRequire(i_created, o_data, b_window);
								});
							}
							else if (/(run-dynapp).*/.test(s_url)) {

								Ext.require("Portfolio.dynapp.App", function() {

									var i_created = Ext.create("Portfolio.dynapp.App", {
										title: s_title,
										options: {
											library: o_params.lib || o_params.library || "",
											file: o_params.file
										},
										closable: true
									});

									i_self.afterRequire(i_created, o_data, b_window);
								});
							}
							else if (/(run-registry).*/.test(s_url)) {

								Ext.require("Portfolio.registry.App", function() {

									var i_created = Ext.create("Portfolio.registry.App", {
										title: s_title,
										options: {
											library: o_params.lib || o_params.library || "",
											file: o_params.file
										},
										closable: true
									});

									i_self.afterRequire(i_created, o_data, b_window);
								});
							}
							else if (/(start-dmd).*/.test(s_url)) {

								Ext.require("Portfolio.designer.view.Main", function() {

									var i_created = Ext.create("Portfolio.designer.view.Main", {
										title: s_title,
										closable: true
									});

									i_self.afterRequire(i_created, o_data, b_window);
								});
							}
							else {
								i_child = ip2.callWidget(o_properties);
								if (i_child) {
									i_child.setTitle(s_title);
									i_self.afterRequire(i_child, o_data, b_window);
								}
								else {
									Portfolio.util.Handler.unmask();
								}
							}
						}
						else {

							var o_widget;

							if (o_properties.hasOwnProperty("appFolder") || o_properties.hasOwnProperty("main")) {
								o_properties.startActive = o_data.startActive;
								i_self.openApplication(o_properties);
							}
							else if (o_properties.hasOwnProperty("widget")) {

								eval("o_widget = " + o_properties.widget);

								o_widget = o_widget || {
									xtype: "panel"
								};

								Ext.applyIf(o_widget, {
									title: ip2.i18n(o_properties.title)
								});

								i_self.fireEvent("applicationAdd", o_widget.xtype, o_widget, o_data, b_window);
							}
							else if (o_data.hasOwnProperty("widget")) {

								s_title = ip2.i18n(o_data.title || o_data.text);

								eval("o_widget = " + o_data.widget);

								o_widget = o_widget || {
									xtype: "panel"
								};

								if (s_title) {
									Ext.applyIf(o_widget, {
										title: s_title
									});
								}

								i_self.fireEvent("applicationAdd", o_widget.xtype, o_widget, o_data, b_window);
							}
							else if (o_data.hasOwnProperty("component")) {

								s_title = ip2.i18n(o_data.title || o_data.text);

								o_widget = o_data.component || {};

								i_self.fireEvent("applicationAdd", o_widget.xtype, o_widget, o_data, b_window);
							}
							else if (o_data.entity && o_data.dmd) {

								Ext.require("Portfolio.entity.view.Form", function() {

									var i_record = Portfolio.util.Handler.getUser();


									var i_created = Ext.widget("portfolio-entity-form", {
										keys: o_data.keys,
										action: o_data.action,
										dmd: o_data.dmd,
										entity: o_data.entity,
										view: o_data.view,
										oldData: o_data.oldData || o_data.data || null,
										context: "form",
										language: i_record.get("USRLNG") || "en",
										closable: true,
										defaultCollection: o_data.defaultCollection || "",
										transactiontype: o_data.transactiontype || o_data.entityName,
										activeTabIndex: o_data.activeTabIndex || 0,
										linkable: o_data.hasOwnProperty("linkable") ? o_data.linkable : true,
										deletable: o_data.hasOwnProperty("deletable") ? o_data.deletable : true,
										listeners: {
											contentReady: {
												fn: function(i_content, i_entityPanel, b_recreate) {
													if (!b_recreate) {
														i_self.afterRequire(i_entityPanel, o_data, b_window);
													}
												},
												buffer: 100
											},
											contentCancel: {
												fn: function(i_entityPanel) {
													i_self.onCancel(i_entityPanel);
												},
												single: true
											}
										}
									});

									if (o_data.hasOwnProperty("listeners") && Ext.isObject(o_data.listeners)) {
										i_created.on(o_data.listeners);
									}
								});
							}
							else if (o_data.xtype) {
								i_self.fireEvent("applicationAdd", o_data.xtype, o_data, null, b_window);
							}
						}
					}
					else {

						n_addCount--;

						i_self.setAddCount(n_addCount);

						i_self.setActiveTab(i_child);
					}
				});
			}
		},
		entityedit: {
			fn: function(o_keys, o_config, s_action) {

				var i_self = this;

				var o_data = Ext.apply({}, {
					action: s_action,
					keys: o_keys,
					entity: o_config.entityName || o_config.entity,
					view: o_config.uiName || o_config.view,
					dmd: o_config.dmd,
					defaultCollection: o_config.defaultCollection,
					transactiontype: o_config.entityName,
					activeTabIndex: o_config.activeTabIndex || 0,
					oldData: o_config.data || null,
					listeners: o_config.listeners || null,
					linkable: o_config.hasOwnProperty("linkable") ? o_config.linkable : true,
					deletable: o_config.hasOwnProperty("deletable") ? o_config.deletable : true
				});

				i_self.fireEvent("startapplication", o_data);
			}
		},
		entityWindow: {
			fn: function(o_keys, o_config, s_action, o_windowConfig, s_managerId) {

				var i_self = this;

				var i_record = Portfolio.util.Handler.getUser();

				Ext.require("Portfolio.entity.view.Form", function() {

					var i_entityPanel = Ext.widget("portfolio-entity-form", {
						keys: o_keys,
						action: s_action,
						dmd: o_config.dmd,
						header: false,
						entity: o_config.entityName || o_config.entity,
						view: o_config.uiName || o_config.view,
						oldData: o_config.data || null,
						context: "form",
						language: i_record.get("USRLNG") || "en",
						closable: false,
						createTitle: o_config.createTitle ? o_config.createTitle : true,
						defaultCollection: o_config.defaultCollection || "",
						transactiontype: o_config.transactiontype || o_config.entityName || o_config.entity,
						activeTabIndex: o_config.activeTabIndex || 0,
						linkable: o_config.hasOwnProperty("linkable") ? o_config.linkable : true,
						deletable: o_config.hasOwnProperty("deletable") ? o_config.deletable : true,
						listeners: {
							contentReady: {
								fn: function(i_entityPanel) {
									Portfolio.util.Handler.unmask();
								},
								single: true
							},
							contentCancel: {
								fn: function(i_entityPanel) {
									i_self.onCancel(i_entityPanel);
								},
								single: true
							}
						}
					});

					if (o_config.hasOwnProperty("listeners") && Ext.isObject(o_config.listeners)) {
						i_entityPanel.on(o_config.listeners);
					}

					delete o_config.container;

					i_self.afterRequire(i_entityPanel, o_config, true, function() {

						i_self.detachApplication([i_entityPanel], false, o_windowConfig, s_managerId);

					});

				});
			}
		},
		applicationAdd: {
			fn: function (s_main, o_config, o_data, b_window) {

				var i_self = this;
				var i_application;
				var i_user = ip2.getUser();

				o_data = o_data || o_config;

				var n_count = i_self.getAddCount();

				if (n_count == 0) {
					n_count++;
					i_self.setAddCount(n_count);
					o_data.startActive = true;
				}

				Portfolio.util.Handler.mask("Loading...");

				Ext.apply(o_config, {
					closable: true,
					reorderable: true
				});

				if (/^\w+\.\w+/.test(s_main)) {

					if (s_main.toLowerCase() == "icecap.view.main" || o_config.xtype.toLowerCase() == "icecap-panel") {
						Ext.apply(o_config, {
							bodyCls: "centertabs-panel",
							activeLanguage: i_user.get("USRLNG") || "da"
						});
					}

					Ext.require(s_main, function() {

						i_application = Ext.create(s_main, o_config);

						if (i_application) {
							i_self.afterRequire(i_application, o_data, b_window);
						}
						else {
							Portfolio.util.Handler.unmask();
						}
					});
				}
				else {

					if (s_main.toLowerCase() == "icecap.view.main" || o_config.xtype.toLowerCase() == "icecap-panel") {
						Ext.apply(o_config, {
							bodyCls: "centertabs-panel",
							activeLanguage: i_user.get("USRLNG") || "da"
						});
					}

					i_application = Ext.widget(s_main, o_config);

					if (i_application) {
						i_self.afterRequire(i_application, o_data, b_window);
					}
					else {
						Portfolio.util.Handler.unmask();
					}
				}
			}
		},
		addContainer: {
			fn: function (i_instance, b_window) {

				var i_self = this;

				var o_data = i_instance.initialConfig || {};

				Ext.applyIf(o_data, {
					xtype: i_instance.xtype
				});

				i_self.fireEvent("startapplication", o_data, b_window);
			}
		},
		applicationError: {
			fn: function() {

				var i_self = this;

				var n_count = i_self.getAddCount();
				n_count--;

				if (n_count < 0) {
					n_count = 0;
				}

				i_self.setAddCount(n_count);

				Ext.resumeLayouts(true);
			}
		},
		toWindow: {
			fn: function (i_item, o_windowConfig) {
				var i_self = this;
				i_self.detachApplication(i_item, o_windowConfig);
			}
		},
		toTab: {
			fn: function (i_item, o_data) {
				var i_self = this;
				i_self.attachApplication(i_item, o_data);
			}
		},
		compare: {
			fn: function (i_tab, i_compare) {

				var i_self = this;
				i_self.detachApplication([i_tab, i_compare], true);
				Portfolio.app.fireEvent("resizewindows", true);
			}
		},
	},

	initComponent: function() {

		var i_self = this;

		i_self.callParent(arguments);

		i_self.mon(Portfolio.app, "startapplication", function(o_config, b_window) {
			i_self.fireEvent("startapplication", o_config, b_window);
		});

		i_self.mon(Portfolio.app, "entityedit", function(o_config, s_action) {
			i_self.fireEvent("entityedit", o_config.keys, o_config, s_action);
		});

		i_self.mon(Portfolio.app, "entityWindow", function(o_config, s_action, o_windowConfig, s_managerId) {
			i_self.fireEvent("entityWindow", o_config.keys, o_config, s_action, o_windowConfig, s_managerId);
		});

		i_self.mon(Portfolio.app, "applicationAdd", function (s_main, o_config, b_window) {
			i_self.fireEvent("applicationAdd", s_main, o_config, b_window);
		});

		i_self.mon(Portfolio.app, "addContainer", function (i_instance, b_window) {
			i_self.fireEvent("addContainer", i_instance, b_window);
		});

		i_self.mon(Portfolio.app, "applicationError", function(o_error) {
			i_self.fireEvent("applicationError", o_error);
		});

		i_self.mon(Portfolio.app, "toWindow", function (i_item, o_windowConfig) {
			i_self.fireEvent("toWindow", i_item, o_windowConfig);
		});

		i_self.mon(Portfolio.app, "toTab", function (i_item, o_data) {
			i_self.fireEvent("toTab", i_item, o_data);
		});

		i_self.mon(Portfolio.app, "compare", function (i_tab, i_compare) {
			i_self.fireEvent("compare", i_tab, i_compare);
		});


		Ext.getWin().on("message", function(i_event) {

			var i_bEvent = i_event.browserEvent ? i_event.browserEvent : i_event;

			if (i_bEvent.origin == location.origin) {

				var o_data = Ext.decode(i_bEvent.data, true) || {};

				if (o_data.event) {

					var o_config = o_data.config;

					i_self.fireEvent(o_data.event, o_config);
				}
			}
		});
	},

	initKeys: function() {

		var i_self = this;

		var a_bindings = [
			{
				key: Ext.event.Event.Z,
				alt: true,
				ctrl: false,
				fn: function(n_key, i_event) {
					i_event.stopEvent();

					var a_range = Ext.WindowManager.zIndexStack.getRange();

					if (a_range.length > 0) {

						var i_next = Ext.WindowManager.zIndexStack.getAt(0);

						Ext.WindowManager.bringToFront(i_next, false);

						var i_panel = i_next.down("panel");

						if (i_panel) {
							i_panel.focus();
						}
					}
				}
			},
			{
				key: Ext.event.Event.ONE,
				alt: true,
				ctrl: false,
				fn: function (n_key, i_event) {

					i_event.stopEvent();
					i_self.handleKeys(1);
				}
			},
			{
				key: Ext.event.Event.TWO,
				alt: true,
				ctrl: false,
				fn: function (n_key, i_event) {

					i_event.stopEvent();
					i_self.handleKeys(2);
				}
			},
			{
				key: Ext.event.Event.THREE,
				alt: true,
				ctrl: false,
				fn: function (n_key, i_event) {

					i_event.stopEvent();
					i_self.handleKeys(3);
				}
			},
			{
				key: Ext.event.Event.FOUR,
				alt: true,
				ctrl: false,
				fn: function (n_key, i_event) {

					i_event.stopEvent();
					i_self.handleKeys(4);
				}
			},
			{
				key: Ext.event.Event.FIVE,
				alt: true,
				ctrl: false,
				fn: function (n_key, i_event) {

					i_event.stopEvent();
					i_self.handleKeys(5);
				}
			},
			{
				key: Ext.event.Event.SIX,
				alt: true,
				ctrl: false,
				fn: function (n_key, i_event) {

					i_event.stopEvent();
					i_self.handleKeys(6);
				}
			},
			{
				key: Ext.event.Event.SEVEN,
				alt: true,
				ctrl: false,
				fn: function (n_key, i_event) {

					i_event.stopEvent();
					i_self.handleKeys(7);
				}
			},
			{
				key: Ext.event.Event.EIGHT,
				alt: true,
				ctrl: false,
				fn: function (n_key, i_event) {

					i_event.stopEvent();
					i_self.handleKeys(8);
				}
			},
			{
				key: Ext.event.Event.NINE,
				alt: true,
				ctrl: false,
				fn: function (n_key, i_event) {

					i_event.stopEvent();
					i_self.handleKeys(9);
				}
			},
			{
				key: Ext.event.Event.F3,
				alt: true,
				ctrl: false,
				fn: function (n_key, i_event) {

					i_event.stopEvent();

					var i_activeElement = Ext.get(Ext.Element.getActiveElement());
					var i_component = i_activeElement.component;

					var b_handel = false;

					if (i_component) {

						var i_window;

						if (i_component.isXType("window")) {
							i_window = i_component;
						}
						else {
							i_window = i_component.up("window");
						}

						if (i_window) {
							b_handel = true;
							i_window.close();
						}
					}

					if (!b_handel) {

						var i_active = i_self.getActiveTab();

						if (i_active) {
							var n_active = i_self.items.indexOf(i_active);

							n_active--;

							if (n_active > -1) {
								i_self.setActiveTab(n_active);
							}

							i_active.close();
						}
					}
				}
			}
		];

		var i_keyMap = Ext.create("Ext.util.KeyMap", {
			target: Ext.getDoc().el,
			binding: a_bindings
		});

		return i_keyMap;
	},

	handleKeys: function(n_key) {

		var i_self = this;

		var n_length = i_self.items.getCount();

		var n_active = n_key - 1;

		i_self.setActiveTab(n_active);
	},

	openApplication: function(o_application) {

		var i_self = this;

		var s_appName = o_application.appName || o_application.main;
		var s_mainView = o_application.main || s_appName + ".view.Main";

		var o_temp = o_application.appConfig || {};

		var o_appConfig = Ext.apply(o_temp, {
			title: ip2.i18n(o_application.title),
			closable: true
		});

		if (!s_appName) {

			Portfolio.util.Handler.messageBox({
				title: "Error",
				icon: Ext.Msg.ERROR,
				message: ip2.i18n({
					da: "Manglende app navn",
					en: "Missing app name"
				}),
				yesText: "Ok"
			});

			return null;
		}

		var f_destroy = function() {

			var a_items = i_self.items.getRange();
			var n_count = 0;

			Ext.Array.each(a_items, function(i_container) {
				if (i_container.appName === s_appName) {
					n_count++;
				}
			});

			if (n_count === 0) {

				var i_namespace = Ext.namespace(s_appName);

				if (i_namespace) {

					var i_application = i_namespace.getApplication();

					if (i_application) {

						i_application.destroy();

						Ext.undefine(s_appName + ".$application")
						;
						delete Ext.app.namespaces[s_appName];
					}
				}
			}
		};

		var i_user = ip2.getUser();

		if (!Ext.app.namespaces[s_appName]) {

			var a_requires = Ext.Array.from(o_application.requires);
			var a_scripts = Ext.Array.from(o_application.requiredScripts);

			a_requires = Ext.Array.clone(a_requires);
			a_scripts = Ext.Array.clone(a_scripts);

			if (!Ext.Array.contains(a_requires, s_mainView)) {
				a_requires.push(s_mainView);
			}

			a_requires = Ext.Array.filter(a_requires, function(value) {
				return value;
			});

			a_scripts = Ext.Array.filter(a_scripts, function(value) {
				return value;
			});

			var s_appPath = o_application.appFolder;
			var o_packages = o_application.packages;

			if (!o_packages && !s_appPath) {

				Portfolio.util.Handler.messageBox({
					title: "Error",
					icon: Ext.Msg.ERROR,
					message: ip2.i18n({
						da: "Paths eller appFolder skal være tilstede",
						en: "Paths or appFolder must be present"
					}),
					yesText: "Ok"
				});

				return null;
			}

			if (!o_packages) {
				o_packages = {};
				o_packages[s_appName] = o_application.appFolder;
			}



			var o_config = Ext.apply({}, {
				appFolder: s_appPath,
				name: s_appName,
				requires: a_requires,
				paths: o_packages,
				mixins: [
					"Ext.mixin.Mashup"
				],
				requiredScripts: a_scripts,
				launch: function() {

					if (s_mainView.toLowerCase() == "icecap.view.main") {
						Ext.apply(o_appConfig, {
							bodyCls: "centertabs-panel",
							activeLanguage: i_user.get("USRLNG") || "da",
							appName: s_appName
						});
					}

					var i_mainView = Ext.create(s_mainView, o_appConfig);

					i_self.afterRequire(i_mainView, o_application);

					if (i_mainView.isXType) {

						i_mainView.appName = s_appName;

						i_mainView.on({
							destroy: {
								fn: f_destroy
							},
							contentCancel: {
								fn: function(i_entityPanel) {
									i_self.onCancel(i_entityPanel);
									f_destroy.call(i_self);
								},
								single: true
							}
						});
					}
					else {
						setTimeout(function() {
							f_destroy();
						}, 100);
					}
				}
			});

			if (!o_config.appFolder) {
				delete o_config.appFolder;
			}

			Ext.application(o_config);
		}
		else {

			if (o_application.force) {

				if (s_mainView.toLowerCase() == "icecap.view.main") {
					Ext.apply(o_appConfig, {
						bodyCls: "centertabs-panel",
						activeLanguage: i_user.get("USRLNG") || "da"
					});
				}

				var i_mainView = Ext.create(s_mainView, o_appConfig);

				i_self.afterRequire(i_mainView, o_application);

				if (i_mainView.isXType) {

					i_mainView.appName = s_appName;

					i_mainView.on({
						destroy: {
							fn: f_destroy
						},
						contentCancel: {
							fn: function(i_entityPanel) {
								i_self.onCancel(i_entityPanel);
								f_destroy.call(i_self);
							},
							single: true
						}
					});
				}
				else {
					setTimeout(function() {
						f_destroy();
					}, 100);
				}
			}
			else {
				var a_containers = i_self.items.getRange();
				var i_application;

				Ext.Array.each(a_containers, function(i_container) {
					if (i_container.$className === s_mainView) {
						i_application = i_container;
						return false;
					}
				});

				if (i_application) {
					i_self.setActiveTab(i_application);
				}

				var n_count = i_self.getAddCount();

				n_count--;

				i_self.setAddCount(n_count);

				Portfolio.util.Handler.unmask();
			}
		}
	},

	afterRequire: function (i_child, o_data, b_window, f_callback) {

		Portfolio.util.Handler.unmask();

		f_callback = f_callback || Ext.emptyFn;

		var i_self = this;
		var a_allowed = ["panel", "container", "tappanel", "gridpanel"];

		var b_add = i_child.isXType ? i_child.isXType("container") : Ext.Array.contains(a_allowed, i_child.xtype);

		if (b_add) {

			i_child.startActive = o_data.startActive;

			var i_applications = i_self.getApplications();
			var s_id = Ext.id(null, "app-");

			if (i_child.itemId) {
				delete i_child.itemId;
			}

			i_applications.add({
				id: s_id,
				data: o_data,
				active: i_child
			});

			i_child.closable = true;
			i_child.reorderable = true;

			i_child.on({
				destroy: {
					fn: i_self.removeApplication,
					scope: i_self
				}
			});
		}

		if (Ext.emptyFn != f_callback) {
			f_callback.call(i_self);
		}
		else {
			i_self.fireEvent("applicationReady", i_self, b_add ? i_child : null, b_window);
		}

	},

	onCancel: function() {

		var i_self = this;

		var n_count = i_self.getAddCount();

		n_count--;

		i_self.setAddCount(n_count);
	},

	getState: function() {

		var i_self = this;

		var o_state = {
			tabs: [],
			activeTabIndex: -1
		};

		var i_applications = i_self.getApplications();
		var a_items = i_applications.getRange();

		Ext.Array.each(a_items, function(o_config) {

			var i_panel = o_config.active;

			var o_data = Ext.clone(o_config.data);

			if (i_panel) {

				var o_stateInfo = i_panel.getState();

				var o_appConfig = o_stateInfo.appConfig || o_stateInfo;

				if (o_data.hasOwnProperty("component")) {

					var o_component = o_data.component;
					Ext.apply(o_component, o_appConfig);
				}
				else {

					if (o_data.hasOwnProperty("appFolder") || o_data.hasOwnProperty("main")) {
						Ext.apply(o_data, o_stateInfo);
					}
					else {
						Ext.apply(o_data, o_appConfig);
					}
				}
			}

			o_state.tabs.push(o_data);
		});

		if (a_items.length > 0) {
			o_state.activeTabIndex = i_self.items.indexOf(i_self.getActiveTab());
		}

		return o_state;
	},

	applyState: function(o_state) {

		var i_self = this;
		var o_nullState = Ext.state.Manager.get("portfolio-center-main-null");

		if (o_nullState) {
			Ext.state.Manager.clear("portfolio-center-main-null");
		}

		Ext.applyIf(o_state, {
			tabs: [],
			activeTabIndex: -1
		});

		var a_states = Ext.Array.from(o_state.tabs);

		if (a_states.length > 0 && i_self.stateful) {

			var n_activate = o_state.activeTabIndex || 0;

			i_self.on({
				applicationAdded: {
					fn: function(i_self, a_items) {
						i_self.setActiveTab(n_activate);
					},
					single: true
				}
			});

			i_self.fireEvent("startapplication", a_states);

			Ext.GlobalEvents.fireEvent("centerReady", i_self);
		}
	},

	detachApplication: function (items, b_comparing, o_windowConfig, s_managerId) {

		var i_self = this;
		var i_applications = i_self.getApplications();

		o_windowConfig = o_windowConfig || {};

		var a_item = Ext.Array.from(items);

		Ext.Array.each(a_item, function(i_item) {

			var o_application = Ext.Array.findBy(i_applications.getRange(), function (o_config) {

				return o_config.active == i_item ? o_config : false;
			});

			if (o_application) {

				var o_data = o_application.data || {};

				if (i_item.tab && i_item.tab.tt) {
					i_item.tab.tt.destroy();

					delete i_item.tab.tt;
				}

				var o_restoreState = o_data.restoreState || {};

				delete o_data.o_restoreState;

				var o_size = Portfolio.util.Handler.getWindowSize();
				var n_height = o_windowConfig.height || o_size.height * 0.6;
				var n_width = o_windowConfig.width || o_size.width * 0.6;

				if (o_restoreState.hasOwnProperty("size")) {

					o_size = o_restoreState.size;
					n_height = o_size.height;
					n_width = o_size.width;
				}

				if (i_item.isXType("icecap-panel")) {
					n_width = null;
					n_height = null;
				}

				var i_topmost = Ext.WindowManager.topMost;

				Portfolio.app.fireEvent("beforedetached", o_windowConfig);

				var i_window = Ext.widget("window", Ext.applyIf({
					layout: "fit",
					height: n_height,
					width: n_width,
					constrain: true,
					maximizable: true,
					stateData: Ext.clone(o_application.data),
					comparing: b_comparing,
					listeners: {
						destroy: {
							fn: function (i_window) {

								var a_windows = i_self.getWindows();
								Ext.Array.remove(a_windows, i_window);

								i_self.setWindows(a_windows);
							}
						},
						afterrender: {
							fn: function (i_window) {

								var i_header = i_window.header;

								if (i_header && i_window.stateData) {

									var i_tabTool = Ext.widget("tool", {
										iconCls: "pf-navigate_minus",
										tooltip: "To tab",
										handler: function () {

											var i_panel = i_window.down("panel");
											var o_size = i_window.getSize();

											var o_restoreState = {
												size: o_size,
												position: i_window.getPosition()
											};

											if (i_panel) {

												var o_stateData = i_window.stateData || {};

												Ext.apply(o_stateData, {
													restoreState: o_restoreState
												});

												i_panel.setTitle(i_window.title);

												Portfolio.app.fireEvent("toTab", i_panel, i_window.stateData);

												i_window.close();
											}
										}
									});

									i_header.add(1, i_tabTool);

									i_item.fireEvent("detach", i_item);

									i_item.show();
								}
							}
						}
					},
					items: [
						i_item
					]
				}, o_windowConfig));

				i_window.on({
					maximize: {
						fn: function() {
							i_window.setSize(i_window.constrainTo.getSize());
						}
					}
				});

				if (i_item.bodyCls) {
					i_item.removeBodyCls(i_item.bodyCls);
				}

				i_item.removeListener("destroy", i_self.removeApplication, i_self);

				i_item.on({
					beforedestroy: {
						fn: i_self.removeFromWindow,
						scope: i_self
					}
				});

				var a_windows = i_self.getWindows();

				if (!o_windowConfig.title) {
					i_window.setTitle(i_item.title);

					i_item.setTitle("");

				}

				if (o_restoreState.hasOwnProperty("position")) {

					var a_position = o_restoreState.position;

					i_window.showAt(a_position);
				}
				else {
					if (i_topmost) {

						var a_xy = i_topmost.getXY();

						i_window.showAt(a_xy[0] + 100, a_xy[1] + 100);
					}
					else {

						i_window.show();
					}

				}
				a_windows.push(i_window);

				i_self.setWindows(a_windows);

				i_applications.removeByKey(o_application.id);

				Portfolio.app.fireEvent("applicationdetached", i_window, s_managerId);
			}
		});

	},

	attachApplication: function (i_item, o_data) {

		var i_self = this;
		var i_applications = i_self.getApplications();

		var s_id = Ext.id(null, "app-");

		i_applications.add({
			id: s_id,
			data: o_data ? o_data : i_item.initialConfig,
			active: i_item
		});

		i_item.setClosable(true);
		i_item.reorderable = true;

		if (i_item.initialConfig.bodyCls) {
			i_item.addBodyCls(i_item.initialConfig.bodyCls);
		}

		i_item.removeListener("beforedestroy", i_self.removeFromWindow, i_self);

		i_item.on({
			destroy: {
				fn: i_self.removeApplication,
				scope: i_self
			}
		});

		Ext.suspendLayouts();

		var i_active = i_self.add(i_item);

		Ext.resumeLayouts(true);

		i_self.setActiveItem(i_active);

		i_active.tab.tt = Ext.create("Ext.tip.ToolTip", {
			target: i_active.tab.getEl(),
			html: "",
			anchor: true,
			defealtAlign: "b50-t50",
			showDelay: 10,
			listeners: {
				beforeshow: {
					fn: function (i_tip) {

						var i_collection = i_self.items.getRange();

						var n_index = i_collection.indexOf(i_item);

						if (n_index > - 1) {
							i_tip.update("Alt + " + (n_index + 1));
						}
						else {
							return false;
						}

					}
				}
			}
		});

		i_active.tab.on({
			dblclick: {
				element: "el",
				fn: function (i_event) {
					i_self.fireEvent("toWindow", i_item);
				}
			}
		});
	},

	removeApplication: function(i_component) {

		var i_self = this;
		var i_applications = i_self.getApplications();

		var o_application = Ext.Array.findBy(i_applications.getRange(), function (o_config) {

			return o_config.active == i_component ? o_config : false;
		});

		if (o_application) {
			i_applications.removeByKey(o_application.id);
		}
	},

	removeFromWindow: function(i_component) {

		var i_window = i_component.up("window");

		if (i_window) {
			i_window.close();
		}
	}

});
