Ext.define("Portfolio.menu.view.Favorite", {

	xtype: "portfolio-menu-favorite",

	extend: "Ext.panel.Panel",

	config: {
		systemId: "",
		tree: null
	},

	layout: "anchor",
	floatable: false,

	ui: "menu-navigation",

	initComponent: function() {

		var i_self = this;

		i_self.callParent();

		var s_id = ip2.baseconfig.session.preset.origin;

		i_self.setSystemId(s_id);

		var o_global = Portfolio.util.Handler.global.get(s_id + ".favorites-settings", {
		});

		var o_settings = Portfolio.util.Handler.profile.get(s_id + ".favorites-settings", {
		});

		var s_title = ip2.i18n(o_global.title || {
			da: "Favoritter",
			en: "Favorites"
		});

		i_self.setTitle(s_title);

		i_self.add(i_self.createTree());

		i_self.initKeyEvents(o_global);
	},

	createTree: function() {

		var i_self = this;

		var s_id = i_self.getSystemId();

		var i_store = Ext.create("Ext.data.TreeStore", {
			model: "treeMenu",
			proxy: {
				type: "memory"
			},
			data: []
		});

		var i_tree = Ext.create("Ext.tree.TreePanel", {
			useArrows: true,
			border: false,
			animate: false,
			rootVisible: false,
			anchor: "100% 100%",
			frame: false,
			store: i_store,
			viewConfig: {
				plugins: {
					ptype: "treeviewdragdrop",
					enableDrag: true,
					enableDrop: true,
					dropGroup: "tree2fav",
					dragGroup: "tree2fav",
					allowContainerDrops: true,
					appendOnly: false,
					dropZone: {

						isValidDropPoint: function(i_node, s_position, i_dragZone, i_event, o_data) {

							var i_view = this;
							var a_records = o_data.records;
							var b_allowed = true;

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

							if (b_allowed && i_view.id != o_data.view.id) {

								var o_favorites = Portfolio.util.Handler.profile.get(s_id + ".favorites", {
									nodes: []
								});

								Ext.Array.each(o_favorites.nodes, function(o_record) {
									Ext.Array.each(a_records, function(i_record) {
										if (i_record.get("id") == o_record.id) {
											b_allowed = false;
										}
									});
								});
							}

							return b_allowed;
						},

						onContainerOver: function(i_target, i_event, o_data) {

							var i_dragdrop = this;
							var a_records = o_data.records;
							var b_allowed = true;

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

							if (b_allowed && i_dragdrop.id != o_data.view.id) {

								var o_favorites = Portfolio.util.Handler.profile.get(s_id + ".favorites", {
									nodes: []
								});

								Ext.Array.each(o_favorites.nodes, function(o_record) {
									Ext.Array.each(a_records, function(i_record) {
										if (i_record.get("id") == o_record.id) {
											b_allowed = false;
										}
									});
								});
							}
							return b_allowed ? i_dragdrop.dropAllowed : i_event.getTarget("." + i_dragdrop.indicatorCls) ? i_dragdrop.currentCls : i_dragdrop.dropNotAllowed;
						},

						onContainerDrop: function(i_dragZone, i_event, o_data) {

							var i_dragdrop = this;
							var a_records = o_data.records;
							var b_allowed = true;

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

							if (b_allowed && i_dragdrop.id != o_data.view.id) {

								var o_favorites = Portfolio.util.Handler.profile.get(s_id + ".favorites", {
									nodes: []
								});

								Ext.Array.each(o_favorites.nodes, function(o_record) {
									Ext.Array.each(a_records, function(i_record) {
										if (i_record.get("id") == o_record.id) {
											b_allowed = false;
										}
									});
								});
							}

							if (i_dragdrop.allowContainerDrops && b_allowed) {
								i_dragdrop.valid = true;
								i_dragdrop.currentPosition = "append";
								i_dragdrop.overRecord = this.view.store.getRoot();
								i_dragdrop.onNodeDrop(i_dragdrop.overRecord, i_dragZone, i_event, o_data);
							}
							return b_allowed;
						}
					}
				},
				listeners: {
					beforedrop: {
						fn: function(i_node, o_data, i_overModel, s_dropPosition, f_dropHandler, i_event) {

							var i_view = this;

							var o_favorites = Portfolio.util.Handler.profile.get(s_id + ".favorites", {
								nodes: []
							});

							var b_found = false;
							var a_records = o_data.records;

							o_data.copy = true;

							Ext.Array.each(o_favorites.nodes, function(o_record) {

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

									if (i_record.get("id") == o_record.id) {
										b_found = true;
										o_data.copy = false;
										return false;
									}
								});

								if (b_found) {
									return false;
								}
							});
						}
					},
					drop: {
						fn: function(i_node, o_data, i_overModel, s_posistion) {

							var a_records = o_data.records;
							i_self.doSave(a_records, i_overModel, s_posistion);
						}
					}
				}
			},
			listeners: {
				beforeload: {
					fn: function(i_store, i_operation) {

						var i_node = i_operation.node;

						if (i_node.get("type")) {

							var i_proxy = i_store.getProxy();
							var o_extraParams = i_proxy.getExtraParams();

							Ext.apply(o_extraParams, {
								url: "/ip2-services/ip2navigator.aspx?func=getAccordionMenu",
								type: i_node.get("type"),
								system: i_node.get("system"),
								applicationGroup: i_node.get("applicationGroup"),
								application: i_node.get("application")
							});
						}
					}
				},
				itemcontextmenu: {
					fn: function(i_tree, i_node, i_element, n_index, i_event) {

						i_event.stopEvent();

						if (!i_node.isRoot()) {

							var a_items = [];

							var i_open = Ext.widget("menuitem", {
								iconCls: "pf-gearwheel",
								text: ip2.i18n({
									da: "Åben ny",
									en: "Open new"
								}),
								handler: function(i_button) {

									i_node.set("force", true);

									Portfolio.app.fireEvent("startapplication", i_node);

									i_node.set("force", null);
								}
							});

							var i_delete = Ext.widget("menuitem", {
								iconCls: "pf-delete",
								text: ip2.i18n({
									da: "Slet",
									en: "Delete"
								}),
								handler: function(i_button) {

									if (i_node) {

										var i_parent = i_node.parentNode;

										i_self.doDelete(i_node, function(a_nodes) {

											i_parent.removeAll(false);

											if (a_nodes.length) {

												i_parent.appendChild(a_nodes);
												i_parent.expand();
											}
										});
									}
								}
							});

							a_items.push(i_open);
							a_items.push(i_delete);

							var i_menu = Ext.widget("menu", {
								items: a_items
							});

							i_menu.showAt(i_event.getXY());
						}
					}
				},
				itemclick: {
					fn: function (i_view, i_node, i_element, n_index, i_event) {

						if (!i_node.isRoot()) {
							Portfolio.app.fireEvent("startapplication", i_node);
						}
					}
				}
			}
		});

		var i_root = i_tree.getRootNode();
		i_root.appendChild(i_self.getData());

		i_self.setTree(i_tree);

		return i_tree;
	},

	doSave: function(a_records, i_overModel, s_posistion) {

		var i_self = this;
		var s_id = i_self.getSystemId();

		var o_favorites = Portfolio.util.Handler.profile.get(s_id + ".favorites", {
			nodes: []
		});

		var b_found = false;
		var n_index = 0;
		var o_record;

		if (i_overModel.isRoot()) {

			Ext.Array.each(o_favorites.nodes, function(o_record) {

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

					if (i_record.get("id") == o_record.id) {
						b_found = true;
						return false;
					}
					n_index++;
				});

				if (b_found) {
					return false;
				}
			});

			if (b_found) {
				o_record = o_favorites.nodes.splice(n_index, 1)[0];
				o_favorites.nodes.push(o_record);
			}
			else {
				Ext.Array.each(a_records, function(i_record) {
					var o_record = i_record.getData();
					o_favorites.nodes.push(o_record);
				});
			}
		}
		else {

			var n_recordIndex = 0;
			var b_recordFound = false;

			Ext.Array.each(o_favorites.nodes, function(o_record) {
				if (i_overModel.get("id") == o_record.id) {
					b_found = true;
					return false;
				}
				n_index++;
			});

			Ext.Array.each(o_favorites.nodes, function(o_record) {
				Ext.Array.each(a_records, function(i_record) {
					if (i_record.get("id") == o_record.id) {
						b_recordFound = true;
						return false;
					}
					n_recordIndex++;
				});

				if (b_recordFound) {
					return false;
				}
			});

			if (!b_found && !b_recordFound) {
				Ext.Array.each(a_records, function(i_record) {
					var o_data = i_record.data;
					o_favorites.nodes.push(o_data);
				});
			}
			else {
				if (s_posistion == "after") {

					if (b_recordFound) {

						n_insert = n_index;
						o_record = o_favorites.nodes.splice(n_recordIndex, 1)[0];
						o_favorites.nodes.splice(n_insert, 0, o_record);
					}
					else {

						n_insert = n_index;

						Ext.Array.each(a_records, function(i_record) {
							var o_record = i_record.data;
							o_favorites.nodes.splice(n_insert, 0, o_record);
						});
					}
				}
				else {
					if (n_index !== 0) {

						if (b_recordFound) {

							n_insert = n_index;
							o_record = o_favorites.nodes.splice(n_recordIndex, 1)[0];
							o_favorites.nodes.splice(n_insert, 0, o_record);
						}
						else {

							n_insert = n_index;

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

								var o_record = i_record.data;
								o_favorites.nodes.splice(n_insert, 0, o_record);
							});
						}
					}
					else {

						if (b_recordFound) {

							o_record = o_favorites.nodes.splice(n_recordIndex, 1)[0];
							o_favorites.nodes.unshift(o_record);
						}
						else {

							Ext.Array.each(a_records, function(i_record) {
								var o_record = i_record.data;
								o_favorites.nodes.unshift(o_record);
							});
						}
					}
				}
			}
		}

		Portfolio.util.Handler.profile.set(s_id + ".favorites", Ext.encode(o_favorites));

		return o_favorites;
	},

	doDelete: function(i_node, f_callback) {

		var i_self = this;
		var s_id = i_self.getSystemId();

		var o_favorites = Portfolio.util.Handler.profile.get(s_id + ".favorites", {
			nodes: [],
			title: "",
			binding: {
				alt: false,
				ctrl: false,
				shift: false,
				key: null
			}
		});

		var b_found = false;
		var n_index = 0;

		Ext.Array.each(o_favorites.nodes, function(o_record) {
			if (o_record.id == i_node.get("id")) {
				b_found = true;
				return false;
			}
			n_index++;
		});

		if (b_found) {
			o_favorites.nodes.splice(n_index, 1);
		}

		Portfolio.util.Handler.profile.set(s_id + ".favorites", Ext.encode(o_favorites), function() {
			var a_nodes = i_self.getData();
			f_callback(a_nodes);
		});
	},

	getData: function() {

		var i_self = this;

		var s_id = i_self.getSystemId();

		var o_favorites = Portfolio.util.Handler.profile.get(s_id + ".favorites", {
			nodes: []
		});

		Ext.applyIf(o_favorites, {
			nodes: []
		});

		return o_favorites.nodes;
	},

	getApplication: function(i_node, b_force) {

		var i_model = ip2.getModel({
			dmd: "dmd/portfolio.dmd",
			entity: "NAVMNUET00",
			context: "form",
			view: "portfolio"
		});

		b_force = b_force || false;

		Ext.Ajax.request({
			url: "/ip2-services/ip2dmdProxy.aspx",
			params: {
				action: "getRow",
				context: "form",
				dmdFile: "dmd/portfolio.dmd",
				uiName: "portfolio",
				model: "NAVMNUET00",
				where: i_model.idProperty + " = " + i_node.get("id")
			},
			success: function (i_response) {

				var o_result = Ext.decode(i_response.responseText, true) || {
					success: false,
					rows: [{}]
				};

				if (!o_result.rows) {
					o_result.rows = [{}];
				}

				var o_data = o_result.rows[0];

				var i_created = i_model.create(o_data);

				var o_values = Ext.decode(i_created.get("MNUPROP", true));

				if (o_values) {
					o_values.force = b_force;
					Portfolio.util.Handler.addTab(o_values);
				}
			},
			failure: function() {}
		});
	},

	initKeyEvents: function(o_settings) {

		var i_self = this;

		var i_tree = i_self.getTree();
		var i_root = i_tree.getRootNode();

		var o_binding = o_settings.binding || {};

		if (o_binding.keyCode) {

			var i_keyMap = Ext.create("Ext.util.KeyMap", {
				target: Ext.getDoc().el,
				binding: [
					{
						alt: o_binding.alt,
						ctrl: o_binding.ctrl,
						shift: o_binding.shift,
						key: o_binding.keyCode,
						handler: function(n_key, i_event) {

							i_event.stopEvent();

							var i_store = i_tree.getStore();

							if (!i_store.isLoaded()) {

								i_store.on({
									load: {
										fn: function(i_store, a_records) {

											var i_select = i_root.findChildBy(function(i_record) {
												return !i_record.isRoot();
											}, i_tree, true);

											if (i_select) {
												i_tree.view.select(i_select, false, true);
												i_tree.view.focusNode(i_select, 10);
											}
										},
										singel: true
									}
								});
							}
							else {
								var i_select = i_root.findChildBy(function(i_record) {
									return !i_record.isRoot();
								}, i_tree, true);

								if (i_select) {
									i_tree.view.select(i_select, false, true);
									i_tree.view.focusNode(i_select, 10);
								}
							}
						}
					}
				]
			});
		}
	}
});
