/*
 * Spreed WebRTC.
 * Copyright (C) 2013-2014 struktur AG
 *
 * This file is part of Spreed WebRTC.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
 * This plugin is part of the Spreed WebApp plugin by Kopano.
 * It is hooked into the spreed application, after configuration
 * in server.conf
 *
 */

define(['angular'], function (angular) {

	var version = "1";

	/**
	 * Tells whether Spreed is loaded in an iframe
	 */
	var spreedLoadedInIFrame = window !== window.top;

	return {
		initialize: function (app, launcher) {
			//console.log("XXX initialize plugin");
			app.controller("UsersettingsController", ["$scope", "$element", "$window", "$timeout", "webmeetingsApi", "appData", function($scope, $element, $window, $timeout, webmeetingsApi, appData) {

				//console.log("XXX Plugin UsersettingsController", $element[0]);
				$scope.withUsersRegistration = false;
				$scope.withUsersForget = true;

				var namePrefix = "spreedme-account-"+appData.id+"-";
				var popup = null;

				angular.element($window).on("unload", function() {
				});

				this.forgetUserid = function() {
					//console.log("XXX forgetUserid");
					webmeetingsApi.requestLogout();
				};

			}]);
		},
		/**
		 *
		 * @param modules
		 */
		module: function (modules) {
			//console.log("XXX module plugin");

			/**
			 * Reference to the 'take picture button' in the settings panel
			 */
			var takePictureButton = null;

			/**
			 * Reference to the 'Your Name' textfield in settings panel
			 */
			var yourNameTextfield = null;

			/**
			 * Reference to the 'Default Room' textfield in settings panel
			 */
			var defaultRoomTextfieldFormGroup = null;

			/**
			 * Reference to the Sound settings section in settings panel
			 */
			var yourNotificationSettingsIncomingMessages = null;
			var yourNotificationSettingsIncomingCall = null;
			var yourNotificationSettingsRoomJoinLeave = null;

			/**
			 * Plugin main module
			 */
			var module = angular.module('spreedWebRTCPlugin', []).run(["$rootScope", "$window", "$http", "$timeout", "$q", "$route", "mediaStream", "appData", "continueConnector", "buddyData", "buddySession", "userSettingsData", "constraints", "playSound", "webmeetingsAccount", "webmeetingsApi", "spreedwebrtcSettingsApi", function ($rootScope, $window, $http, $timeout, $q, $route, mediaStream, appData, continueConnector, buddyData, buddySession, userSettingsData, constraints, playSound, webmeetingsAccount, webmeetingsApi, spreedwebrtcSettingsApi) {

				/**
				 * server_turn_ttl TTL of server configured TURN server
				 */
				var server_turn_ttl = 0;

				/**
				 * If no authentication is required and Spreed loads in the parent window resolve directly
				 */
				if(!config.requireAuthentication && !spreedLoadedInIFrame) {
					webmeetingsApi.resolveDefer();
				}

				/**
				 * If Spreed loads in an iframe then hide the logo since it is in the dialog header
				 */
				if (spreedLoadedInIFrame) {
					$(".navbar-brand").hide();
				}

				var dynamicCSSContainer = "webapp-login";
				var injectCSS = function(css) {
					$.injectCSS(css, {
							containerName: dynamicCSSContainer,
							truncateFirst: true,
							useRawValues: true
						}
					);
				};

				var extraCSS = {};
				extraCSS["#webapp-auth-login"] = {
					display: "block",
					position: "absolute",
					left: "0px",
					bottom: "0%",
					"z-index": "100",
					border: "none",
					width: "100%",
					height: "100%",
					background: "white",
					"margin-top": "0%",
				};

				extraCSS["#roombar .input-group"] = {
					"max-width": "205px",
				};

				extraCSS[".chat.newmessage .chatheader, .chatlist .list-group .list-group-item.newmessage"] = {
					"animation": "none",
					"-webkit-animation": "none",
					"-moz-animation": "none",
					"-o-animation": "none",
					"background": "rgb(132, 184, 25)"
				};

				injectCSS(extraCSS);

				// Noise suppression
				var playSound_play = playSound.play;
				playSound.play = function(id, name) {
					switch (id) {
						case "joined":
						case "left":
							// suppress noise
							break;
						default:
							playSound_play(id, name);
							break;
					}
				}

				// Listen to post message event from the Kopano spreed plugin
				$window.addEventListener('message', webmeetingsApi.onPostMessage);

				if (spreedLoadedInIFrame) {
					webmeetingsApi.requestAuthentication();
				}

				// EVENTS //

				// Try to authorize current the user in spreed
				appData.e.on('selfReceived', function (e, data) {
					webmeetingsApi.authorizeUser(data);
				});

				// Set the authenticated user settings
				appData.e.on('authenticationChanged', function (e, userId) {
					webmeetingsApi.authenticationChanged(userId);
				});

				mediaStream.webrtc.e.on("usermedia", function(event, usermedia) {
					if (usermedia) {
						webmeetingsApi.sendCalling();
					}
				});

				// Send a message to WebApp to notify that current user rejected the call
				mediaStream.webrtc.e.on('statechange', function(event, state, currentcall) {
					switch (state) {
						case "completed":
						case "connected":
							webmeetingsApi.sendCallEstablished();
						case "failed":
							break;
					}
				});

				// Send a message to WebApp to notify that current user rejected the call
				mediaStream.webrtc.e.on('done', function(event, reason) {
					if (reason === 'reject') {
						webmeetingsApi.sendCallRejected();
					} else {
						webmeetingsApi.sendCallDone(reason);
					}
				});

				// Send a message WebApp to notify that current user accepted the call
				mediaStream.webrtc.e.on('waitforusermedia', function() {
					webmeetingsApi.sendRefusedOrAccepted();
				});

				// Send a message when the status of a buddy was received. This is used to tell WebApp a user has
				// joined. The userleftorjoined event does not provide the userId when a user joins.
				mediaStream.api.e.on("received.status", function (event, data) {
					if (event.type === 'received' && event.namespace === 'status' && typeof data.Userid !== 'undefined') {
						webmeetingsApi.sendUserStatusChanged(data.Userid, "online");
					}
				});

				// Send a message to WebApp when the status of a user changes
				mediaStream.api.e.on('received.userleftorjoined', function (event, dataType, data) {
					if (dataType === "Left") {
						webmeetingsApi.sendUserStatusChanged(buddySession.sessions()[data.Id].Userid, "offline");
					}
				});

				// Send a message when an event is received from a buddy
				appData.e.on('uiNotification', function (e, type, data) {
					var from = buddyData.get(data.from).display;
					webmeetingsApi.sendChatInfo(type, data.from, from.displayName);
				});

				// Send a message when the room status changes
				$rootScope.$on('roomStatus', function(){
					webmeetingsApi.sendRoomChanged($rootScope.roomid);
				});

			}]);

			module.provider('webmeetingsAccount', function webmeetingsAccountProvider() {
				this.$get = ["globalContext", "$window", "$timeout", "$rootScope", "rooms", "appData", function webmeetingsAccountFactory(context, $window, $timeout, $rootScope, rooms, appData) {

					/**
					 * Tells whether Spreed was loaded in a room
					 */
					var spreedLoadedInRoom = window.location.pathname && window.location.pathname !== (context.Cfg.B || "/");

					/**
					 * login iFrame for authentication with webapp auth
					 */
					var loginFrame = null;

					/**
					 * login iFrame active
					 */
					var loginActive = false;

					/**
					 * login type is either kopano or code
					 */
					var loginType = null;

					// public api of webmeetingsAccount

					var webmeetingsAccount = {
						loginRequest: function(roomName) {
							if (!loginFrame) {
								loginType = null;
								loginActive = true;
								loginFrame = $window.document.createElement("iframe");
								loginFrame.id = "webapp-auth-login";
								$window.document.body.appendChild(loginFrame);
								loginFrame.onload = function() {
									//console.log("YYYY onload");
									loginFrame.contentWindow.postMessage({Type: "Hello", Version: version}, config.webappDomain);
								};
							}
							loginFrame.setAttribute("src", config.webappAuthLoginUrl + "?meetingid=" + roomName + "&" + $window.location.search.substring(1));
						},
						loginSuccess: function(login_type) {
							loginType = login_type;
							loginActive = false;
							if (loginFrame) {
								loginFrame.className = "";
								$timeout(function() {
									if (!loginActive && loginFrame) {
										loginFrame.parentElement.removeChild(loginFrame);
										loginFrame = null;
									}
								}, 50);
							}
						},
						loginType: function() {
							return (loginType);
						},
						spreedLoadedInRoom: function() {
							return (spreedLoadedInRoom);
						}
					};

					return webmeetingsAccount;
				}];
			});

			module.service('webmeetingsParentApi', ["$window", function($window) {
				/**
				 * auth api iFrame for authentication with webapp auth
				 */
				var parentApiWindow = (function() {
					/**
					 * If Spreed not loaded in an iframe then use kopano webapp as parent api window as well
					 */
					if (spreedLoadedInIFrame) {
						return $window.parent;
					} else {
						return $window.opener;
					}
				})();

				var webmeetingsParentApi = {
					postMessage: function() {
						if (parentApiWindow) {
							return parentApiWindow.postMessage.apply(parentApiWindow, arguments);
						}
					}
				};

				return webmeetingsParentApi;

			}]);

			module.service('webmeetingsAuthApi', ["$window", function($window) {
				/**
				 * auth api iFrame for authentication with webapp auth
				 */
				var authApiFrame = (function() {
					/**
					 * If Spreed not loaded in an iframe then load kopano webapp auth iframe api
					 */
					if (spreedLoadedInIFrame) { return $window.parent; }
					var url=config.webappAuthApiUrl;
					authApiFrame = $window.document.createElement("iframe");
					authApiFrame.id = "webapp-auth-api";
					authApiFrame.hidden = true;
					$window.document.body.appendChild(authApiFrame);
					authApiFrame.setAttribute("src", url);
					return authApiFrame.contentWindow;
				})();

				var webmeetingsAuthApi = {
					postMessage: function() {
						return authApiFrame.postMessage.apply(authApiFrame, arguments);
					}
				};

				return webmeetingsAuthApi;

			}]);

			module.service('webmeetingsApi', ["$rootScope", "$window", "$timeout", "$q", "$route", "mediaStream", "appData", "continueConnector", "buddyData", "buddySession", "webmeetingsParentApi", "webmeetingsAuthApi", "webmeetingsAccount", "spreedwebrtcSettingsApi", function($rootScope, $window, $timeout, $q, $route, mediaStream, appData, continueConnector, buddyData, buddySession, webmeetingsParentApi, webmeetingsAuthApi, webmeetingsAccount, spreedwebrtcSettingsApi) {
				/**
				 * Tells whether Spreed is loaded in an iframe
				 */
				var spreedLoadedInIFrame = $window !== $window.top;

				/**
				 * Deferred object that will need to be resolved before the application can start
				 */
				var defer = continueConnector.defer();

				/**
				 * Deferred object that will be resolved once we are online
				 */
				var online = $q.defer();

				/**
				 * online flag
				 */
				var isOnline = false;

				/**
				 * auth api access_token
				 */
				var access_token = null;

				/**
				 * Deferred object that will be resolved once we receive authentication credentials from webapp
				 */
				var authentication;

				/**
				 * Authentication object from the webapp
				 */
				var webappAuthentication = {};

				/**
				 * timeout timer for TURN server
				 */
				var ttlTimeout = null;

				/**
				 * Called when authorization was successful
				 *
				 * @param {Object} data The authentication data
				 */
				var authorizationSucceeded = function (data) {
					// This will set the authentication on the spreed server and fire the authenticationChanged event
					mediaStream.api.requestAuthentication(data.userid, data.nonce);
					delete data.nonce;

					webmeetingsApi.sendPostMessage({
						"type": "authentication",
						"authentication": "success"
					});

					if (!spreedLoadedInIFrame) {
						webmeetingsApi.sendParentApiPostMessage({
							"type": "authentication",
							"authentication": "success"
						});
					}
				};

				/**
				 * Called when authorization failed
				 */
				var authorizationFailed = function () {
					webmeetingsApi.sendPostMessage({
						"type": "authentication",
						"authentication": "fail"
					});
					// When authenticated failed, we request it again. This loops until it works.
					$timeout(webmeetingsApi.requestAuthentication, 500);
				};

				$($window).on("unload", function() {
					webmeetingsApi.sendParentApiPostMessage({
						"type": "unload",
						"unload": "unload"
					});
				});

				var webmeetingsApi = {
					resolveDefer: function() {
						defer.resolve();
					},

					/**
					 * determines the current room name to identify this window's roomw
					 */
					getRoomName: function () {
						if (spreedLoadedInIFrame) {
							// detect main window with roombar
							return "";
						}
						if ($route.current) {
							roomName = $route.current.params.room;
							roomName = $window.decodeURIComponent(roomName);
							console.log("Room:" + roomName);
						} else {
							roomName = "";
						}
						return roomName;
					},

					/**
					 * Takes care of sending post message to parent window
					 *
					 * @param {Object} data The data to send to WebApp
					 */
					sendParentApiPostMessage: function (data) {
						roomName = webmeetingsApi.getRoomName();
						data.roomid = roomName;
						webmeetingsParentApi.postMessage(data, config.webappDomain);
					},

					/**
					 * Takes care of sending post message to auth api iframe
					 *
					 * @param {Object} data The data to send to WebApp
					 */
					sendAuthApiPostMessage: function (data) {
						webmeetingsAuthApi.postMessage(data, config.webappDomain);
					},

					/**
					 * Takes care of sending post message to parent window
					 *
					 * @param {Object} data The data to send to WebApp
					 */
					sendPostMessage: function (data) {
						webmeetingsAuthApi.postMessage(data, config.webappDomain);
					},

					// Request the authentication object from WebApp
					requestAuthentication: function () {
						if (spreedLoadedInIFrame) {
							webmeetingsApi.sendAuthApiPostMessage({
								"type": "requestAuthentication",
								"requestAuthentication": ""
							});
						} else {
							if (access_token) {
								webmeetingsApi.sendAuthApiPostMessage({
									"type": "requestAuthentication",
									"requestAuthentication": {
										"access_token": access_token
									}
								});
							} else {
								webmeetingsApi.sendAuthApiPostMessage({
									"type": "request_token",
									"request_token": {
										type: "none",
										code: undefined
									}
								});
							}
						}

						authentication = $q.defer();
						return authentication.promise;
					},

					requestLogin: function () {
						if (isOnline) {
							online = $q.defer();
							isOnline = false;
							webappAuthentication = {};
							appData.authorizing(true);
							continueConnector.reset();
							defer = continueConnector.defer();
							if (ttlTimeout) {
								$timeout.cancel(ttlTimeout);
								ttlTimeout = null;
							}
							access_token = null;
							mediaStream.connector.forgetAndReconnect();
						}
						if ($route.current) {
							roomName = $route.current.params.room;
							roomName = $window.decodeURIComponent(roomName);
							console.log("Room:" + roomName);
						} else {
							roomName = "";
						}
						webmeetingsAccount.loginRequest(roomName);
					},

					requestLogout: function() {
						webmeetingsApi.sendAuthApiPostMessage({
							"type": "requestLogout",
							"requestLogout": ""
						});
					},

					requestToken: function (code) {
						webmeetingsApi.sendAuthApiPostMessage({
							"type": "request_token",
							"request_token": code
						});
					},

					refreshAccessToken: function (code) {
						webmeetingsApi.sendAuthApiPostMessage({
							"type": "request_token",
							"request_token": code
						});
					},

					authorizeUser: function(data) {
						if (data.Userid === '') {
							authentication.promise.then(function() {
								mediaStream.users.authorize({
									useridcombo: webappAuthentication.timestamp + ":" + webappAuthentication.userid,
									secret: webappAuthentication.secret
								}, authorizationSucceeded, authorizationFailed);
							});
						}
						if (!isOnline) {
							// indicate authorization phase
							appData.authorizing(true);
						}
						// resolve online promise and set ttl timer if necessary
						online.resolve(data.Turn.ttl);
						// if kopano turn service credential data available then set them again
						if (!data.Turn.ttl && webappAuthentication.turn_ttl) {
							spreedwebrtcSettingsApi.setTurnData(webappAuthentication);
						}
						// Update online flag for instant online checks.
						online.promise.then(function() {
							isOnline = true;
						});

					},

					authenticationChanged: function(userid) {
						if (userid == webappAuthentication.userid) {
							spreedwebrtcSettingsApi.setWebAppUser(webappAuthentication);

							webmeetingsApi.sendParentApiPostMessage({
								"type": "authenticationchanged",
								"authenticationchanged": userid
							});
						}
					},

					/**
					 * Get the list of WebApp user ids of online users from the buddy session
					 */
					sendBuddyList: function () {
						var sendIds = [];
						var buddyList = buddySession.sessions();

						for (var id in buddyList) {
							sendIds.push(buddyList[id].Userid);
						}
						webmeetingsApi.sendParentApiPostMessage({
							"type": "sendBuddyList",
							"list": sendIds
						});
					},

					sendRoomChanged: function(roomid) {
						webmeetingsApi.sendParentApiPostMessage({
							"type": "roomChanged",
							"newRoom": roomid
						});

						// XXX(longsleep): Why is this in a timeout?
						$timeout(function() {
							sendBuddyList();
						});
					},

					sendCalling: function() {
						webmeetingsApi.sendParentApiPostMessage({
							"type": "calling",
							"calling": "connecting"
						});
					},

					sendCallEstablished: function() {
						webmeetingsApi.sendParentApiPostMessage({
							"type": "callEstablished",
							"callEstablished": "connected"
						});
					},

					sendCallDone: function(reason) {
						webmeetingsApi.sendParentApiPostMessage({
							"type": "callDone",
							"callDone": reason
						});
					},

					sendCallRejected: function() {
						webmeetingsApi.sendParentApiPostMessage({
							"type": "chat",
							"chat": "refusedoraccepted"
						});
					},

					sendRefusedOrAccepted: function() {
						webmeetingsApi.sendParentApiPostMessage({
							"type": "chat",
							"chat": "refusedoraccepted"
						});
					},

					sendUserStatusChanged: function(userid, status) {
						webmeetingsApi.sendParentApiPostMessage({
							"type": "userStatusChanged",
							"newStatus": status,
							"userId": userid
						});
					},

					sendChatInfo: function(type, userid, displayName) {
						webmeetingsApi.sendParentApiPostMessage({
							"type": "chat",
							"chat": type,
							"from": {
								id: userid,
								"displayName": displayName
							}
						});
					},

					/**
					 * Event handler for post messages from WebApp
					 *
					 * @param {Event} e postMessage event
					 */
					onPostMessage: function (e) {
						var message = e.data;
						var roomName;

						// check if the message comes from a valid origin
						if (config.webappDomain === e.origin) {
							// Handle postMessages from the webapp
							switch (message.type) {
								// Webapp requests authorization
								case "hello":
									webmeetingsApi.requestAuthentication();
									break;
								case "requestLogin":
									webmeetingsApi.requestLogin();
									break;
								case "loginSuccess":
									//console.log("login successful");
									webmeetingsAccount.loginSuccess(message.loginSuccess.type);
									webmeetingsApi.requestToken(message.loginSuccess)
									break;
								case "access_token":
									//console.log("access_token");
									access_token = message.access_token.access_token;
									webmeetingsApi.requestAuthentication();
									break;
								case "refresh_access_token":
									//console.log("refresh_access_token");
									webmeetingsApi.refreshAccessToken(message.refresh_access_token);
									break;
								// Webapp requests authorization
								case "authentication":
									webappAuthentication = message.authentication;
									if (config.requireAuthentication || spreedLoadedInIFrame) {
										defer.resolve();
									}
									if (!isOnline) {
										online.promise.then(function(data_turn_ttl) {
											isOnline = true;
											// check if Turn server not configured, then use Kopano Turn service
											server_turn_ttl = data_turn_ttl;
											if (!server_turn_ttl && webappAuthentication.turn_ttl) {
												spreedwebrtcSettingsApi.setTurnData(webappAuthentication);
												ttlTimeout = $timeout(function() {
													console.log("Turn service TTL reached - sending refresh request.");
													// Request the authentication object from WebApp
													webmeetingsApi.requestAuthentication();
												}, webappAuthentication.turn_ttl / 100 * 90 * 1000);
											}
										});
									} else {
										// we're online
										if (!server_turn_ttl && webappAuthentication.turn_ttl) {
											spreedwebrtcSettingsApi.setTurnData(webappAuthentication);
											ttlTimeout = $timeout(function() {
												console.log("Turn service TTL reached - sending refresh request.");
												// Request the authentication object from WebApp
												webmeetingsApi.requestAuthentication();
											}, webappAuthentication.turn_ttl / 100 * 90 * 1000);
										}
									}
									authentication.resolve();
									break;
								case "soundSettings":
									webappSoundSettings = message.soundSettings;
									spreedwebrtcSettingsApi.setSoundSettings(webappSoundSettings);
									break;
								case "requestBuddyList":
									webmeetingsApi.sendBuddyList();
									break;
								case "startCall":
									mediaStream.webrtc.doCall(buddyData.get(message.userId).session.Id);
									break;
								case "startChat":
									$rootScope.$emit("startchat", buddyData.get(message.userId).session.Id, {
										autofocus: true,
										restore: true
									});
							}
						}
					}


				};

				return webmeetingsApi;
			}]);

			module.service('spreedwebrtcSettingsApi', ["$rootScope", "appData", "userSettingsData", "constraints", "turnData", function($rootScope, appData, userSettingsData, constraints, turnData) {
				var spreedwebrtcSettingsApi = {
					/**
					 * This will overwrite the user info in Spreed with the user info from webApp
					 */
					setWebAppUser: function (webappAuthentication) {
						var spreedData = appData.get(),
							userData = userSettingsData.load();

						userData.displayName = webappAuthentication.fullname;
						userData.buddyPicture = (webappAuthentication.buddyPicture === '' && userData !== null) ? userData.buddyPicture : webappAuthentication.buddyPicture;
						userSettingsData.save(userData);

						// Disable the 'your name' textfield when possible
						if (yourNameTextfield !== null && typeof yourNameTextfield !== 'undefined') {
							yourNameTextfield.prop('disabled', true);
						}

						// Hide the 'take picture' button when authenticated
						if (webappAuthentication.buddyPicture && webappAuthentication.buddyPicture.indexOf('data:image') === 0) {
							if (takePictureButton !== null && typeof takePictureButton !== 'undefined') {
								takePictureButton.hide();
								// also hide the 'upload picture' button
								takePictureButton.next().hide();
							}
						}

						defaultRoomTextfieldFormGroup
						// Hide the 'defaultRoom' textfield Form Group when possible
						if (defaultRoomTextfieldFormGroup !== null && typeof defaultRoomTextfieldFormGroup !== 'undefined') {
							defaultRoomTextfieldFormGroup.hide();
						}
					},

					/**
					 * Called when TURN authentication set for Kopano TURN service
					 */
					setTurnData: function (webapp_data) {
						// check for backward compatibility workaround
						if (typeof $rootScope.turn === 'object') {
							$rootScope.turn.username = webapp_data.turn_username;
							$rootScope.turn.password = webapp_data.turn_password;
							$rootScope.turn.ttl      = webapp_data.turn_ttl;
							$rootScope.turn.urls = webapp_data.turn_urls;
						}

						// new style use of constraints
						var zarafaTurnData = {
								"username": webapp_data.turn_username,
								"password": webapp_data.turn_password,
								"ttl": webapp_data.turn_ttl,
								"urls": webapp_data.turn_urls
							}
						constraints.turn(zarafaTurnData);

						turnData.update(zarafaTurnData);

						// refresh turn settings
						$rootScope.refreshWebrtcSettings();
					},

					/**
					 * Callen to set sound settings from WebApp
					 */
					setSoundSettings: function (webappSoundSettings) {
						var spreedData = appData.get(),
							userData = userSettingsData.load();

						spreedData.master.settings.sound.incomingMessages = webappSoundSettings.incomingMessages;
						spreedData.master.settings.sound.incomingCall     = webappSoundSettings.incomingCall;
						spreedData.master.settings.sound.roomJoinLeave    = webappSoundSettings.roomJoinLeave;
						userSettingsData.save(spreedData.master);
						$rootScope.refreshSoundSettings();

						yourNotificationSettingsIncomingMessages.hide();
						yourNotificationSettingsIncomingCall.hide();
						yourNotificationSettingsRoomJoinLeave.hide();
					}

				};

				return spreedwebrtcSettingsApi;
			}]);

			// HANDLE DIRECTIVES //

			// Get a reference to the 'take picture' button in the spreed settings panel
			module.directive('buddyPictureCapture', [function () {
				return {
					"restrict": "C",
					"link": function (scope, elem, attrs) {
						takePictureButton = $(elem).children('a.btn-primary');
					}
				};
			}]);

			// Get a reference to the 'your name' textfield in the spreed settings panel
			module.directive('settingsExtra', [function () {
				return {
					"restrict": "A",
					"link": function (scope, elem, attrs) {
						yourNameTextfield = $(elem).parent().find("input[ng-model=user\\.displayName]");
					}
				};
			}]);

/*			// Always hide the profile Yourid section.
			module.directive('profileYourid', [function() {
				return {
					"restrict": "C",
					"link": function(scope, elem, attrs) {
						$(elem).remove();
					}
				}
			}]);
*/
			// Always hide the socialshare section.
			module.directive('socialshare', [function() {
				return {
					"restrict": "C",
					"link": function(scope, elem, attrs) {
						$(elem).remove();
					}
				}
			}]);

			// Always hide the roomBar section.
			module.directive('roomBar', ['appData', 'webmeetingsAccount', function(appData, webmeetingsAccount) {
				return {
					"restrict": "E",
					"link": function(scope, elem, attrs) {
						appData.e.on('authenticationChanged', function (e, userId) {
							if (webmeetingsAccount.loginType() == 'code') {
								$(elem).hide();
							} else {
								if (webmeetingsAccount.spreedLoadedInRoom()) {
									$(elem).hide();
								} else {
									$(elem).show();
								}
							}
						});
						$(elem).hide();
					}
				}
			}]);

			// Get a reference to the sounds settings section in the spreed settings panel
			module.directive('settingsExtra', [function () {
				return {
					"restrict": "A",
					"link": function (scope, elem, attrs) {
						defaultRoomTextfieldFormGroup            = $(elem).parent().find("input[ng-model=user\\.settings\\.defaultRoom]").parent().parent();
						yourNotificationSettingsIncomingMessages = $(elem).parent().find("input[ng-model=user\\.settings\\.sound\\.incomingMessages]").parent().parent();
						yourNotificationSettingsIncomingCall     = $(elem).parent().find("input[ng-model=user\\.settings\\.sound\\.incomingCall]").parent().parent();
						yourNotificationSettingsRoomJoinLeave    = $(elem).parent().find("input[ng-model=user\\.settings\\.sound\\.roomJoinLeave]").parent().parent();
					}
				};
			}]);

			//Inject the module into modules array so that it gets loaded
			modules.push(module.name);
		}
	};
});
