/* global Strophe, APP, $, config, interfaceConfig, toastr */
var UI = {};
var VideoLayout = require("./videolayout/VideoLayout.js");
var AudioLevels = require("./audio_levels/AudioLevels.js");
var Prezi = require("./prezi/Prezi.js");
var Etherpad = require("./etherpad/Etherpad.js");
var Chat = require("./side_pannels/chat/Chat.js");
var Toolbar = require("./toolbars/Toolbar");
var ToolbarToggler = require("./toolbars/ToolbarToggler");
var BottomToolbar = require("./toolbars/BottomToolbar");
var ContactList = require("./side_pannels/contactlist/ContactList");
var Avatar = require("./avatar/Avatar");
var EventEmitter = require("events");
var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
var Settings = require("./../settings/Settings");
var PanelToggler = require("./side_pannels/SidePanelToggler");
var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
UI.messageHandler = require("./util/MessageHandler");
var messageHandler = UI.messageHandler;
var Authentication  = require("./authentication/Authentication");
var UIUtil = require("./util/UIUtil");
var NicknameHandler = require("./util/NicknameHandler");
var JitsiPopover = require("./util/JitsiPopover");
var CQEvents = require("../../service/connectionquality/CQEvents");
var DesktopSharingEventTypes
    = require("../../service/desktopsharing/DesktopSharingEventTypes");
var RTCEvents = require("../../service/RTC/RTCEvents");
var RTCBrowserType = require("../RTC/RTCBrowserType");
var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
var XMPPEvents = require("../../service/xmpp/XMPPEvents");
var UIEvents = require("../../service/UI/UIEvents");
var MemberEvents = require("../../service/members/Events");
var eventEmitter = new EventEmitter();
var roomNode = null;
var roomName = null;
function promptDisplayName() {
    var message = '
';
    message += APP.translation.translateString(
        "dialog.displayNameRequired");
    message += ' ' +
        'true  to mute the local video; otherwise, false 
 * @param options an object which specifies optional arguments such as the
 * boolean  key byUser  with default value true  which
 * specifies whether the method was initiated in response to a user command (in
 * contrast to an automatic decision taken by the application logic)
 */
function setVideoMute(mute, options) {
    APP.RTC.setVideoMute(mute,
        UI.setVideoMuteButtonsState,
        options);
}
function onResize() {
    Chat.resizeChat();
    VideoLayout.resizeLargeVideoContainer();
}
function bindEvents() {
    /**
     * Resizes and repositions videos in full screen mode.
     */
    $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
        onResize);
    $(window).resize(onResize);
}
UI.start = function (init) {
    document.title = interfaceConfig.APP_NAME;
    var setupWelcomePage = null;
    if(config.enableWelcomePage && window.location.pathname == "/" &&
        (!window.localStorage.welcomePageDisabled ||
            window.localStorage.welcomePageDisabled == "false")) {
        $("#videoconference_page").hide();
        if (!setupWelcomePage)
            setupWelcomePage = require("./welcome_page/WelcomePage");
        setupWelcomePage();
        return;
    }
    $("#welcome_page").hide();
    // Set the defaults for prompt dialogs.
    $.prompt.setDefaults({persistent: false});
    registerListeners();
    VideoLayout.init(eventEmitter);
    NicknameHandler.init(eventEmitter);
    bindEvents();
    setupPrezi();
    if (!interfaceConfig.filmStripOnly) {
        $("#videospace").mousemove(function () {
            return ToolbarToggler.showToolbar();
        });
        setupToolbars();
        setupChat();
        // Display notice message at the top of the toolbar
        if (config.noticeMessage) {
            $('#noticeText').text(config.noticeMessage);
            $('#notice').css({display: 'block'});
        }
        $("#downloadlog").click(function (event) {
            dump(event.target);
        });
    }
    else
    {
        $("#header").css("display", "none");
        $("#bottomToolbar").css("display", "none");
        $("#downloadlog").css("display", "none");
        $("#remoteVideos").css("padding", "0px 0px 18px 0px");
        $("#remoteVideos").css("right", "0px");
        messageHandler.disableNotifications();
        $('body').popover("disable");
//        $("[data-toggle=popover]").popover("disable");
        JitsiPopover.enabled = false;
    }
    document.title = interfaceConfig.APP_NAME;
    if(config.requireDisplayName) {
        var currentSettings = Settings.getSettings();
        if (!currentSettings.displayName) {
            promptDisplayName();
        }
    }
    init();
    if (!interfaceConfig.filmStripOnly) {
        toastr.options = {
            "closeButton": true,
            "debug": false,
            "positionClass": "notification-bottom-right",
            "onclick": null,
            "showDuration": "300",
            "hideDuration": "1000",
            "timeOut": "2000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut",
            "reposition": function () {
                if (PanelToggler.isVisible()) {
                    $("#toast-container").addClass("notification-bottom-right-center");
                } else {
                    $("#toast-container").removeClass("notification-bottom-right-center");
                }
            },
            "newestOnTop": false
        };
        SettingsMenu.init();
    }
};
function chatAddError(errorMessage, originalText) {
    return Chat.chatAddError(errorMessage, originalText);
}
function chatSetSubject(text) {
    return Chat.chatSetSubject(text);
}
function updateChatConversation(from, displayName, message, myjid, stamp) {
    return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
}
function onMucJoined(jid, info) {
    Toolbar.updateRoomUrl(window.location.href);
    var meHTML = APP.translation.generateTranslationHTML("me");
    $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
    var settings = Settings.getSettings();
    // Make sure we configure our avatar id, before creating avatar for us
    Avatar.setUserAvatar(jid, settings.email || settings.uid);
    // Add myself to the contact list.
    ContactList.addContact(jid);
    // Once we've joined the muc show the toolbar
    ToolbarToggler.showToolbar();
    var displayName =
        config.displayJids ? Strophe.getResourceFromJid(jid) : info.displayName;
    if (displayName)
        onDisplayNameChanged('localVideoContainer', displayName);
    VideoLayout.mucJoined();
}
function initEtherpad(name) {
    Etherpad.init(name);
}
function onMucMemberLeft(jid) {
    console.log('left.muc', jid);
    var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
        '>.displayname').html();
    messageHandler.notify(displayName,'notify.somebody',
        'disconnected',
        'notify.disconnected');
    if (!config.startAudioMuted ||
        config.startAudioMuted > APP.members.size()) {
        UIUtil.playSoundNotification('userLeft');
    }
    ContactList.removeContact(jid);
    VideoLayout.participantLeft(jid);
}
function onLocalRoleChanged(jid, info, pres, isModerator) {
    console.info("My role changed, new role: " + info.role);
    onModeratorStatusChanged(isModerator);
    VideoLayout.showModeratorIndicator();
    SettingsMenu.onRoleChanged();
    if (isModerator) {
        Authentication.closeAuthenticationWindow();
        messageHandler.notify(null, "notify.me",
            'connected', "notify.moderator");
        Toolbar.checkAutoRecord();
    }
}
function onModeratorStatusChanged(isModerator) {
    Toolbar.showSipCallButton(isModerator);
    Toolbar.showRecordingButton(
        isModerator); //&&
    // FIXME:
    // Recording visible if
    // there are at least 2(+ 1 focus) participants
    //Object.keys(connection.emuc.members).length >= 3);
}
function onPasswordRequired(callback) {
    // password is required
    Toolbar.lockLockButton();
    var message = '';
    message += APP.translation.translateString(
        "dialog.passwordRequired");
    message += ' ' +
        '';
    message += APP.translation.translateString(
        "dialog.passwordRequired");
    message += ' ' +
        '