var i_body = Ext.getBody();

var i_htmlElement = document.documentElement;
i_htmlElement.setAttribute("data-useragent",  Ext.browser.name);
i_htmlElement.setAttribute("data-platform",  Ext.os.name);

//i_body.mask("Loading...");

if (Ext.is.Desktop) {
	Ext.supports.Touch = false;
	Ext.supports.TouchEvents = false;
	Ext.supports.touchScroll = 0;
}

Ext.Loader.setConfig({
	paths: {
		"Ext.ux": "/portfolio/app/ux",
		"Ext.dynapp": "/portfolio/app/dynapp",
		"Ext.registry": "/portfolio/app/registry"
	}
});



function doBoot(n_index) {

	Ext.manifest = Ext.applyIf(Ext.manifest, {
		singleSession: false,
		stateful: false,
		showHelp: true,
		showErrors: false
	});

	Ext.ariaWarn = Ext.emptyFn;

	if (Ext.manifest.singleSession && !sessionStorage.getItem("session")) {

		var s_sysid = Ext.util.Cookies.get("sys_sesid");
		var i_date;

		if (s_sysid) {
			s_sysid = Ext.decode(s_sysid);
			i_date = Ext.Date.parse(s_sysid, "Y-m-d-H.i.s.u");
		}
		else {
			i_date = new Date();
		}
		i_date.setFullYear(i_date.getFullYear() + 10);
		var s_session = Ext.Date.format(i_date, "Y-m-d-H.i.s.u000");
		s_session = "sys_sesid=" + s_session;
		sessionStorage.setItem("session", s_session);
	}

	Ext.define("Portfolio.Application", {
		extend: "Ext.app.Application",

		name: "Portfolio",

		appFolder: "/portfolio/app",

		requires: [
			"Portfolio.util.Handler",
			"Portfolio.state.local.Provider"
		],

		listen: {
			global: {
				login: {
					fn: function (o_result) {

						var i_self = this;
						var o_user = o_result.user || {};

						i_self.showSplashScreen(function (b_splash) {

							Ext.GlobalEvents.fireEvent("logindone");

							Portfolio.login.util.Handler.checkLogin(function (o_result) {

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

								var o_copy = {};

								Ext.Object.each(o_user, function (s_key, value) {
									o_copy[s_key.toUpperCase()] = value;
								});

								i_userRecord.set(o_copy);

								Portfolio.util.Handler.setCurrentUser(o_user);

								Portfolio.util.Handler.setUser(i_userRecord);
								Portfolio.util.Handler.setAccess(i_userRecord.get("ACCESS"));

								Portfolio.util.Handler.getRoles(function () {
									i_self.bootup(i_userRecord);
								});
							});
						});
					}
				},
				logout: {
					fn: function () {
						var i_self = this;

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

						if (i_userRecord && i_userRecord.get(i_userRecord.idProperty)) {
							if (Ext.GlobalEvents.fireEvent("beforelogout")) {
								i_self.logout(true);
							}
						}
					}
				},
				reload: {
					fn: function () {

						var i_self = this;

						if (Ext.GlobalEvents.fireEvent("beforelogout")) {
							i_self.reload();
						}
					}
				},
				applyContextMenu: {
					fn: function () {

						var i_globalWindow = Ext.get(window.document);

						i_globalWindow.events.contextmenu.clearListeners();
					}
				},
				removeContextMenu: {
					fn: function () {

						Ext.get(window.document).on("contextmenu", function (e) {
							e.preventDefault();
							return false;
						});
					}
				},
				updateinfotemplate: {
					fn: function (s_template) {

						Portfolio.app.fireEvent("updateinfotemplate", s_template);
					}
				},
				centerReady: {
					fn: function(i_center) {

						var i_self = this;

						i_self.hideSplashScreen();
					},
					buffer: 1000
				},
				toggleNavigation: {
					fn: function(b_collapse) {

						Portfolio.app.fireEvent("toggleNavigation", b_collapse);
					}
				}
			}
		},

		config: {
			viewport: null,
			stateIndex: n_index
		},

		init: function () {


			Ext.get(window.document).on("contextmenu", function (e) {
				e.preventDefault();
				return false;
			});


			Ext.state.Manager.setProvider(Ext.create("Portfolio.state.local.Provider"));

			var i_model = Portfolio.util.Handler.getModel({
				dmd: "dmd/portfolio.dmd",
				entity: "NAVUSRET00",
				view: "portfolio",
				context: "form"
			});

			var i_record = i_model.create({});

			Portfolio.util.Handler.setUser(i_record);

			Ext.USE_NATIVE_JSON = false;
		},

		launch: function () {

			var i_self = this;

			var i_body = Ext.getBody();

			document.title = ip2.baseconfig.session.preset.text;

			Portfolio.util.Handler.getI18nConfig(function () {

				Portfolio.login.util.Handler.getLoginConfig(function (o_config) {

					Portfolio.login.util.Handler.checkLogin(function (o_result) {

						i_body.unmask();

						var o_currentUser = o_result.currentUser || {
							anonymous: true
						};

						if (o_currentUser.anonymous) {
							i_self.login(false);
						}
						else {

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

							var o_copy = {};

							Ext.Object.each(o_result.currentUser, function (s_key, value) {
								o_copy[s_key.toUpperCase()] = value;
							});

							i_userRecord.set(o_copy);

							Portfolio.util.Handler.setCurrentUser(o_result.currentUser);

							Portfolio.util.Handler.setUser(i_userRecord);
							Portfolio.util.Handler.setAccess(i_userRecord.get("ACCESS"));


							Portfolio.util.Handler.getRoles(function () {
								i_self.bootup(i_userRecord);
							});
						}
					});
				});
			});
		},

		bootup: function (i_userRecord) {

			var i_self = this;

			var s_language = i_userRecord.get("USRLNG") || i_userRecord.get("usrlng") || "en";

			i_userRecord.set("USRLNG", s_language);

			var s_locale = s_language;

			var s_scriptUrl = "";

			if (Ext.versions.ext.isLessThan("6")) {

				s_scriptUrl = "/system/shared/ext5/build/packages/ext-locale/build/ext-locale-" + s_locale + "-debug.js";
			}
			else {

				var s_version = "ext-".concat([
					Ext.getVersion().getMajor(),
					Ext.getVersion().getMinor(),
					Ext.getVersion().getPatch()
				].join("."));

				s_scriptUrl = "/system/shared/" + s_version + "/build/classic/locale/locale-" + s_locale + "-debug.js";
			}

			Ext.Loader.loadScript({
				url: s_scriptUrl,
				onError: function () {

					s_scriptUrl = "";

					if (Ext.versions.ext.isLessThan("6")) {

						s_scriptUrl = "/system/shared/ext5/build/packages/ext-locale/build/ext-locale-en-debug.js";
					}
					else {

						var s_version = "ext-" + Ext.getVersion().version;

						s_scriptUrl = "/system/shared/" + s_version + "/build/classic/locale/locale-"+ s_locale +"-debug.js";
					}

					Ext.Loader.loadScript({
						url: s_scriptUrl,
						onError: function () {

							s_scriptUrl = "";
		
							if (Ext.versions.ext.isLessThan("6")) {
		
								s_scriptUrl = "/system/shared/ext5/build/packages/ext-locale/build/ext-locale-en-debug.js";
							}
							else {
		
								var s_version = "ext-" + Ext.getVersion().version;
		
								s_scriptUrl = "/system/shared/" + s_version + "/build/classic/locale/locale-en-debug.js";
							}
		
							Ext.Loader.loadScript({
								url: s_scriptUrl
							});
						}
					});
				}
			});

			var o_state = Ext.state.Manager.get("portfolio-center-main-" + i_userRecord.get(i_userRecord.idProperty)) || {
				tabs: []
			};

			Ext.GlobalEvents.fireEvent("loggedIn", i_userRecord);

			var i_viewport = Ext.widget("panel", {
				plugins: "viewport",
				layout: "fit"
			});

			var i_main = Ext.widget("portfolio-viewport", {
				centerStateFul: Ext.manifest.stateful,
				showHelp: Ext.manifest.showHelp,
			});

			if (Ext.manifest.showErrors) {
				Portfolio.util.Message.setShowErrors(Ext.manifest.showErrors);
			}

			i_viewport.add(i_main);

			i_self.setViewport(i_viewport);

			if (o_state.tabs.length === 0) {
				Ext.GlobalEvents.fireEvent("centerReady");
			}
		},

		login: function (b_end) {

			var i_self = this;

			i_self.hideSplashScreen();

			var i_login = Ext.widget("portfolio-login", {
				endServerSession: b_end
			});

			i_login.show();
		},

		logout: function (b_end) {

			var i_self = this;

			i_self.showSplashScreen(function (b_splash) {

				i_self.clearUser();

				var i_viewport = i_self.getViewport();

				if (i_viewport) {

					var a_logoutFunctions = Portfolio.util.Handler.getLogoutFunctions();

					Ext.Array.each(a_logoutFunctions, function (f_function) {
						f_function();
					});
				}

				if (i_viewport && !b_splash) {

					i_viewport.animate({
						to: {
							opacity: 0
						},
						listeners: {
							afteranimate: {
								fn: function () {
									i_viewport.removeAll(true);
								}
							}
						}
					}).animate({
						duration: 1,
						to: {
							opacity: 1
						},
						listeners: {
							afteranimate: {
								fn: function () {

									i_self.cleanUp();

									i_self.login(b_end);
								}
							}
						}
					});
				}
				else {

					i_viewport.removeAll(true);

					i_self.cleanUp();

					i_self.login(b_end);
				}
			});
		},

		reload: function () {

			var i_self = this;

			i_self.showSplashScreen(function (b_splash) {

				i_self.clearUser();

				var i_viewport = i_self.getViewport();

				if (i_viewport) {

					var a_logoutFunctions = Portfolio.util.Handler.getLogoutFunctions();

					Ext.Array.each(a_logoutFunctions, function (f_function) {
						f_function();
					});
				}

				Ext.Ajax.request({
					url: "/ip2-services/ip2navigator.aspx",
					params: {
						func: "cleanUp"
					},
					success: function (response, request) {

						if (i_viewport && !b_splash) {

							i_viewport.animate({
								to: {
									opacity: 0
								},
								listeners: {
									afteranimate: {
										fn: function () {
											i_viewport.removeAll(true);
										}
									}
								}
							}).animate({
								duration: 1,
								to: {
									opacity: 1
								},
								listeners: {
									afteranimate: {
										fn: function () {

											i_self.cleanUp();

											document.location.reload();
										}
									}
								}
							});
						}
						else {
							i_self.cleanUp();

							i_self.login(false);
						}

					},
					failure: function (o_error) {

						i_self.cleanUp();

						i_self.login(false);
					}
				});
			});
		},

		cleanUp: function () {

			var i_self = this;

			var i_viewport = i_self.getViewport();

			var i_body = Ext.getBody();

			i_viewport.destroy();

			i_self.setViewport(null);

			i_body.removeCls("x-border-box");
		},

		clearUser: function () {

			var i_model = Portfolio.util.Handler.getModel({
				dmd: "dmd/portfolio.dmd",
				entity: "NAVUSRET00",
				view: "portfolio",
				context: "form"
			});

			var i_record = i_model.create({});

			Portfolio.util.Handler.setCurrentUser(null);
			Portfolio.util.Handler.setUser(i_record);
			Portfolio.util.Handler.setAccess(null);
			Portfolio.util.Handler.navigator.currentUser = Portfolio.util.Handler.navigator.user = null;
			Portfolio.util.Handler.profile.setCache({});
			Portfolio.util.Handler.global.setCache({});
		},

		showSplashScreen: function(f_callback) {

			var i_self = this;

			f_callback = f_callback || Ext.emptyFn;

			var i_loadSplash = Ext.get("loadingSplash");

			if (i_loadSplash) {

				var i_loadtop = Ext.get("loadingSplashTop");
				var i_loadBottom = Ext.get("loadingSplashBottom");
				var i_loadMessage = Ext.get("loadingSplashMessage");

				i_loadtop.on({
					webkitTransitionEnd: {
						fn: function()  {
							i_loadMessage.show();
							f_callback.call(i_self, true);
						},
						single: true
					},
				});

				i_loadtop.removeCls("loading-done");
				i_loadBottom.removeCls("loading-done");
			}
			else {
				f_callback.call(i_self, false);
			}
		},

		hideSplashScreen: function(f_callback) {

			var i_self = this;

			f_callback = f_callback || Ext.emptyFn;

			var i_loadSplash = Ext.get("loadingSplash");

			if (i_loadSplash) {

				var i_loadtop = Ext.get("loadingSplashTop");
				var i_loadBottom = Ext.get("loadingSplashBottom");
				var i_loadMessage = Ext.get("loadingSplashMessage");

				i_loadtop.on({
					webkitTransitionEnd: {
						fn: function () {
							f_callback.call(i_self, true);
						},
						single: true
					},
				});

				i_loadtop.addCls("loading-done");
				i_loadBottom.addCls("loading-done");

				i_loadMessage.hide();
			}
			else {
				f_callback.call(i_self, false);
			}
		}
	});
}

function legacyBoot() {

	var i_window = Ext.getWin();

	var n_counter = parseFloat(localStorage.getItem("portfolio-counter"));

	var n_index = parseFloat(sessionStorage.getItem("portfolio-index"));

	var o_remove = Ext.decode(localStorage.getItem("portfolio-remove"), true) || {};

	var b_reset = localStorage.getItem("portfolio-reset") || "";

	i_window.on({
		storage: {
			fn: function (i_event) {

				i_event = i_event.event;

				if (i_event.key == "portfolio-update") {

					if (i_event.newValue) {

						var value = i_event.newValue;

						var n_update = parseFloat(value);

						if (!isNaN(n_update)) {

							var n_index = parseFloat(sessionStorage.getItem("portfolio-index"));

							if (n_index > 0 && n_index > n_update) {

								n_index--;

								if (window.Portfolio && window.Portfolio.app) {
									Portfolio.app.setStateIndex(n_index);
								}

								sessionStorage.setItem("portfolio-index", n_index);
							}
						}

					}

					localStorage.removeItem("portfolio-update");
				}

				if (i_event.key == "portfolio-close") {

					var b_primary = sessionStorage.getItem("portfolio-primary");

					if (b_primary) {

						i_window.fireEvent("flushRemove");
					}

					localStorage.removeItem("portfolio-close");
				}

				if (i_event.key == "portfolio-change-primary") {

					if (i_event.newValue) {
						i_window.fireEvent("primaryChange");
					}
				}
			}
		},
		unload: {
			fn: function (i_event) {

				var n_closed = parseFloat(sessionStorage.getItem("portfolio-index"));

				var o_remove = Ext.decode(localStorage.getItem("portfolio-remove"), true) || {};

				var a_states = Ext.decode(localStorage.getItem("portfolio-states"), true) || [];

				if (a_states.length > 1) {

					if (!isNaN(n_closed)) {

						o_remove[n_closed] = n_closed;

						var n_remove = Ext.Object.getSize(o_remove);

						if (n_remove > 1) {
							localStorage.setItem("portfolio-reset", 1);
						}

						localStorage.setItem("portfolio-remove", JSON.stringify(o_remove));

						if (n_closed == 0) {
							localStorage.setItem("portfolio-change-primary", new Date());
						}
						else {
							localStorage.setItem("portfolio-close", new Date());
						}
					}
				}
			}
		},
		flushRemove: {
			fn: function () {

				var b_primary = sessionStorage.getItem("portfolio-primary");

				if (b_primary) {

					var o_remove = Ext.decode(localStorage.getItem("portfolio-remove"), true) || {};

					var a_states = Ext.decode(localStorage.getItem("portfolio-states"), true) || [];

					var n_counter = parseFloat(localStorage.getItem("portfolio-counter"));

					var a_keys = Ext.Object.getKeys(o_remove);

					a_keys = a_keys.reverse();

					Ext.Array.each(a_keys, function (s_key) {

						var n_closed = parseFloat(s_key);

						n_counter--;

						if (a_states.length > 1) {

							a_states = Ext.Array.removeAt(a_states, n_closed, 1);

							localStorage.setItem("portfolio-update", JSON.stringify(n_closed));
						}
					});

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

					localStorage.setItem("portfolio-counter", n_counter);

					var s_value = JSON.stringify(a_states);

					localStorage.setItem("portfolio-states", s_value);

					localStorage.removeItem("portfolio-remove");

					localStorage.removeItem("portfolio-reset");
				}
			},
			buffer: 1000
		},
		flushReset: {
			fn: function () {

				var a_states = Ext.decode(localStorage.getItem("portfolio-states"), true) || [];

				var a_indexs = [];

				Ext.Array.each(a_states, function (value, n_index) {
					a_indexs.push(n_index);
				});

				a_indexs = a_indexs.reverse();

				Ext.Array.each(a_indexs, function (n_closed) {

					if (n_closed != 0) {

						a_states = Ext.Array.removeAt(a_states, n_closed, 1);
					}
				});

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

				var s_value = JSON.stringify(a_states);

				localStorage.setItem("portfolio-states", s_value);

				localStorage.removeItem("portfolio-remove");

				localStorage.removeItem("portfolio-reset");
			}
		},
		primaryChange: {
			fn: function () {

				var s_primary = localStorage.getItem("portfolio-change-primary");
				var o_remove = Ext.decode(localStorage.getItem("portfolio-remove"), true) || {};

				if (s_primary && o_remove.hasOwnProperty(0)) {

					var n_index = parseFloat(sessionStorage.getItem("portfolio-index"));

					n_index--;

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

					if (n_index == 0) {

						sessionStorage.setItem("portfolio-primary", 1);

						sessionStorage.setItem("portfolio-index", n_index);

						localStorage.removeItem("portfolio-change-primary");

						if (window.Portfolio && window.Portfolio.app) {
							Portfolio.app.setStateIndex(n_index);
						}

						i_window.fireEvent("flushRemove");
					}
				}
			},
			buffer: 1000
		}
	});

	b_reset = b_reset.length > 0;

	n_counter = isNaN(n_counter) ? -1 : n_counter;

	if (isNaN(n_index) && window.performance.navigation.type != window.performance.navigation.TYPE_RELOAD) {

		if (b_reset) {

			if (o_remove.hasOwnProperty(0)) {
				delete o_remove[0];
			}

			localStorage.setItem("portfolio-remove", JSON.stringify(o_remove));

			i_window.fireEvent("flushReset");

			sessionStorage.setItem("portfolio-index", 0);
			sessionStorage.setItem("portfolio-primary", 1);
			localStorage.setItem("portfolio-counter", 0);

			n_index = 0;
			n_counter = -1;
		}
	}

	if (n_index > -1) {

		o_remove = Ext.decode(localStorage.getItem("portfolio-remove"), true) || {};

		delete o_remove[n_index];

		localStorage.setItem("portfolio-remove", JSON.stringify(o_remove));

		if (n_index === 0) {
			localStorage.removeItem("portfolio-change-primary");
		}
	}

	localStorage.removeItem("portfolio-update");

	if (isNaN(n_index)) {

		n_index = n_counter + 1;

		var a_states = Ext.decode(localStorage.getItem("portfolio-states"), true) || [];

		if (n_index > a_states.length) {
			n_index = a_states.length;

			n_index = n_index < 0 ? 0 : n_index;
		}

		if (!a_states[n_index]) {

			a_states[n_index] = {};

			var s_value = JSON.stringify(a_states);
			localStorage.setItem("portfolio-states", s_value);
		}

		sessionStorage.setItem("portfolio-index", n_index);
		localStorage.setItem("portfolio-counter", n_index);

		if (n_index === 0) {

			sessionStorage.setItem("portfolio-primary", 1);
		}
	}

	doBoot.call(this, n_index);
}

if ("serviceWorker" in navigator && navigator.serviceWorker) {

	navigator.serviceWorker.register("/portfolio/service-worker.js", { scope: "/" }).then(function () {
		return navigator.serviceWorker.ready;
	}).then(function (reg) {

		var s_currentID = sessionStorage.getItem("portfolio-index");

		navigator.serviceWorker.addEventListener("message", function (i_event) {

			var o_result = i_event.data || {};
			var s_id = o_result.buid;
			var a_remove = o_result.remove || [];

			if (o_result.action == "updatetab") {

				var n_count = o_result.count;

				if (n_count <= 1) {

					var o_oldStates = Ext.decode(localStorage.getItem("portfolio-states"), true) || {};

					var o_state = Ext.Object.getValues(o_oldStates)[0] || {};

					var o_newStates = {};

					o_newStates[s_id] = o_state;

					var s_value = JSON.stringify(o_newStates);

					localStorage.setItem("portfolio-states", s_value);
				}
				else {

					var o_states = Ext.decode(localStorage.getItem("portfolio-states"), true) || {};

					Ext.Array.each(a_remove, function (s_guid) {
						delete o_states[s_guid];
					});

					var s_value = JSON.stringify(o_states);

					localStorage.setItem("portfolio-states", s_value);
				}

				sessionStorage.setItem("portfolio-index", s_id);
				doBoot.call(this, s_id);
			}
		});

		if (window.performance.navigation.TYPE_RELOAD == window.performance.navigation.type) {
			navigator.serviceWorker.controller.postMessage({
				action: "reloadtab",
				id: s_currentID
			});
		}
		else {
			navigator.serviceWorker.controller.postMessage({
				action: "newtab",
				id: s_currentID
			});
		}


	}).catch(function (err) {
		legacyBoot.call(this);
	});
}
else {
	legacyBoot.call(this);
}
