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

	xtype: "portfolio-menu-system",

	extend: "Ext.panel.Panel",

	requires: [
		"Portfolio.menu.model.System"
	],

	config: {
		system: null,
		tree: null,
		keyBinding: null
	},

	tools: [{
		type: "refresh",
		handler: function (i_event, i_element, i_header) {

			var i_panel = i_header.up("portfolio-menu-system");
			i_panel.doReload();
		}
	}],

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

				if (!i_panel.collapsed) {
					i_panel.doReload();
				}
			},
			single: true
		},
		beforeexpand: {
			fn: function(i_panel) {

				var i_tree = i_panel.getTree();
				var i_store = i_tree.getStore();

				if (!i_store.isLoaded()) {
					i_panel.doReload();
				}
			},
			single: true
		},
		shortcut: {
			fn: function() {
				var i_self = this;
				i_self.doShortCut();
			}
		}
	},

	ui: "menu-navigation",

	initComponent: function() {

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

		i_self.add(i_self.createTree());

		i_self.enableBubble("startapplication");

		return i_self;
	},

	createTree: function () {

		var i_self = this;
		var i_user = Portfolio.util.Handler.getUser();
		var i_store = i_self.createStore();

		var o_config = i_self.getSystem() || {};

		var i_tree = Ext.widget("treepanel", {
			useArrows: true,
			singleExpand: false,
			border: false,
			animate: false,
			rootVisible: false,
			store: i_store,
			viewConfig: {
				plugins: {
					copy: true,
					ptype: "treeviewdragdrop",
					enableDrag: true,
					enableDrop: false,
					dragGroup: "tree2fav"
				}
			},
			listeners: {
				load: {
					fn: function(i_store, a_records) {

						var i_tree = i_self.getTree();

						i_tree.setLoading(false);

						var i_root = i_tree.getRootNode();

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

						var i_select;

						var a_bindings = [];

						if (o_extraParams.hasOwnProperty("search")) {

							if (o_extraParams.search) {

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

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

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

							if (i_record.isLeaf()) {

								var o_properties = i_record.get("properties") || {};
								var o_binding = o_properties.binding;
								var b_execute = i_record.get("execute") || false;

								if (o_binding && o_binding.keyCode) {
									o_binding.record = i_record;

									a_bindings.push(o_binding);
								}

								if (b_execute) {
									i_self.fireEvent("startapplication", i_self, i_record);
								}

							}
						});

						i_self.addBindings(a_bindings);
					}
				},
				beforeload: {
					fn: function(i_store, i_operation) {

						var i_tree = i_self.getTree();
						i_tree.setLoading();

						var n_system = o_config.system || o_config.id;

						var i_node = i_operation.node;
						var i_proxy = i_store.getProxy();
						var o_extraParams = i_proxy.getExtraParams();

						delete o_extraParams.system;

						if (!i_node.isRoot()) {
							delete o_extraParams.search;
						}

						var s_loader = i_node.get("url");

						if (i_node.isRoot()) {
							s_loader = o_config.url;
						}

						if (!s_loader) {
							i_proxy.setUrl("/ip2-services/ip2transaction.aspx");

							Ext.apply(o_extraParams, {
								action: "ip2NavProxy.listMenuNodes",
								language: i_user.get("USRLNG") || "en",
								userToken: i_user.get("USRUSRTKN")
							});
							if (i_node.isRoot()) {
								Ext.apply(o_extraParams, {
									system: n_system
								});
							}
						}
						else {

							Ext.apply(o_extraParams, {
								system: n_system,
								language: i_user.get("USRLNG") || "en",
								userToken: i_user.get("USRUSRTKN")
							});

							i_proxy.setUrl(s_loader);
						}
					}
				},
				itemclick: {
					fn: function(i_view, i_record) {

						if (i_record.isLeaf()) {
							i_self.fireEvent("startapplication", i_self, i_record);
						}
						else {
							i_record.expand();
						}
					}
				},
				itemcontextmenu: {
					fn: function(i_tree, i_node, i_element, n_index, i_event) {

						var i_menu;
						var a_items = [];

						i_event.preventDefault();

						var a_xy = i_event.getXY();

						if (!i_node.isLeaf()) {

							var i_refresh = Ext.widget("menuitem", {
								iconCls: "pf-refresh",
								text: ip2.i18n({
									da: "Oprisk",
									en: "Refresh"
								}),
								parent: i_node,
								handler: function(button) {

									if (i_node) {

										if (i_node.get("loaded")) {
											i_node.collapse();
											i_node.removeAll(false);

											i_store.load({
												node: i_node,
												callback: function(a_records, i_store) {
													i_node.expand();
												}
											});
										}
										else {
											i_node.expand();
										}
									}
								}
							});

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

									i_node.set("force", true);

									i_self.fireEvent("startapplication", i_self, i_node);

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

							a_items.push(i_open);
						}

						if (a_items.length > 0) {
							i_menu = Ext.widget("menu", {
								items: a_items
							});
							i_menu.showAt(a_xy[0], a_xy[1]);
						}
					}
				}
			}
		});

		i_self.setTree(i_tree);

		if (o_config.searchable) {

			var i_toolbar = Ext.widget("toolbar", {
				dock: "top",
				layout: "fit",
				items: [
					{
						xtype: "searchfield",
						store: i_store,
						allowSort: false
					}
				]
			});

			i_tree.addDocked(i_toolbar);
		}

		return i_tree;
	},

	createStore: function() {

		var i_self = this;

		var i_store = Ext.create("Ext.data.TreeStore", {
			autoLoad: false,
			model: "Portfolio.menu.model.System",
			proxy: {
				type: "ajax",
				url: "/ip2-services/ip2transaction.aspx",
				paramsAsJson: true,
				reader: {
					type: "json",
					totalProperty: "totalRows"
				},
				timeout: (( 5 * 60) * 1000),
				actionMethods: {
					read: "POST"
				}
			},
			listeners: {
				load: {
					fn: function(i_store, a_records) {

						var i_tree = i_self.getTree();
						var i_view = i_tree.getView();

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

							var s_text = "";

							var title = i_node.get("title") || i_node.get("text");

							if (Ext.isObject(title)) {
								s_text = ip2.i18n(title);
							}
							else {
								s_text = title;
							}

							i_node.set("text", s_text);

							var s_icon = i_node.get("icon");

							if (s_icon === "null") {
								i_node.set("icon", null);
							}

							if (i_node.parentNode && i_node.parentNode.isRoot()) {
								var o_data = i_node.getData();

								if (!o_data.hasOwnProperty("collapsed")) {
									if (!i_node.isLeaf()) {
										if (!i_node.get("expanded")) {
											i_node.expand();
										}
										else {
											i_node.collapse();
											i_node.expand();
										}
									}
								}
								else {
									if (!i_node.get("collapsed")) {
										if (!i_node.get("expanded")) {
											i_node.expand();
										}
										else {
											i_node.collapse();
											i_node.expand();
										}
									}
								}
							}

							i_node.commit();
						});

						i_view.refresh();
					}
				}
			}
		});

		return i_store;
	},

	doReload: function() {

		var i_self = this;

		var i_keyBinding = i_self.getKeyBinding();

		if (i_keyBinding) {

			var a_bindings = i_keyBinding.bindings;

			Ext.Array.each(a_bindings, function(i_binding) {
				i_keyBinding.removeBinding(i_binding);
			});
		}

		var i_tree = i_self.getTree();

		var i_store = i_tree.getStore();

		var i_root = i_tree.getRootNode();

		i_root.collapse();
		i_root.removeAll(false);

		i_store.load({
			node: i_root,
			callback: function(a_records, i_store) {
				i_root.expand();
			}
		});
	},

	addBindings: function(a_bindings) {

		var i_self = this;

		var i_keyBinding = i_self.getKeyBinding();

		if (i_keyBinding) {

			var a_processed = i_keyBinding.bindings || [];

			var a_add = [];

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

				var i_found = Ext.Array.findBy(a_processed, function(i_binding) {

					var i_return;
					if (o_config.keyCode == i_binding.key) {

						if (o_config.alt == i_binding.altKey) {

							if (o_config.ctrl == i_binding.ctrlKey) {

								if (o_config.shift == i_binding.shift) {

									i_return = i_binding;
								}
							}
						}
					}
					return i_return;
				});

				if (!i_found) {
					a_add.push(o_config);
				}
			});

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

				var i_record = o_config.record;
				delete o_config.record;

				var o_binding = {
					alt: o_config.alt,
					ctrl: o_config.ctrl,
					key: o_config.keyCode,
					handler: function(n_key, i_event) {

						i_event.stopEvent();
						i_self.fireEvent("startapplication", i_self, i_record);
					}
				};

				i_keyBinding.addBinding(o_binding);
			});
		}
		else {

			var a_result = [];

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

				var i_record = o_config.record;

				delete o_config.record;

				var o_binding = {
					alt: o_config.alt,
					ctrl: o_config.ctrl,
					key: o_config.keyCode,
					handler: function(n_key, i_event) {

						i_event.stopEvent();

						i_self.fireEvent("startapplication", i_self, i_record);
					}
				};

				a_result.push(o_binding);
			});

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

			i_self.setKeyBinding(i_keyMap);
		}
	},

	doShortCut: function() {

		var i_self = this;

		var i_tree = i_self.getTree();

		if (i_tree) {

			var i_root = i_tree.getRootNode();
			var i_store = i_tree.getStore();

			var i_searchfield = i_tree.down("searchfield");

			if (i_searchfield) {

				i_searchfield.focus(10, true);
			}
			else {
				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);
					}
				}
			}
		}
	}
});
