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

.config(function ($stateProvider, $urlRouterProvider, $locationProvider, SQEventsProvider) {
    
    SQEventsProvider.add("SKIN_CHANGED", "skin-changed");
    SQEventsProvider.add("SHOW_INSTRUMENT", 'show-instrument');
    SQEventsProvider.add("OPEN_ABOUT_DIALOG", "open-about-dialog");
    
    $stateProvider
        .state('app', {
            abstract: false,
            url: '/',
            views: {
                root: {
                    templateUrl: '../SQMANAGER/layout/views/layout.html',
                    controller: 'LayoutCtrl'
                }
            },
            resolve: {
                tryLoadData: function(SQConstants){
                    if(!mainAppExists()){
                        return SQConstants.loadAll();
                    }
                },
                loadSkins: function(SkinService){
                    return SkinService.loadSkins();
                },
                connectWebSocket: function(SQWebSocketService){
                    return SQWebSocketService.connectWebSocket(location.port);
                }
            }
        });
        
    $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.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, sqPlugin, SQEvents, AppService, SQWebSocketService, SQConstants, SkinService, BackendService, DMDataService) {
    console.log("DataManager's Layout controller initialized");

    $scope.isQuantDataManager = isQuantDataManager();
    $scope.broker = SQConstants.getConstants().broker;
    $scope.isBrazilianEdition = SQConstants.getConstants().isBrazilianEdition;

    $rootScope.brEdition = "";
    if (SQConstants.getConstants().isBrazilianEdition) {
        $rootScope.brEdition = "br-edition";
    }

    $scope.mainTabs = {
        tabs: getPlugins(),
        onSelectTab: onTabChange,
        idPrefix: "dm-tabs",
    }

    function getPlugins() {
        var availablePlugins = sqPlugin.getPlugins("MainTab");
        var plugins = [];

        for (var i = 0; i < availablePlugins.length; i++) {
            var plugin = availablePlugins[i];

            if(isQuantDataManager()) {
                if(plugin.dataItem == 'sessions' || plugin.dataItem == 'custom-da-ta' || plugin.dataItem == 'baskets') continue;
            } else {
                if(plugin.dataItem == 'help') continue;
            }

            plugins.push(plugin);
        }      

        return plugins;
    }

    $scope.selectedMenu = 'add';

    $scope.ribbonActive = "data-sources";

    function onTabChange(tab) {
        //enable/disable actions based on source
        for (var key in $scope.actions) {
            var actions = $scope.actions[key];

            for (var i = 0; i < actions.length; i++) {
                var action = actions[i];

                if (Array.isArray(action)) {
                    for (var j = 0; j < action.length; j++) {
                        action[j].enabled = (action[j].source.indexOf(tab.dataItem) != -1);
                    }
                } else {
                    action.enabled = (action.source.indexOf(tab.dataItem) != -1);
                }
            }
        }

        if(tab.menuActive) {
            $scope.ribbonActive = tab.menuActive;
        }

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

    $scope.onSelectAction = function (action, item) {
        var tabIndex = $scope.mainTabs.getActiveTab().index;

        if (action.onSelect) {
            var data = $scope.mainTabs.tabs[tabIndex].getSelectedRows();

            action.onSelect(data.rows, data.grid, item);
        } else {
            $scope.mainTabs.tabs[tabIndex].callAction(action.key);
        }
    }

    function init() {
         if (SQConstants.getConstants().isBrazilianEdition){
            //find br buttons
            var plugins = sqPlugin.getPlugins("DataManagerActionTools");
            var brBtns = plugins.filter(i=>i.key=='brData' || i.key=='brDataUpdate');
            //add br buttoins to the first position
            console.log('brbuttons', brBtns);
            for(var i = 0;i<brBtns.length;i++){
                $scope.actions.firstTools.push(brBtns[i]);
            }
        }

        $scope.actions.dataSources.push(angular.copy(sqPlugin.getCombos("DataSourceDukascopy")));
        $scope.actions.dataSources.push(angular.copy(sqPlugin.getCombos("DataSourceTD")));
        $scope.actions.dataSources.push(angular.copy(sqPlugin.getCombos("DataSourceFiles")));

        if(isStrategyQuant()) {
            $scope.actions.dataSources.push(angular.copy(sqPlugin.getCombos("DataSourceSQEquityData")));
            $scope.actions.dataSources.push(angular.copy(sqPlugin.getCombos("DataSourceSQFuturesData")));
        }

        $scope.actions.dataSources.push(angular.copy(sqPlugin.getCombos("DataSourceDarwinex")));
        $scope.actions.dataSources.push(angular.copy(sqPlugin.getCombos("DataSourceCrypto")));
        $scope.actions.dataSources.push(angular.copy(sqPlugin.getCombos("DataSourceYahoo")));

        loadPlugins($scope.actions.exports, angular.copy(sqPlugin.getPlugins("DataManagerActionExport")));

        var actionTools = sqPlugin.getPlugins("DataManagerActionTools");
        actionTools = actionTools.filter(i=>i.key!='brData' && i.key!='brDataUpdate');
        loadPlugins($scope.actions.tools, angular.copy(actionTools));

        loadPlugins($scope.actions.instruments, angular.copy(sqPlugin.getPlugins("DataManagerActionInstrument")));

        loadPlugins($scope.actions.sessions, angular.copy(sqPlugin.getPlugins("DataManagerActionSession")));

        loadPlugins($scope.actions.customData, angular.copy(sqPlugin.getPlugins("DataManagerActionCustomData")));
		
        loadPlugins($scope.actions.baskets, angular.copy(sqPlugin.getPlugins("DataManagerActionBasket")));		
   
        loadPlugins($scope.actions.brokers, angular.copy(sqPlugin.getPlugins("DataManagerActionBroker")));	
    }

    function loadPlugins(array, plugins) {
        array.length = 0;

        for (var i = 0; i < plugins.length; i++) {
            let plugin = plugins[i];

            if(plugin.products && plugin.products.indexOf(window.top.appConfig.product) == -1) {
                continue;
            }

            array.push(plugin);
        }
    }

    $scope.actions = {
        dataSources: [],
        exports: [],
        tools: [],
        firstTools: [],
        instruments: [],
        sessions: [],
        customData: [],
		baskets: [],
        brokers: []
    }

    init();

    /*
    $timeout(function () {
        AppService.notifyAppLoaded();
    }, 1000);*/

    $scope.$on('$viewContentLoaded', function (event) {
        AppService.notifyAppLoaded();
    });

    function onWebSocketData(args) {
        if (args.notification) {
            var data = args.notification;

            if (data.message) {
                $rootScope.showErrorModal(data.title, data.message);

            } else if (data.error) {
                $rootScope.showError(data.error);

            }
        }
        
        if (args.DMConfirmation) {
            var data = args.DMConfirmation;

            $rootScope.showOptionsDialog(data.title, data.message, function (option) {
                BackendService.sendRequest("/data/confirm", {action: option.key});
            }, data.options, true);

            return;
        }

        if (args.DMDataProgresses) {
			var progresses = args.DMDataProgresses;
			for (var i = 0; i < progresses.length; i++) {
				var progress = progresses[i];

				if (progress.key=='TotalProgressSymbol'){
					$scope.progress = progress.pct;
					$scope.progressLabel = progress.message;
					
					if (progress.pct==100){
						$scope.progress = 0;
						$scope.progressLabel = ''
					}
				}			
			}

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

    SQWebSocketService.subscribeGeneral("DataManagerLayoutCtrl", onWebSocketData);

    function performAction(action) {
        console.log("DataManager - Performing action '" + action.name + "'.");

        if (action.name == 'openCDataIndy') {
            $scope.mainTabs.selectTab('custom-da-ta');
        }
    }

    $scope.batchActionPaused = false;

    $scope.batchAction = function(action) {
        if (
            action == "stop" &&
            !confirm(Ltsq("Do you really want to stop all?"))
        ) {
            return;
        }

        $scope.batchActionPaused = action == "pause";

        if (action == "pause") {
            DMDataService.pauseAll();
        } else if (action == "continue") {
            DMDataService.resumeAll();
        } else if (action == "stop") {
            DMDataService.stopAll();
        }
    };

    // QDM help iframe --------------------------------------------------------------------------
    function onEvent(event, data) {
        if (event == SQEvents.get('DATA_CHANGED')) {
            checkData();
        }
    }

    function onSkinChanged() {
        var skin = SkinService.selectedSkin.name;

        if (skin == 'Dark skin') {
            $("#iframe_qdm_no_data").contents().find('body').addClass('dark-skin');
        } else {
            $("#iframe_qdm_no_data").contents().find('body').removeClass('dark-skin');
        }
    }

    function checkData() {
        if (!isQuantDataManager()) {
            return;
        }

        $scope.noData = (SQConstants.getConstants().data && SQConstants.getConstants().data.length == 0);

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

        positionIframeHelp();
    }

    $(window).on("resize", function () {
        positionIframeHelp();
    });

    $("#iframe_qdm_no_data").on("load", function () {
        onSkinChanged();
    });

    function positionIframeHelp() {
        if (!isQuantDataManager()) {
            return;
        }

        var sqGrid = $(".datamanager-main-tabs > .tabs-body > :first-child.active .sq-grid");

        if (sqGrid && sqGrid.length > 0) {
            var sqGridDimensions = sqGrid.offset();
            var sqDMDimensions = $(".sq-app-datamanager").offset();
            var topPos = sqGridDimensions.top + sqDMDimensions.top + 25;
            $("#iframe_qdm_no_data").css("top", topPos + "px").css("left", (11) + "px").css("width", (sqGrid[0].offsetWidth - 2) + "px").css("height", (sqGrid[0].offsetHeight - 26) + "px").addClass("shownReally");
        } else {
            $("#iframe_qdm_no_data").removeClass("shownReally");
        }
    }
    SQEvents.addListener("DataManager", [SQEvents.get('DATA_CHANGED')], onEvent);

    if (isQuantDataManager()) {
        window.parent.addListener("DataManagerSkin", [SQEvents.get("SKIN_CHANGED")], onSkinChanged);
        onSkinChanged();
    } else {
        window.parent.addListener("LayoutCtrl-" + window.appConfig.appCode, [SQEvents.get('APP_SWITCHED'), SQEvents.get("ACTION_REQUEST")], function (event, data) {
            if (event == SQEvents.get('APP_SWITCHED') && data == window.appConfig.product) {
                AppService.onAppSwitched();
            } 
            else if (event == SQEvents.get("ACTION_REQUEST") && data.productCode == window.appConfig.product) {
                performAction(data.action);
            }
        });
    }

    $scope.noData = false;
	$scope.progress=0;
	$scope.progressLabel='';

    checkData();
    //---------------------------------------------------------------------------------------------

    $scope.showDownloadCountConfig = function() {
        $scope.cdnAllowed = AppService.isProVersion();

        showPopup("#downloadCountModal");
    };

    $scope.parallelDownload = { common: 1, cdn: 1, cdnType: "cdn" };

    $scope.parallelDownloadChanged = function() {
        SQConstants.getSettings().cdnPreferred =
            $scope.parallelDownload.cdnType;

        DMDataService.setParallelDownload(
            $scope.parallelDownload.common,
            $scope.parallelDownload.cdn,
            $scope.parallelDownload.cdnType
        );
    };

    DMDataService.getParallelDownload(function(result) {
        $scope.parallelDownload.common = result.parallelDownload;
        $scope.parallelDownload.cdn = result.cdnParallelDownload;
        $scope.parallelDownload.cdnType = result.cdnPreferred;

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

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

$(window).on('resize', function () {
    autoSizeTabContents();
});

function autoSizeTabContents() {}

$(document).on("click", '#left-panel nav a', function (e) {
    var parentLiObj = $(this).closest('li');

    if (parentLiObj.hasClass('nav-root')) {
        //if collapsing menu item, don't set it active
        if (parentLiObj.hasClass('has-submenu')) return;
    }

    $('#left-panel nav a.active').removeClass('active');
    $(this).addClass('active');

    e.stopPropagation();
});

$(document).on("click", '#left-panel nav .arrow-down', function (e) {
    var parentItem = $(this).closest('li');
    parentItem.toggleClass('menu-opened');

    e.stopPropagation();
});

function selectFirstSubItem(liObj) {
    var aObj = liObj.find('li a')[0];

    if (liObj.find('.submenu').length) {
        if ($('body').hasClass('menu-reduced')) return;

        setTimeout(function () {
            aObj.click(); //select first subitem
        }, 200);
        return;
    }
}

$(document).on("click", '.btn-reduce-menu', function () {
    $('body').toggleClass('menu-reduced');
});

function tabsShowHiddenTabs() {
    return;
    $('.quant-tabs').each(function () {
        $(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", '.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');
});

function tabsShowHiddenTabs() {
    $('.quant-tabs').each(function () {
        $(this).children('.tabs-header').children('div').removeAttr('style');
        var tabsHeaderRect = $(this).children('.tabs-header')[0].getBoundingClientRect();
        var tabsHeaderRight = tabsHeaderRect.right;
        var tabsHeaderBottom = tabsHeaderRect.top + $(this).find('.tabs-header .active').outerHeight();
        var tabsHidden = [];
        var tabsHidden2 = [];
        $(this).children('.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).children('.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).children('.tabs-header').append($tabsMenu);
        }
    });
}

$(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();
});

$(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');
});
$(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();

});
