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

	xtype: "portfolio-viewport",

	extend: "Ext.panel.Panel",

	layout: "border",

	border: false,

	config: {

		navigation: null,
		centerTabs: null,
		northArea: null,
		helpArea: null,
		centerStateFul: true,
		showHelp: true,
		hash: "",
		desktops: []
	},

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

				var i_self = this;
				var s_hash = i_self.getHash();

				if (s_hash) {
					Portfolio.Router.instance.redirectTo(s_hash, {
						force: true,
						replace: true
					});
				}
			},
			buffer: 10
		},
		startapplication: {
			fn: function(i_system, i_record) {

				var i_self = this;

				var i_centerTabs = i_self.getCenterTabs();
				i_centerTabs.fireEvent("startapplication", i_record);
			}
		},
		systemAdded: {
			fn: function (a_systems) {

				var i_self = this;
				var i_topArea = i_self.getNorthArea();

				i_topArea.fireEvent("systemAdded", a_systems);
			}
		},
		systemShortcut: {
			fn: function (s_itemId) {

				var i_self = this;
				var i_topArea = i_self.getNorthArea();

				i_topArea.fireEvent("systemShortcut", s_itemId);
			}
		},
		systemActivate: {
			fn: function (s_itemId) {

				var i_self = this;
				var i_navigation = i_self.getNavigation();

				i_navigation.fireEvent("systemActivate", s_itemId);
			}
		},
		aftershortcut: {
			fn: function (s_itemId) {

				var i_self = this;
				var i_navigation = i_self.getNavigation();

				i_navigation.fireEvent("aftershortcut", s_itemId);
			}
		},
		toggleNavigation: {
			fn: function(b_collapse) {

				var i_self = this;
				var i_navigation = i_self.getNavigation();

				if (!i_navigation.getPlaceholder().isVisible() && b_collapse) {
					i_navigation.collapse();
				}

			}
		},
		organizewindows: {
			fn: function () {

				var i_self = this;
				i_self.doOrganizeWindows();
			}
		},
		resizewindows: {
			fn: function (b_comparing) {
				var i_self = this;
				i_self.resizeAndOrganize(b_comparing);
			}
		},
		tabsToWindow: {
			fn: function() {
				var i_self = this;
				i_self.tabsToWindow();
			}
		},
		windowsToTab: {
			fn: function () {
				var i_self = this;
				i_self.windowsToTab();
			}
		},
		createdesktop: {
			fn: function () {
				var i_self = this;
				i_self.createDesktop();
			}
		},
		beforeDetached: {
			fn: function (o_config) {

				var i_self = this;
				i_self.addConstrain(o_config);
			}
		},
		applicationDetached: {
			fn: function (i_window, s_managerId) {

				var i_self = this;
				i_self.addToDesktop(i_window, s_managerId);
			}
		},
		hasTabs: {
			fn: function() {

				var i_self = this;
				var i_centerTabs = i_self.getCenterTabs();
				return i_centerTabs.items.getRange().length > 0;
			}
		}
	},

	initComponent: function() {

		var i_self = this;
		i_self.callParent(arguments);

		i_self.add(i_self.createLayout());

		var s_hash = Ext.History.getHash();

		if (s_hash) {
			i_self.setHash(s_hash);
		}

		i_self.enableBubble("login");

		i_self.mon(Portfolio.app, "toggleNavigation", function (b_collapse) {
			i_self.fireEvent("toggleNavigation", b_collapse);
		});

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

		i_self.mon(Portfolio.app, "resizewindows", function (b_comparing) {
			i_self.fireEvent("resizewindows", b_comparing);
		});

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

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

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

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

		i_self.mon(Portfolio.app, "applicationdetached", function (i_window, s_managerId) {
			i_self.fireEvent("applicationdetached", i_window, s_managerId);
		});

		i_self.mon(Portfolio.app, "hasTabs", function () {
			return i_self.fireEvent("hasTabs");
		});

		return i_self;
	},

	createLayout: function() {

		var i_self = this;

		var a_items = [];

		var o_params = Ext.Object.fromQueryString(window.location.search);

		var n_layout = parseInt(o_params.layout, 10) || o_params.hide || 0;

		var b_header = true;
		var b_navigation = true;
		var b_help = i_self.getShowHelp();
		var b_centertabs = true;
		var b_message = true;

		if (o_params.layout == "fullscreen" || o_params.layout == "terminal") {
			n_layout = 0xff;
		}

		if (o_params.layout == "frontend") {
			n_layout = 2;
		}

		// DOES HIDE CONTAIN BIT VALUE FOR 1 ('00001')
		if (n_layout & 1) {
			b_header = false;
		}

		// DOES HIDE CONTAIN BIT VALUE FOR 2 ('00010')
		if (n_layout & 2) {
			b_navigation = false;
		}

		// DOES HIDE CONTAIN BIT VALUE FOR 4 ('00100')
		if (n_layout & 4) {
			b_help = false;
		}

		// DOES HIDE CONTAIN BIT VALUE FOR 8 ('01000')
		if (n_layout & 8) {
			b_centertabs = false;
		}

		// DOES HIDE CONTAIN BIT VALUE FOR 16 ('10000')
		if (n_layout & 16) {
			b_message = false;
		}

		a_items.push(i_self.createTop(b_header));
		a_items.push(i_self.createWest(b_navigation));
		a_items.push(i_self.createCenter(b_centertabs));
		a_items.push(i_self.createEast(b_help));
		a_items.push(i_self.createBottom(b_message));

		return a_items;
	},

	createTop: function(b_show) {

		var i_self = this;

		var i_toppanel = Ext.widget("portfolio-top", {
			region: "north",
			hidden: !b_show
		});

		i_self.setNorthArea(i_toppanel);

		return i_toppanel;
	},

	createWest: function(b_show) {

		var i_self = this;

		var i_menu = Ext.widget("portfolio-menu", {
			title: ip2.i18n({
				da: "Navigation",
				en: "Navigation"
			}),
			width: 300,
			minwidth: 100,
			collapsible: true,
			split: {
				width: 1,
				size: 1
			},
			border: false,
			bodyBorder: false,
			region: "west",
			hidden: !b_show,
			header: {
				style: {
					"border-top": "0 !important;"
				}
			},
			listeners: {
				afterrender: {
					fn: function (i_panel) {
						var i_placeHolder = i_panel.getPlaceholder();
						if (i_placeHolder) {
							i_placeHolder.on({
								mouseenter: {
									fn: function () {
										i_panel.floatCollapsedPanel();
									},
									element: "el",
									scope: this
								}
							});
						}
					},
				}
			}
		});

		i_self.setNavigation(i_menu);

		return i_menu;
	},

	createCenter: function(b_show) {

		var i_self = this;

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

		var n_token = i_user.get("USRUSRTKN") || 0;

		var i_tabpanel = Ext.widget("portfolio-centertabs", {
			flex: 1,
			region: "center",
			split: true,
			stateful: b_show && n_token > 0 ? i_self.getCenterStateFul() : false,
			stateId: n_token > 0 ? "portfolio-center-main-" + i_user.get("USRUSRTKN") : ""
		});

		if (!b_show) {
			i_tabpanel.tabBar.hide();
		}

		i_self.setCenterTabs(i_tabpanel);

		return i_tabpanel;
	},

	createEast: function(b_show) {

		var i_self = this;

		var i_panel = Ext.widget("panel", {
			title: ip2.i18n({
				da: "Hjælp",
				en: "Help"
			}),
			width: 300,
			collapsible: true,
			collapsed: true,
			split: true,
			region: "east",
			hidden: !b_show,
			ui: "menu-navigation"
		});

		i_self.setHelpArea(i_panel);

		return i_panel;
	},

	createBottom: function(b_show) {

		var i_panel = Portfolio.util.Message.initGrid({
			title: ip2.i18n({
				da: "Log & beskeder",
				en: "Log & Messages"
			}),
			region: "south",
			height: 400,
			collapsible: true,
			collapsed: true,
			hidden: !b_show,
		});

		return i_panel;
	},

	doOrganizeWindows: function () {

		var i_self = this;
		var i_northArea = i_self.getNorthArea();
		var i_northRegion = i_northArea.getRegion(false, true);

		var i_region = i_self.getRegion();

		var n_x = 10;
		var n_y = i_northRegion.bottom + 10;
		var n_count = 1;
		var o_rows = {};
		var n_index = 0;
		var n_heigthes = 0;
		var n_padding = 10;

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

		var a_filtered = Ext.Array.filter(a_windows, function(i_window) {
			return !i_window.hidden && i_window.$className == "Ext.window.Window";
		});

		Ext.Array.each(a_filtered, function (i_window) {

			if (!i_window.hidden) {
				var o_windowSize = i_window.getSize();

				var o_box = Ext.Object.merge({}, {
					x: n_x,
					y: n_y
				}, o_windowSize);

				var a_rows = o_rows[n_count] || [];

				if ((n_x + o_box.width) > i_region.width) {
					n_heigthes = 0;
					n_index = 0;
					n_x = n_count % 2 ? 40 : 10;
					n_count++;

					a_rows = [];
				}

				a_rows.push({
					box: o_box,
					el: i_window.getEl()
				});

				o_rows[n_count] = a_rows;

				if (n_count > 1) {

					var a_saved = o_rows[n_count - 1];

					if (n_index < a_saved.length) {

						var o_index = a_saved[n_index];
						var b_intersected = false;
						var o_intersected;

						var o_saved = o_index.box;

						n_y = o_saved.y + o_saved.height + n_padding;
						o_box.y = n_y;
						o_box.x = n_x;

						Ext.Array.each(a_saved, function (o_entry) {

							var o_value = o_entry.box;

							// THIS WILL BE FALSE IF WE INTERSECT

							var n_maxX = Math.max(o_box.x, o_value.x);
							var n_maxY = Math.max(o_box.y, o_value.y);

							var n_minWidth = Math.min(o_box.x + o_box.width, o_value.x + o_value.width);
							var n_minHeight = Math.min(o_box.y + o_box.height, o_value.y + o_value.height);

							if (n_minWidth >= n_maxX && n_minHeight >= n_maxY) {
								b_intersected = true;
								o_intersected = o_value;
							}
						});

						if (b_intersected) {
							n_y = o_intersected.y + o_intersected.height + n_padding;
							o_box.y = n_y;
						}
					}
				}

				n_index++;

				i_window.setPosition(n_x, n_y, true);

				n_x += o_windowSize.width + n_padding;
			}
		});
	},

	resizeAndOrganize: function (b_comparing) {

		var i_self = this;

		var i_northArea = i_self.getNorthArea();
		var i_northRegion = i_northArea.getRegion(false, true);

		var i_region = i_self.getRegion();

		var n_top = i_northRegion.bottom;
		var n_regionHeight = i_region.height - i_northRegion.height;

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

		var a_filtered = [];

		if (b_comparing) {
			a_filtered = Ext.Array.filter(a_windows, function(i_window) {
				return i_window.comparing;
			});
		}
		else {
			a_filtered = Ext.Array.filter(a_windows, function (i_window) {
				return !i_window.hidden && i_window.$className == "Ext.window.Window";
			});
		}

		var n_windows = a_filtered.length;

		if (n_windows > 0) {

			var n_padding = 10;

			var n_rows = n_windows > 2 ? 2 : 1;
			var n_cols = n_windows > 2 ? Math.ceil(n_windows / 2) : n_windows;

			var n_calcWidth = (i_region.width - n_padding) - (n_padding * n_cols);
			var n_calcHeight = (n_regionHeight - n_padding) - (n_padding * n_rows);

			var n_count = 0;

			var o_size = {
				width: Math.ceil(n_calcWidth / n_cols),
				height: Math.ceil(n_calcHeight / n_rows)
			};

			var n_x = i_region.left + n_padding;
			var n_y = n_top + n_padding;

			Ext.suspendLayouts();

			Ext.Array.each(a_filtered, function (i_window) {
				i_window.setSize(o_size.width, o_size.height);
			});

			Ext.resumeLayouts(true);

			Ext.Array.each(a_filtered, function (i_window) {

				if (n_windows <= 2) {
					i_window.setPosition(n_x, n_y, true);

					n_x += o_size.width + n_padding;
				}
				else {
					if (n_count < n_cols) {

						i_window.setPosition(n_x, n_y, true);

						n_x += o_size.width + n_padding;
						n_count++;
					}
					else {

						n_count = 0;

						n_x = i_region.left + n_padding;
						n_y += o_size.height + n_padding;

						i_window.setPosition(n_x, n_y, true);

						n_x += o_size.width + n_padding;

					}
				}
			});
		}
	},

	createDesktop: function() {

		var i_self = this;

		var a_desktops = i_self.getDesktops();

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

		var n_count = a_desktops.length;


		var i_desktop = Ext.create("Portfolio.util.Desktop", {
			count: n_count,
			items: a_windows,
			listeners: {
				activate: {
					fn: function (i_desktop, b_pressed) {

						Ext.Array.each(a_desktops, function (i_current) {

							if (!i_current.getIsActive()) {
								i_current.fireEvent("deactivate");
							}
							else {
								i_current.fireEvent("preview");
							}
						});

						i_desktop.setIsActive(b_pressed);
						i_desktop.fireEvent(b_pressed ? "preview" : "depreview");
					}
				},
				preshift: {
					fn: function (i_desktop) {

						Ext.WindowManager.hideAll();

						Ext.Array.each(a_desktops, function(i_current) {

							if (i_current == i_desktop) {
								i_current.fireEvent("preview");
							}
							else {
								i_current.fireEvent("depreview");
							}
						});
					}
				},
				deshift: {
					fn: function(i_desktop) {

						var b_active = false;

						Ext.Array.each(a_desktops, function (i_current) {

							if (!i_current.getIsActive()) {
								i_current.fireEvent("deactivate");
							}
							else {
								i_current.fireEvent("preview");
								b_active = true;
							}
						});

						if (!b_active) {

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

							Ext.Array.each(a_windows, function (i_window) {
								i_window.show();
							});
						}
					}
				},
				destroy: {
					fn: function(i_desktop) {
						Ext.Array.remove(a_desktops, i_desktop);
						i_self.setDesktops(a_desktops);
					}
				}
			}
		});

		a_desktops.push(i_desktop);
		i_self.setDesktops(a_desktops);

		Portfolio.app.fireEvent("desktopadded", i_desktop);
	},

	tabsToWindow: function() {

		var i_self = this;
		var i_centerTabs = i_self.getCenterTabs();

		var a_tabs = i_centerTabs.items.getRange();

		Portfolio.app.fireEvent("toWindow", a_tabs);
	},

	windowsToTab: function () {

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

		Ext.Array.each(a_windows, function(i_window) {

			var o_stateData = i_window.stateData;

			if (o_stateData) {

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

				if (i_panel) {
					i_panel.setTitle(i_window.getTitle());

					Portfolio.app.fireEvent("toTab", i_panel, o_stateData);
					i_window.close();
				}
			}
		});
	},

	addToDesktop: function(i_window, s_managerId) {

		var i_self = this;

		var a_desktops = i_self.getDesktops();

		Ext.Array.each(a_desktops, function(i_desktop) {

			var i_manager = i_desktop.getManager();

			if (i_manager.id == s_managerId) {

				var a_items = i_desktop.getItems();

				a_items.push(i_window);

				i_desktop.addItems(i_window, true);

				i_desktop.setItems(a_items);
			}
		});
	},

	addConstrain: function(o_config) {

		var i_self = this;

		var n_padding = 10;

		var i_northArea = i_self.getNorthArea();
		var i_northRegion = i_northArea.getRegion(false, true);

		var i_region = i_self.getRegion();

		var n_top = i_northRegion.bottom;
		var n_regionHeight = i_region.height - (i_northRegion.height + n_padding * 2);

		var i_constrain = Ext.util.Region.create({});

		Ext.apply(i_constrain, {
			x: i_region.left + n_padding,
			y: n_top + n_padding,
			left: i_region.left + n_padding,
			right: i_region.right - n_padding,
			top: n_top + n_padding,
			bottom: i_region.bottom - n_padding,
			height: n_regionHeight,
			width: i_region.width - (n_padding * 2)
		});

		Ext.apply(o_config, {
			constrainTo: i_constrain,
			maxHeight: n_regionHeight - n_padding
		});

		return o_config;
	}
});
