"use strict";

angular.module('app.layout', ['ui.router', 'ui.bootstrap'])

.config(function ($stateProvider, $urlRouterProvider, $locationProvider, SQEventsProvider) {

    SQEventsProvider.add("SKIN_CHANGED", "skin-changed");
    SQEventsProvider.add("APP_PANEL_CHANGED", "app-panel-changed");
    SQEventsProvider.add("OPEN_ABOUT_DIALOG", "open-about-dialog");

    $stateProvider
        .state('app', {
            abstract: false,
            url: '/',
            views: {
                root: {
                    templateUrl: '../QDM/layout/views/layout.html',
                    controller: 'LayoutCtrl'
                }
            },
            resolve: {
                connectWebSocket: function(SQWebSocketService){
                    return SQWebSocketService.connectWebSocket(location.port);
                },
                loadConstants: function(SQConstants){
                    return SQConstants.loadAll();
                },
                loadLanguage: function(L){
                    return L.downloadLanguage();
                },
                loadSkin: function(SkinService){
                    return SkinService.loadSkins();
                }
            }
        });
        
    $urlRouterProvider.otherwise(window.appConfig.defaultURL);

})
"use strict";

angular.module('app.login', ['ui.router', 'ngStorage']).config(function ($stateProvider) {

    $stateProvider.state('sqlogin', {
        url: '/sqlogin:redirectTo',
        data: {
            title: 'Login',
            rootId: 'extra-page'
        },
        views: {
            root: {
                templateUrl: '../app/login/views/login.html',
                controller: 'LoginController'
            }
        }
    })
});
angular.module('app.layout').service('QDMService', function(BackendService) {
    
    this.bannerClicked = function(id, callOnSuccess, dismiss) {
        var data = {id: id};
        if(dismiss) {
            data.dismiss = true;
        }

        BackendService.sendRequest('qdm/bannerClicked', data, callOnSuccess);
    }   
});
    
angular.module('app.login').service('LoginService', ['$q', '$localStorage', 'BackendService', function($q, $localStorage, BackendService) {
        var token;
        var $storage = $localStorage.$default();
        var disabled = false;
        
        this.login = function(password){
            var deferred = $q.defer();
            var data = { password: password };
            
            BackendService.getPromise('/main/login', data, 'POST').then(function(result){
                if(result.success){
                    token = result.data.token;
                    
                    saveToken();
                    
                    BackendService.setToken(token);
                    deferred.resolve({success: true});
                }
                else {
                    deferred.resolve({
                        success: false,
                        data: result.data
                    });
                }
            });
            
            return deferred.promise;
        }
        
        this.checkRemoteAccess = function(){
            var url = "main/checkaccess";
            return BackendService.getPromise(url, null);
        }
        
        this.loadSessionInfo = function(){
            token = $storage.token;
            if(token){
                BackendService.setToken(token);
            }
        }();
        
        this.logout = function(){
            token = null;
            $storage.token = null;
        }
        
        function saveToken(){
            $storage.token = token;
        }
        
        this.getToken = function(){
            return token;
        }
        
        this.setDisabled = function(dis){
            disabled = dis;
        }
        
        this.isDisabled = function(){
            return disabled;
        }
        
    }]);
        
angular.module('app.layout').controller('LayoutCtrl', function ($rootScope, $scope, $timeout, $state, sqPlugin, AppService, SQEvents, SQConstants, SQWebSocketService, L, SkinService, QDMService) {
    console.log("QuantDataManager's Layout controller initialized");

    $scope.apps = sqPlugin.getPlugins("NavigationPlugin");
    $scope.isQDM = true;

    function loadApps() {
        for (var i = 0; i < $scope.apps.length; i++) {
            var app = $scope.apps[i];

            if (app.appCode == 'SQMANAGER') {
                addApp(app);
                break;
            }
        }
    }

    loadApps();

    $scope.closeInitSettings = function (save) {
        if(save) {
            L.downloadLanguage($scope.initSettings.language);
            SkinService.changeSkin($scope.initSettings.skin);
        }

        hidePopup("#initSettingsDialog");
    }

    $scope.openLinkSupport = function () {
        AppService.openBrowser('http://docs.strategyquant.com/', function () {});
    }

    $scope.openLinkBugs = function () {
        AppService.openBrowser('http://roadmap.strategyquant.com', function () {});
    }

    $scope.openLinkSuggestIdea = function () {
        AppService.openBrowser('http://roadmap.strategyquant.com', function () {});
    }

    $scope.onAbout = function () {
        window.parent.broadcastEvent(SQEvents.get('OPEN_ABOUT_DIALOG'));
    }

    $scope.onUpdateLicense = function () {
        window.parent.broadcastEvent(SQEvents.get('OPEN_ABOUT_DIALOG'), {
            update: true
        });
    }

    $scope.onSettings = function () {
        $scope.initSettings.language = getItem(L.languages, "title", $rootScope.selectedLanguage.title || "English");
        $scope.initSettings.skin = getItem($scope.skins, "name", SQConstants.getSettings().skin || "Light skin");

        try {
            $scope.$digest();
        } catch (err) {}
        $timeout(function () {
            showPopup("#initSettingsDialog");
        });
    }

    $scope.footerCustomText = SQConstants.getConstants().global.footerCustomText;

    $scope.loadNext = function () {
        if (!SQConstants.getSettings().skin) {
            $scope.onSettings();
        }
    }

    window.onAppLoaded = $scope.loadNext;

    //skin/language --------------------------------------------------------------
    $scope.skins = SkinService.skins;
    $scope.languages = L.languages;
    $scope.initSettings = {
        skin: $scope.skins[0],
        language: $rootScope.selectedLanguage,
        help: L.tsq('You will be able to change these options later in Settings in footer')
    };

    //banners --------------------------------------------------------------
    $scope.topBanner = null;
    $scope.popupBanner = null;

    $scope.onBannerClicked = function (banner, dismiss) {
        QDMService.bannerClicked(banner.id, null, dismiss);

        hidePopup('#popupBannerModal');
    }

    function onWebSocketData(data) {
        if (data.qdmBanner) {

            if (data.qdmBanner.top) {
                $scope.topBanner = data.qdmBanner.top;
            }

            if (data.qdmBanner.popup) {
                $scope.popupBanner = data.qdmBanner.popup;

                var iframe_dm = $("#iframe_dm")[0]
                if (!window.activePopup && !iframe_dm.contentWindow.activePopup) {
                    showPopup('#popupBannerModal');
                } else {
                    console.log("Popup banner isn't displayed because another popup is opened.")
                }
            }

            try {
                $scope.$digest();
            } catch (err) {}
        }
    }

    function updateFbIconOccurence() {
        if (navigator.onLine) {
            $(".fb-like").show();
            setTimeout(function () {
                $(".fb-like").attr('src', function (i, val) {
                    return val;
                });
            }, 1000);
        } else {
            $(".fb-like").hide();
        }
    }

    window.addEventListener('online', updateFbIconOccurence);
    window.addEventListener('offline', updateFbIconOccurence);
    updateFbIconOccurence();


    SQWebSocketService.subscribeGeneral("QDM", onWebSocketData);

    function onEvent(event, data) {
        if (event == SQEvents.get('LICENSE_CHANGED')) {
            if ($rootScope.license.isProVersion) {
                $scope.topBanner = null;
            }

            try {
                $scope.$digest();
            } catch (err) {}
        }
    }

    SQEvents.addListener("QDM-layout", [SQEvents.get('LICENSE_CHANGED')], onEvent);
});
$(document).on(
  "click",
  "ul.icons-system .dropdown-menu .dropdown-dont-close",
  function (e) {
    e.stopPropagation();
    return false;
  }
);

$(document).on("click", ".sq-accordion .item-head", function () {
  $(this)
    .closest(".sq-accordion")
    .children(".item.active")
    .removeClass("active");
  $(this).closest(".item").addClass("active");
});

$(document).on("show.bs.modal", ".modal", function () {
  var zIndex = 1040 + 10 * $(".modal:visible").length;
  $(this).css("z-index", zIndex);
  setTimeout(function () {
    $(".modal-backdrop")
      .not(".modal-stack")
      .css("z-index", zIndex - 1)
      .addClass("modal-stack");
  }, 0);
});

$(document).on("click", ".quant-tabs >.tabs-header > div", function () {
  window.dispatchEvent(new Event("resize"));
});

$(document).on("focus", ".sq-input input, .sq-input select", function () {
  if ($(this).closest(".sq-input-select-overlay").length > 0) {
    $(this).closest(".sq-input-select-overlay").addClass("sq-input-focused");
  }
  if ($(this).closest(".input-group").length > 0) {
    $(this).closest(".input-group").addClass("sq-input-focused");
  }
  showTooltipForInput(this);
});

$(document).on("blur", ".sq-input input, .sq-input select", function () {
  if ($(this).closest(".sq-input-select-overlay").length > 0) {
    $(this).closest(".sq-input-select-overlay").removeClass("sq-input-focused");
  }
  if ($(this).closest(".input-group").length > 0) {
    $(this).closest(".input-group").removeClass("sq-input-focused");
  }
  hideTooltipForInput();
});

$(document).on("mouseenter", ".sq-input input, .sq-input select", function () {
  if (
    $(".sq-input.sq-input-focused").length > 0 &&
    !$(this).closest(".sq-input").hasClass("sq-input-focused")
  ) {
    return;
  }
  showTooltipForInput(this);
});

function showTooltipForInput(thisElem) {
  if ($(thisElem).closest(".sq-input").find(".sq-tooltip").length <= 0) return;
  var thisTooltipContent = $(thisElem)
    .closest(".sq-input")
    .find(".sq-tooltip")
    .html();
  if (thisTooltipContent == "") return;
  var thisInputOffset = $(thisElem).offset();
  if ($(".sq-input-global-tooltip").length <= 0) {
    $("<div />").addClass("sq-input-global-tooltip").appendTo("body");
  }
  $(".sq-input-global-tooltip").html(thisTooltipContent);
  $(".sq-input-global-tooltip").show();
  var offsetBottom = $(window).height() - thisInputOffset.top + 10;
  var offsetLeft = thisInputOffset.left + 20;
  $(".sq-input-global-tooltip").css({
    position: "absolute",
    bottom: offsetBottom + "px",
    left: offsetLeft + "px",
  });
  $(".sq-input-global-tooltip").fadeIn(100);
}

$(document).on("wheel", function () {
  if (
    $(".sq-input-global-tooltip").length <= 0 ||
    $(".sq-input-global-tooltip").css("display") == "none"
  ) {
    return;
  }
  $(".sq-input-global-tooltip").hide();
});

function hideTooltipForInput() {
  if ($(".sq-input-global-tooltip").length > 0) {
    $(".sq-input-global-tooltip").fadeOut(100);
  }
}

$(document).on("mouseleave", ".sq-input input, .sq-input select", function () {
  if ($(".sq-input.sq-input-focused").length > 0) {
    return;
  }
  if ($(this).closest(".sq-input").hasClass("sq-input-focused")) {
    return;
  }
  hideTooltipForInput();
});

$(document).on("click", ".sq-help-ico", function (e) {
  e.stopPropagation();
  $(this).toggleClass("shown");
  if ($(this).hasClass("shown")) {
    rightPositionSqHelpIco(this);
  }
});

$(window).resize(function () {
  $(".sq-help-ico").each(function () {
    if ($(this).hasClass("shown")) {
      rightPositionSqHelpIco(this);
    }
    $(this).closest(".sq-fieldset").parent().addClass("has-help-container");
  });
});

$(document).on("click", function () {
  $(".sq-help-ico").removeClass("shown");
  $(".dropdown").removeClass("open");
});

$(document).on("click", ".sqn-databanks, .dropdown-menu", function () {
  $(".dropdown").removeClass("open");
});

function rightPositionSqHelpIco(thisElem) {
  var fieldsetParent = $(thisElem).closest(".sq-fieldset").parent();
  var fpWidth = fieldsetParent.width();
  var minAllowedWidth = 1100 + 300 + 45;
  if (fpWidth < minAllowedWidth) {
    $(thisElem).addClass("show-left");
  } else {
    $(thisElem).removeClass("show-left");
  }
}

$(document).on("focusin", "#passwordInput input", function () {
  console.log("x");
  this.oldValue = this.value;
  this.value = "";
});

$(document).on("focusout", "#passwordInput input", function () {
  if (this.value == "") {
    this.value = this.oldValue;
  }

  $(this).parent().addClass("sq-input-filled");
});

$(document).on(
  "click",
  ".sqn-settings-body, .modal, .sqn-databanks, #sq-notices, .split-pane-divider, .split-pane-divider-inner",
  function (e) {
    e.stopPropagation();
    $(".dropdown-parameters-settings.open").removeClass("open");
  }
);

$(document).on(
  "click",
  ".dropdown-parameters-settings .dropdown-menu",
  function (e) {
    e.stopPropagation();
  }
);

$(document).on("click", ".quant-tabs > .tabs-header div", function () {
  var itemName = $(this).data("item");
  if (itemName == "" || itemName == undefined) return;
  var $tabsContainer = $(this).parent().parent();
  if ($tabsContainer.children(".tabs-body").length <= 0) {
    $tabsContainer = $tabsContainer.parent().parent();
  }
  var $tabsBody = $tabsContainer.children(".tabs-body");
  $tabsContainer.children(".tabs-header div").removeClass("active");
  $tabsContainer
    .children(".tabs-header div[data-item=" + itemName + "]")
    .addClass("active");
  $tabsBody.children(".active").removeClass("active");
  $tabsBody.children("div[data-item=" + itemName + "]").addClass("active");
});

$(window).on("resize", function () {
  if (window.appConfig.product == "SQUANT") {
    return;
  }
  if ($(".quant-tabs >.tabs-header").length > 0) {
    tabsShowHiddenTabs();
  }
  var $iframe = $("#iframe_results_overlayed", window.parent.document);
  var newHeight = $(".split-pane-component-dashboard").height() - 51;
  if ($iframe.hasClass("active")) {
    if ($(".task-manager-menu").length > 0) {
      /* newHeight -= 30; */
      $iframe.addClass("iframe_results_overlayed_tasks");
    } else {
      $iframe.removeClass("iframe_results_overlayed_tasks");
    }
    $iframe.css("height", newHeight + "px");
  }
  var logHeight = newHeight - 700;
  $(".sqn-engine .log-scroll-content").css("height", logHeight + "px");
});

function displayNormalHeader(selector) {
  $(selector)
    .find(".tabs-header")
    .children("div")
    .each(function () {
      console.error(this);
      $(this).css("display", "block");
    });
}

function tabsShowHiddenTabs() {
  return;
  $(".quant-tabs").each(function () {
    if (!$(this).is(":visible")) {
      return;
    }
    $(this).find(".tabs-header").children("div").removeAttr("style");
    var tabsHeaderRect = $(this)
      .find(".tabs-header")[0]
      .getBoundingClientRect();
    var tabsHeaderRight = tabsHeaderRect.right;
    var tabsHeaderBottom =
      tabsHeaderRect.top + $(this).find(".tabs-header .active").outerHeight();
    var tabsHidden = [];
    var tabsHidden2 = [];
    $(this)
      .find(".tabs-header")
      .children("div")
      .each(function () {
        if (!$(this).hasClass("tabs-menu")) {
          var tabsItemRect = $(this)[0].getBoundingClientRect();
          var tabsItemTop = tabsItemRect.top;
          var tabsItemLeft = tabsItemRect.left;
          if (
            tabsItemTop > tabsHeaderBottom - 10 ||
            tabsItemLeft > tabsHeaderRight - 35
          ) {
            tabsHidden.push($(this)[0].outerHTML);
            tabsHidden2.push($(this));
          }
        }
      });
    for (var key in tabsHidden2) {
      tabsHidden2[key].hide();
    }
    $(this).find(".tabs-header").children(".tabs-menu").remove();
    if (tabsHidden.length > 0) {
      var $tabsMenu = $('<div class="tabs-menu">&#x25BC;</div>');
      var $tabsSubmenu = $('<div class="tabs-submenu"></div>');
      for (var itemKey in tabsHidden) {
        var itemItself = tabsHidden[itemKey];
        $tabsSubmenu.append($(itemItself));
      }
      $tabsMenu.append($tabsSubmenu);
      $(this).find(".tabs-header").append($tabsMenu);
    }
  });
}

$(document).on("click", ".disabled-area-placeholder", function (e) {
  e.preventDefault();
  e.stopPropagation();
  return false;
});

$(document).on(
  "click",
  ".settings-table-cross-check .simple-cs-line.category .categoryName",
  function (e) {
    $(this).parent().parent(".simple-cs-section").toggleClass("opened");
  }
);

history.pushState(null, document.title, location.href);
window.addEventListener("popstate", function (event) {
  history.pushState(null, document.title, location.href);
});

angular.module('app').filter('html', function($sce){
    return function(input){
        return $sce.trustAsHtml(input);
    }
})
$(window).on("resize", function () {
    if ($('.quant-tabs >.tabs-header').length > 0) {
        tabsShowHiddenTabs();
    }
});

$(document).on("click", '.quant-tabs > .tabs-header div', function () {
    var itemName = $(this).data('item');
    if (itemName == '' || itemName == undefined) return;
    var $tabsContainer = $(this).parent().parent();
    if ($tabsContainer.children('.tabs-body').length <= 0) {
        $tabsContainer = $tabsContainer.parent().parent();
    }
    var $tabsBody = $tabsContainer.children('.tabs-body');
    $tabsContainer.children('.tabs-header div').removeClass('active');
    $tabsContainer.children('.tabs-header div[data-item=' + itemName + ']').addClass('active');
    $tabsBody.children('.active').removeClass('active');
    $tabsBody.children('div[data-item=' + itemName + ']').addClass('active');
});

$(document).on('click', '.ribbon-expandbtn', function () {
    fadeInProjectInfo();
});

function fadeInProjectInfo() {
    $('.ribbon-expandbtn').fadeOut(200);
    $('.ribbon-expanded').slideDown(200);
}

$(document).on('click', '.ribbon-expanded-hidebtn', function () {
    fadeOutProjectInfo();
});

function fadeOutProjectInfo() {
    $('.ribbon-expanded').slideUp(200);
    $('.ribbon-expandbtn').fadeIn(200);
}

$(document).on('click', '.pathInput', function (e) {
    var input = this;
    window.setTimeout(function () {
        SetCaretAtEnd(input);
    }, 100);
});

function SetCaretAtEnd(elem) {
    var elemLen = elem.value.length;
    // For IE Only
    if (document.selection) {
        // Set focus
        elem.focus();
        // Use IE Ranges
        var oSel = document.selection.createRange();
        // Reset position to 0 & then set at end
        oSel.moveStart('character', -elemLen);
        oSel.moveStart('character', elemLen);
        oSel.moveEnd('character', 0);
        oSel.select();
    } else if (elem.selectionStart || elem.selectionStart == '0') {
        // Firefox/Chrome
        elem.selectionStart = elemLen;
        elem.selectionEnd = elemLen;
        elem.focus();
    } // if
} // SetCaretAtEnd()

function positionGrid(gridName, width, height) {
    $('#' + gridName).attr('style', 'height: ' + height + '!important;' +
        'width: ' + width + '!important;' +
        'position: relative!important;' +
        'top: 0px!important;' +
        'left: 0px!important;' +
        'right: 0px!important;');
}

//filter data items on Enter press
$(document).on('keypress', '#instSearchInput', function (e) {
    if (e.keyCode == 13) {
        $('#instFilterBtn').click();
    }
});

//fix that enables multiple modal windows overlay
$(document).on('show.bs.modal', '.modal', function () {
    var zIndex = 1040 + (10 * $('.modal:visible').length);
    $(this).css('z-index', zIndex);
    setTimeout(function () {
        $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
    }, 0);
});

// Code goes here

$(document).on('ready', function () {
    PointerEventsPolyfill();
    $('[data-toggle="tooltip"]').tooltip()
});

$(document).on('click', '.sq-input label', function () {
    $(this).parent().find('input').focus();
    $(this).parent().find('select').focus();
});

$(document).on('click', '.bb-left-menu', function () {
    $('label.bb-left-menu').removeClass('selected');
    $(this).addClass('selected');
});

$(document).on('click', '.conditions-menu', function () {
    $('label.conditions-menu').removeClass('selected');
    $(this).addClass('selected');
});

function PointerEventsPolyfill(options) {
    // set defaults
    this.options = {
        selector: '*',
        mouseEvents: ['click', 'dblclick', 'mousedown', 'mouseup'],
        usePolyfillIf: function () {
            if (navigator.appName == 'Microsoft Internet Explorer') {
                var agent = navigator.userAgent;
                if (agent.match(/MSIE ([0-9]{1,}[\.0-9]{0,})/) != null) {
                    var version = parseFloat(RegExp.$1);
                    if (version < 11)
                        return true;
                }
            }
            return false;
        }
    };
    if (options) {
        var obj = this;
        $.each(options, function (k, v) {
            obj.options[k] = v;
        });
    }

    if (this.options.usePolyfillIf())
        this.register_mouse_events();
}

// singleton initializer
PointerEventsPolyfill.initialize = function (options) {
    if (PointerEventsPolyfill.singleton == null)
        PointerEventsPolyfill.singleton = new PointerEventsPolyfill(options);
    return PointerEventsPolyfill.singleton;
};

// handle mouse events w/ support for pointer-events: none
PointerEventsPolyfill.prototype.register_mouse_events = function () {
    // register on all elements (and all future elements) matching the selector
    $(document).on(this.options.mouseEvents.join(" "), this.options.selector, function (e) {
        if ($(this).css('pointer-events') == 'none') {
            // peak at the element below
            var origDisplayAttribute = $(this).css('display');
            $(this).css('display', 'none');

            var underneathElem = document.elementFromPoint(e.clientX, e.clientY);

            if (origDisplayAttribute)
                $(this)
                    .css('display', origDisplayAttribute);
            else
                $(this).css('display', '');

            // fire the mouse event on the element below
            e.target = underneathElem;
            $(underneathElem).trigger(e);

            return false;
        }
        return true;
    });
};

$(document).on('mouseover', '#left-panel nav > ul > li > a', function () {
    $(this).parent().find('.dropdown').addClass('hovered');
});

$(document).on('mouseout', '#left-panel nav > ul > li > a', function () {
    $(this).parent().find('.dropdown').removeClass('hovered');
});

var ctrlPressed = false,
    shiftPressed = false;

$(document).keydown(function (event) {
    if (event.which == 16) {
        shiftPressed = true;
    } else if (event.which == 17) {
        ctrlPressed = true;
    }
    if (event.which == 13 && window.activePopup != undefined && window.activePopup && !window.activeChosen) {
        if (window.activePopup.hasClass("no-enter")) {
            return;
        }
        window.activePopup.find(".modal-footer .btn-primary").click();
    }
});

$(document).keyup(function () {
    ctrlPressed = false;
    shiftPressed = false;
});

$(document).on('mouseout', '#left-panel nav > ul > li > a', function () {
    $(this).parent().find('.dropdown').removeClass('hovered');
});

$(document).on('click', "#performanceDialog .quant-tabs .tabs-header > div", function () {
    $(this).parent().find("div").removeClass("active");
    $(this).addClass("active");
});
'use strict';

angular.module('app.login').controller('LoginController', function ($scope, $rootScope, $stateParams, $state, LoginService, AppService, usSpinnerService) {
    console.log("Login controller initialized.");
    
    //- Functions --------------------------------------------------------------
    
    function init(){
        $('#main-load-screen', window.parent.document).fadeOut('fast');

        $scope.showActionSpinner();

        //request is unsuccessful if remote access is disabled
        AppService.getRemoteAccessSettings(function(settings){
            $scope.hideActionSpinner();
            $scope.settingsLoaded = true;

            if(!settings){
                LoginService.setDisabled(true);
            }
            else {
                LoginService.setDisabled(!settings.allow);
                $scope.accessDisabled = LoginService.isDisabled();
                if(settings.allow){
                    $scope.login(true);
                }
            }
        });
    }

    $scope.login = function(dontShowError){
        $scope.showActionSpinner();

        LoginService.login($scope.credentials.password).then(function(result){
            $scope.hideActionSpinner();
            
            if(result.success){
                console.log("Logged in!"); 
                window.location.replace(window.location.origin);
            }
            else {
                if(!dontShowError){
                    $rootScope.showError("Login error", result.data.error);
                }
            }
        });
    }
    
    $scope.logout = function(){
        LoginService.logout();
    }
    
    //spinner functions
    $scope.showActionSpinner = function() {
        if (!$scope.spinneractive) {
            usSpinnerService.spin('spinner-login');
        }
    };

    $scope.hideActionSpinner = function() {
        if ($scope.spinneractive) {
            usSpinnerService.stop('spinner-login');
        }
    };

    $rootScope.showSuccess = function(title, message){
        if($scope.accessDisabled) return;

        $scope.errorDialog.title = title;
        $scope.errorDialog.message = message;
        $scope.errorDialog.isHtmlContent = true;

        try { $scope.$digest(); } catch(err){}
        showPopup("#errorDialog");
    }

    $rootScope.showError = function(title, message){
        if($scope.accessDisabled) return;

        $scope.errorDialog.title = title;
        $scope.errorDialog.message = message;
        $scope.errorDialog.isHtmlContent = true;

        try { $scope.$digest(); } catch(err){}
        showPopup("#errorDialog");
    }
    
    //- Event Handlers --------------------------------------------------------------
            
    $scope.$on('us-spinner:spin', function(event, key) {
        $scope.spinneractive = true;
    });

    $scope.$on('us-spinner:stop', function(event, key) {
        $scope.spinneractive = false;
    });
    
    //- Initialization --------------------------------------------------------------

    $scope.credentials = {};
    $scope.errorDialog = {};
    $scope.accessDisabled = true;
    $scope.settingsLoaded = false;
        
    $(".modal-backdrop").remove();

    init();

});
