dojo.provide("UI.Widgets.Hud");

/**
 * This is a singleton.  Please see below.
 */
dojo.declare("UI.Widgets._Hud", UI.Base, {
	constructor: function() {
		this.wdgActivation = false;
		this.cntUserInfo   = dojo.byId("layout-userinfo");
		this.btnLaunchers  = dojo.query(".wdg-game-client-launch");
		this.xdcomm        = null;

		dojo.query(".wdg-hud-logout").connect("click", this, function(event) {
			dojo.stopEvent(event);
			this.logoutAndRedirect();
		});

		if ( PPP.data.user.isLoggedIn ) {
			this.login();
		} else {
			this.hideUserStatus();

			this.btnLaunchers.connect("click", function(event) {
				dojo.stopEvent(event);

				if ( PPP.config.global.is_hub_closed ) {
					UI.Widgets.Hud.getMaintenanceDialog(PPP.config.global.msg_hub_closed).open();
				} else {
					window.location = PPP.config.paths.self + "login";
				}
			});
		}

		// If the just been activated
		if ( UI.Util.Cookie.get("isActivated") ) {
			try {
				this.wdgActivation = true;
				new UI.Widgets.User.Activation(function(wdgActivation) {
					// This must be async. No, I haven't take the time to find out why.
					setTimeout(dojo.hitch(wdgActivation, "activationComplete"), 1);
					UI.Util.Cookie.erase("isActivated");
				});
			} catch (e) {
				// Activation module may not be included in this environment
			}
		}

		if ( PPP.isFramed ) {
			var btnHome = dojo.byId("layout-nav-home");
			if ( btnHome ) {
				btnHome.href = this.getHomePage();
			}

			dojo.query("a").forEach(function(node) {
				if ( node.getAttribute("rel") == "nav" && node.id != "layout-nav-home" ) {
					node.target = "_blank";
				} else {
					node.href += (node.href.indexOf("?") == -1 ? "?framed" : "&framed");
				}
			});


			// Initialize cross-domain communicator
			this.xdcomm               = document.createElement("iframe");
			this.xdcomm.style.display = "none";
			this.xdcomm.srcRoot       = PPP.config.paths.xdcomm;
			document.body.appendChild(this.xdcomm);
		}
	},

	login: function() {
		dojo.addClass(document.body, "loggedin");

		// Each this.btnLaunchers may contain a `rel` attribute to explicitly set the domain
		if ( PPP.data.user.isLegacy ) {
			dojo.forEach(this.btnLaunchers, function(node) {
				if ( PPP.config.global.is_registration_closed ) {
					UI.Widgets.Hud.getMaintenanceDialog(PPP.config.global.msg_registration_closed).open();
					return;
				}

				node.href  = PPP.config.paths.self + "register";
				node.title = "Complete your registration to play";
			});
		} else {
			dojo.forEach(this.btnLaunchers, function(node) {
				if ( PPP.config.global.is_hub_closed ) {
					UI.Widgets.Hud.getMaintenanceDialog(PPP.config.global.msg_hub_closed).open();
					return;
				}

				node.href  = PPP.config.paths.self + "games/park";
				node.title = "Play Now!";
			});
		}

		// Populate username fields
		dojo.query(".lbl-username").forEach(function(node) {
			node.innerHTML = PPP.data.user.displayName;
		});

		// Show the container
		if ( this.cntUserInfo ) {
			this.cntUserInfo.style.display = "block";
		}

		try {
			if ( !PPP.data.user.isActivated && !this.wdgActivation ) {
				new UI.Widgets.User.Activation(function(wdgActivation) {
					var cntActivationPrompt = dojo.byId("prompt-activation");

					// Configure activation widget events
					wdgActivation.addEventListener("activationSuccess", function() {
							cntActivationPrompt.style.display = "none";
						})
						.dialog.addOpenTriggers(dojo.byId("btn-activate"));

					// Show activation prompt
					cntActivationPrompt.style.display = "block";
				});
				this.wdgActivation = true;
			}
		} catch (e) {
			// Activation module may not be included depending in this environment
		}

		dojo.addClass(dojo.body(), "loggedin");
	},

	hideUserStatus: function() {
		if ( this.cntUserInfo ) {
			this.cntUserInfo.style.display = "none";
		}

		dojo.removeClass(dojo.body(), "loggedin");
	},

	logoutAndRedirect: function(redirect) {
		this.nchubLogout();
		setTimeout(function() {
			window.location = redirect || (PPP.config.paths.self + "services/auth/logout?clearPreferences=1&redirect=1");
		}, 100);
	},

	logout: function() {
		// Log out of associated NC hub
		this.nchubLogout();
		new Image().src = PPP.config.paths.self + "services/auth/logout?clearPreferences=1";
	},

	nchubLogout: function() {
		if ( PPP.config.paths.nchub.logout.indexOf ) {
			new Image().src = PPP.config.paths.nchub.logout;
		} else {
			new Image().src = PPP.config.paths.nchub.logout.normal;
			new Image().src = PPP.config.paths.nchub.logout.secure;
		}
	},

	clientLogout: function() {
		this.nchubLogout();
		setTimeout(dojo.hitch(this, function() {
			window.location = PPP.config.paths.self + "services/auth/logout?redirect=" + (PPP.isFramed ? this.getHomePage(true) : "1");
		}), 200);
	},

	resizeFrame: function(height) {
		if ( !height ) {
			var p = dojo.position(dojo.byId("layout-footer"));
			height = p.y + p.h;
		}

		this.external("setFrameHeight", height);
	},

	external: function(method, args) {
		if ( PPP.isFramed ) {
			this.xdcomm.src = this.xdcomm.srcRoot + "?method=" + method + "&args=" + window.escape(dojo.toJson(args));
		}
	},

	getHomePage: function(relativePath) {
		var url = PPP.isFramed
			? PPP.config.paths.self + "embed/" + (UI.Util.Cookie.get("embed_referrer") || "")
			: PPP.config.paths.self;

		return relativePath
			? url.replace(/.*\.com\//i, "/")
			: url;
	},

	setMaintenanceRedirect: function(flag, message) {
		UI.Util.Cookie.set("delayed_message", {flag: flag, message: message});
		window.location = this.getHomePage();
	},

	getMaintenanceDialog: function(content) {
		return UI.Dialog.Generic.create(
			{template: {template: "maintenance"}},
			function(dlg) {
				dojo.query("button", dlg.getContent()).connect("click", function(event) {
					dojo.stopEvent(event);
					this.blur();
					dlg.close();
				});
			},
			function(dlg) {
				dojo.query(".notification", dlg.getContent())[0].innerHTML = content;
			}
		).useModal();
	},

	getNoCookieDialog: (function() {
		var recheckOnClose = false;

		return function(recheck) {
			recheckOnClose = !!recheck;

			return UI.Dialog.Generic.create({template:{template: "no-cookies"}}, function(dlg) {
				dojo.query(".btn-okay", dlg.getContent()).connect("click", function(event) {
					dojo.stopEvent(event);
					this.blur();
					dlg.close();
				});

				dlg.addEventListener("beforeclose", function() {
					return !recheckOnClose || UI.Util.Cookie.test();
				}, true);
			}).useModal();
		};
	}())
});

dojo.addOnLoad(function() {
	UI.Widgets.Hud = new UI.Widgets._Hud();

	// If the page is framed, the homepage is the embed lander
	if ( PPP.isFramed && window.location.pathname == "/" ) {
		window.location = UI.Widgets.Hud.getHomePage();
	} else {
		UI.Widgets.Hud.resizeFrame();
	}

	var delayedMessage = UI.Util.Cookie.get("delayed_message");

	if ( delayedMessage ) {
		if ( PPP.config.global[delayedMessage.flag] ) {
			UI.Widgets.Hud.getMaintenanceDialog(PPP.config.global[delayedMessage.message]).open();
			UI.Util.Cookie.erase("delayed_message");
		}
	}
});


