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