/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    angular.module('app.unknown', ['ngNewRouter'])
        .controller('UnknownController', ['$rootScope', '$http', '$router', '$location', '$timeout', '$window', 'authenticationService', 'ngAuthSettings', 'cfpLoadingBar', '$mdDialog', '$translate', UnknownController]);
    function UnknownController($rootScope, $http, $router, $location, $timeout, $window, authenticationService, ngAuthSettings, cfpLoadingBar, $mdDialog, $translate) {
        var $self = this;
        this.loginData = {
            userName: "",
            password: "",
            useRefreshTokens: false,
            unknown: true
        };
        this.isNational = IsNationalLogin;
        this.logo;
        this.requiredClass = false;
        this.message = "";
        this.disableSubmit = false;
        this.showPassword = false;
        this.emailFormat = App.Global.EmailValidationRegEx;
        // Set the default value of inputType
        this.passwordInputType = 'password';
        // Hide & show password function
        this.hideShowPassword = function () {
            if ($self.passwordInputType == 'password')
                $self.passwordInputType = 'text';
            else
                $self.passwordInputType = 'password';
        };
        this.forgotpass = function () {
            $router.parent.navigate('/forgotpassword');
        };
        this.gotonatnlsignup = function (form) {
            var cs = new App.ClientService($http);
            cs.GetNationalClientCallLetters(ClientCallLetters).then(function (callLetters) {
                $window.location.href = '/' + callLetters + '#!/signup';
            });
        };
        this.login = function (form) {
            var _this = this;
            this.disableSubmit = true;
            //Validate
            if (form.$invalid) {
                this.requiredClass = true;
                this.disableSubmit = false;
                if (form.emailInput.$error.pattern == true) {
                    App.Helper.ShowTranslatedAlert("Please enter a valid e-mail address.", this, $mdDialog, $translate);
                }
                else {
                    App.Helper.ShowTranslatedAlert('Please fill out all of the required fields.', this, $mdDialog, $translate);
                }
                return false;
            }
            else {
                this.message = "";
                this.requiredClass = false;
            }
            authenticationService.login(this.loginData).then(function (response) {
                if (response.subscribedToNational == 'False') {
                    var ps = new App.ParticipantService($http);
                    ps.GetParticipantInfo(App.Global.Participant.ID).then(function (data) {
                        data.Password = null;
                        data.ID = 0;
                        data.ClientID = response.data.clientID;
                        var participant = response.data.callLetters + 'participant';
                        window.localStorage.setItem(participant, JSON.stringify(data));
                        $window.location.href = '/' + response.data.callLetters + '#!/signup';
                    });
                }
                else {
                    App.Helper.LoadParticipantData(App.Helper.GetParticipantDataFromAuth(response));
                    //authorizationdata
                    var authorizationdata = response.data.callLetters + 'authorizationdata';
                    window.localStorage.setItem(authorizationdata, JSON.stringify(App.Global.AuthorizationData));
                    //participant
                    var participant = response.data.callLetters + 'participant';
                    window.localStorage.setItem(participant, JSON.stringify(App.Global.Participant));
                    //authenticated
                    var authenticated = response.data.callLetters + 'authenticated';
                    window.localStorage.setItem(authenticated, App.Global.Authenticated);
                    if (App.Global.Participant.CompleteRegistration == false)
                        $window.location.href = '/' + response.data.callLetters + '#!/radiohabits';
                    else if (App.Global.Participant.ForceRescreen == true)
                        $window.location.href = '/' + response.data.callLetters + '#!/signup';
                    else
                        $window.location.href = '/' + response.data.callLetters + '#!/home';
                }
            }, function (err) {
                console.log("unknown error B");
                _this.disableSubmit = false;
                if (err != null && err.data != null && err.data.error_description != null)
                    _this.message = err.data.error_description;
            });
        };
        this.change = function () {
            $self.message = "";
        };
        this.placeholderText = "";
        this.focus = function (event) {
            $self.placeholderText = event.target.placeholder;
            event.target.placeholder = "";
            return true;
        };
        this.blur = function (event) {
            event.target.placeholder = $self.placeholderText;
            return true;
        };
        this.authExternalProvider = function (provider) {
            console.log(location);
            '/' + location.pathname.split('/')[1];
            var sitepath = '';
            var paths = location.pathname.split('/');
            for (var i = 0; i < (paths.length - 1); i++) {
                if (paths[i] != null && paths[i] != '')
                    sitepath = sitepath + '/' + paths[i];
            }
            var redirectUri = location.protocol + '//' + location.host + sitepath + '/authcomplete';
            var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
                + "&response_type=token&client_id=" + ngAuthSettings.appClientID
                + "&call_letters=" + ngAuthSettings.clientCallLetters
                + "&redirect_uri=" + redirectUri;
            window.$unknownWindowScope = this;
            window.localStorage.setItem('exloginlocationhref', window.location.href);
            window.location.href = externalProviderUrl;
            //var oauthWindow = window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0");
        };
        this.authCompletedCB = function (fragment) {
            var _this = this;
            if (App.Global.Participant == null)
                App.Global.Participant = {};
            App.Global.Participant.ExternalAuthData = {
                Provider: fragment.provider,
                UserName: fragment.external_user_name,
                ExternalAccessToken: fragment.external_access_token
            };
            if (fragment.haslocalaccount == 'False') {
                //if no local account is found - redirect to register with external credentials.
                //authenticationService.logOut();
                if (fragment.email != null)
                    App.Global.Participant.EMail = fragment.email;
                if (fragment.first_name != null)
                    App.Global.Participant.FirstName = fragment.first_name;
                if (fragment.last_name != null)
                    App.Global.Participant.LastName = fragment.last_name;
                $timeout(function () { $location.path('/signup'); }, 500);
            }
            else {
                //Obtain access token and redirect to home
                var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token };
                authenticationService.obtainAccessToken(externalData).then(function (response) {
                    var ps = new App.ParticipantService($http);
                    ps.GetBasicParticipantInfo(App.Global.Participant.ID).then(function (data) {
                        App.Helper.LoadParticipantDataAndRedirect(data, $location);
                    });
                }, function (err) {
                    console.log("unknown error A");
                    _this.disableSubmit = false;
                    if (err != null && err.data != null && err.data.error_description != null)
                        _this.message = err.data.error_description;
                });
            }
        };
        function activate() {
            var authFragment = window.localStorage.getItem('authfragment');
            if (authFragment != null && authFragment != '') {
                window.localStorage.setItem('authfragment', '');
                $self.authCompletedCB(JSON.parse(authFragment));
                return;
            }
            //cfpLoadingBar.latencyThreshold = 10000;
            //Set the logo data here
            if (App.Helper.LoadingClientPromise == null) {
                if (App.Global.Client != null && App.Global.Client.Theme != null)
                    $self.logo = App.Global.Client.Theme.LogoPath != null ? App.Global.Client.Theme.LogoPath : "Images/tam.png"; //if there is theme load from them
                else
                    $self.logo = (App.Global.Client != null && App.Global.Client.LogoPath != null) ? App.Global.Client.LogoPath : "Images/tam.png"; //if no theme - load the client logo
            }
            else {
                App.Helper.LoadingClientPromise.then(function () {
                    if (App.Global.Client != null && App.Global.Client.Theme != null)
                        $self.logo = App.Global.Client.Theme.LogoPath != null ? App.Global.Client.Theme.LogoPath : "Images/tam.png"; //if there is theme load from them
                    else
                        $self.logo = (App.Global.Client != null && App.Global.Client.LogoPath != null) ? App.Global.Client.LogoPath : "Images/tam.png"; //if no theme - load the client logo
                });
            }
            var rememberedUserName = authenticationService.getUserName();
            if (rememberedUserName != null) {
                $self.loginData.userName = rememberedUserName;
                $self.loginData.useRefreshTokens = true;
            }
            if (App.Global.Authenticated) {
                if ($self.loginData.useRefreshTokens) {
                    authenticationService.refreshToken().then(function () {
                        if (App.Global.Authenticated) {
                            //authenticationService.fillAuthData();
                            App.Helper.GoToHome();
                        }
                    });
                }
                else {
                    authenticationService.logOut();
                }
            }
            //cfpLoadingBar.latencyThreshold = 100;
            cfpLoadingBar.complete();
        }
        ;
        activate();
    }
})(App || (App = {}));
//# sourceMappingURL=unknown.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
var App;
(function (App) {
    var BannerController = /** @class */ (function () {
        function BannerController($window, $scope) {
            this.activate($scope);
            this.$window = $window;
        }
        BannerController.prototype.activate = function ($scope) {
            $scope.banner.widthOrHeight = $(window).innerWidth() > 600 ? 'height' : 'width';
            $(window).on("resize.doResize", App.Helper.Debounce(function () {
                $scope.$apply(function () {
                    //dapply updates
                    $scope.banner.widthOrHeight = $(window).innerWidth() > 600 ? 'height' : 'width';
                });
            }, 200, $scope));
            this.loadTheme();
        };
        BannerController.prototype.loadTheme = function () {
            var _this = this;
            if (App.Helper.LoadingClientPromise != null)
                App.Helper.LoadingClientPromise.then(function () {
                    _this.applyTheme();
                });
            else {
                this.applyTheme();
            }
        };
        BannerController.prototype.applyTheme = function () {
            if (App.Global.Client == null || App.Global.Client.Theme == null)
                return;
            //banners
            if (App.Global.Client.Theme.Banner1Path != null)
                this.one = App.Global.Client.Theme.Banner1Path;
            if (App.Global.Client.Theme.Banner2Path != null)
                this.two = App.Global.Client.Theme.Banner2Path;
            if (App.Global.Client.Theme.Banner3Path != null)
                this.three = App.Global.Client.Theme.Banner3Path;
            //links
            if (App.Global.Client.Theme.BannerLink1 != null)
                this.onelink = App.Global.Client.Theme.BannerLink1;
            if (App.Global.Client.Theme.BannerLink2 != null)
                this.twolink = App.Global.Client.Theme.BannerLink2;
            if (App.Global.Client.Theme.BannerLink3 != null)
                this.threelink = App.Global.Client.Theme.BannerLink3;
        };
        BannerController.prototype.openlinkone = function () {
            if (this.onelink != null) {
                this.$window.open('http://' + this.onelink, '_blank');
            }
        };
        BannerController.prototype.openlinktwo = function () {
            if (this.twolink != null)
                this.$window.open('http://' + this.twolink, '_blank');
        };
        BannerController.prototype.openlinkthree = function () {
            if (this.threelink != null)
                this.$window.open('http://' + this.threelink, '_blank');
        };
        BannerController.$inject = ['$window', '$scope'];
        return BannerController;
    }());
    App.BannerController = BannerController;
    ;
    function BannerDirective() {
        return {
            scope: {},
            restrict: 'EA',
            controller: BannerController,
            controllerAs: 'banner',
            bindToController: true,
            templateUrl: 'components/banner/banner.html'
        };
    }
    ;
    angular.module('app.banner', [])
        .controller('BannerController', BannerController)
        .directive('banner', BannerDirective);
})(App || (App = {}));
//# sourceMappingURL=banner.js.map;
'use strict';
var App;
(function (App) {
    var HeaderController = /** @class */ (function () {
        function HeaderController($http, $location, $timeout) {
            this.showMenu = true;
            this.showLogo = true;
            this.doubleLine = false;
            this.authenticated = false;
            this.showMenu = true;
            this.showLogo = true;
            this.doubleLine = false;
            this.$location = $location;
            this.loadTheme();
            if (App.Global != null && App.Global.Authenticated != null)
                this.authenticated = App.Global.Authenticated;
            else
                this.authenticated = false;
        }
        HeaderController.prototype.loadTheme = function () {
            var _this = this;
            if (App.Helper.LoadingClientPromise != null)
                App.Helper.LoadingClientPromise.then(function () {
                    _this.applyTheme();
                });
            else {
                this.applyTheme();
            }
        };
        HeaderController.prototype.applyTheme = function () {
            var _this = this;
            if (App.Helper.LoadingClientPromise == null) {
                if (App.Global.Client != null && App.Global.Client.Theme != null)
                    this.logo = App.Global.Client.Theme.LogoPath != null ? App.Global.Client.Theme.LogoPath : "Images/tam.png"; //if there is theme load from them
                else
                    this.logo = (App.Global.Client != null && App.Global.Client.LogoPath != null) ? App.Global.Client.LogoPath : "Images/tam.png"; //if no theme - load the client logo
                this.slogan = (App.Global.Client != null && App.Global.Client.Slogan != null) ? App.Global.Client.Slogan : "";
            }
            else {
                App.Helper.LoadingClientPromise.then(function () {
                    if (App.Global.Client != null && App.Global.Client.Theme != null)
                        _this.logo = App.Global.Client.Theme.LogoPath != null ? App.Global.Client.Theme.LogoPath : "Images/tam.png"; //if there is theme load from them
                    else
                        _this.logo = (App.Global.Client != null && App.Global.Client.LogoPath != null) ? App.Global.Client.LogoPath : "Images/tam.png"; //if no theme - load the client logo
                    _this.slogan = (App.Global.Client != null && App.Global.Client.Slogan != null) ? App.Global.Client.Slogan : "";
                });
            }
        };
        HeaderController.prototype.navigateHome = function () {
            if (!this.authenticated) {
                App.Helper.GoToLogin();
            }
            else if (this.showMenu) {
                this.$location.path('/home');
            }
        };
        HeaderController.prototype.activate = function ($scope) {
            var _this = this;
            this.loadTheme();
            if (ClientCallLetters.toLowerCase() == 'personalinfo') {
                this.showMenu = false;
            }
            if (this.showMenu == true) {
                this.showMenu = (this.$location.$$path.indexOf("survey") < 0) && (this.$location.$$path.indexOf("unknown") < 0); // hide the menu if we are in a survey or if an u
            }
            if (this.showMenu == true) {
                if (App.Global.Participant != null && (App.Global.Participant.ForceRescreen == true || App.Global.Participant.CompleteRegistration == false))
                    this.showMenu = false;
            }
            this.doubleLine = (ClientCallLetters.toLowerCase() == 'ihmmm');
            $scope.$watch(function () {
                return ($scope.header.showLogo != ($scope.header.$location.$$path.indexOf("login") < 0));
            }, function () {
                $scope.header.showLogo = ($scope.header.$location.$$path.indexOf("login") < 0) && (ClientCallLetters.toLowerCase() != 'iphone7'); // hide the logo if on login page
                if (!$scope.$$phase) {
                    //$digest or $apply
                    $scope.$apply();
                }
            });
            $scope.$watch(function () {
                return $scope.header.showMenu != (_this.$location.$$path.indexOf("survey") < 0)
                    && (_this.$location.$$path.indexOf("unknown") < 0)
                    && !(App.Global.Participant != null && (App.Global.Participant.ForceRescreen == true || App.Global.Participant.CompleteRegistration == false))
                    && ClientCallLetters.toLowerCase() != 'personalinfo';
            }, function () {
                $scope.header.showMenu = (_this.$location.$$path.indexOf("survey") < 0)
                    && (_this.$location.$$path.indexOf("unknown") < 0)
                    && !(App.Global.Participant != null && (App.Global.Participant.ForceRescreen == true || App.Global.Participant.CompleteRegistration == false))
                    && ClientCallLetters.toLowerCase() != 'personalinfo';
            });
        };
        ;
        return HeaderController;
    }());
    App.HeaderController = HeaderController;
    angular.module('app.header', [])
        .controller('HeaderController', ['$http', '$location', '$timeout', HeaderController]);
})(App || (App = {}));
//# sourceMappingURL=header.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
var App;
(function (App) {
    var FooterController = /** @class */ (function () {
        function FooterController($http, $translate, $mdDialog, $sce, $location, $window) {
            this.date = new Date();
            this.oldFooter = false;
            this.showDoNotSell = true;
            this.showUnsubscribe = true;
            this.address = null;
            this.contact = null;
            this.showLink = false;
            this.localLink = null; //'https://www.cnn.com';
            this.localLinkText = null; //'this is a test';
            this.themeStyle = { 'color': '#f2f2f2', '-webkit-text-fill-color': '#f2f2f2' };
            this.$http = $http;
            this.$translate = $translate;
            this.$mdDialog = $mdDialog;
            this.$sce = $sce;
            this.$location = $location;
            this.$window = $window;
        }
        FooterController.prototype.$onInit = function () {
            this.authenticated = App.Global.Authenticated;
            this.mmode = this.menumode != null ? this.menumode : false;
            this.loadTheme();
        };
        FooterController.prototype.activate = function ($scope) {
            if (ClientCallLetters.toLowerCase() == 'personalinfo') {
                this.showUnsubscribe = false;
            }
            //else {
            //    this.showUnsubscribe = true;
            //}
            this.loadTheme();
            $scope.$watch(function () {
                return $scope.footer.authenticated != App.Global.Authenticated;
            }, function () {
                $scope.footer.authenticated = App.Global.Authenticated;
                if (!$scope.$$phase) {
                    $scope.$apply();
                }
            });
        };
        FooterController.prototype.loadTheme = function () {
            var _this = this;
            if (App.Helper.LoadingClientPromise != null)
                App.Helper.LoadingClientPromise.then(function () {
                    _this.applyTheme();
                });
            else {
                this.applyTheme();
            }
        };
        FooterController.prototype.applyTheme = function () {
            this.localLink = App.Global.Client.localLink;
            this.localLinkText = App.Global.Client.localLinkText;
            if (this.localLink.length > 0 && this.localLinkText.length > 0) {
                this.showLink = true;
            }
            if (App.Global.Client == null || App.Global.Client.Theme == null) {
                this.themeStyle.color = '#FFF';
                return;
            }
            if (App.Global.Client.Theme.FontColor != null)
                this.themeStyle.color = '#' + App.Global.Client.Theme.FontColor;
            //this information will not be shown in the footer for now.
            //this.address = App.Global.Client.Address; 
            //this.contact = App.Global.Client.Contact;
        };
        FooterController.prototype.showDisclaimer = function () {
            var _this = this;
            var year = this.date.getFullYear();
            if (year < 2020) {
                this.$translate('Privacy Policy').then(function (tr) {
                    _this.$mdDialog.show({
                        controller: App.DisclaimerpopupController,
                        templateUrl: 'components/disclaimerpopup/disclaimerpopup.html',
                        parent: angular.element(document.body),
                        locals: {
                            name: 'Test All Media ' + tr,
                            clientid: undefined,
                            $http: _this.$http,
                            $location: _this.$location,
                            $sce: _this.$sce
                        }
                    })
                        .then(function (answer) { }, function () { });
                });
            }
            else {
                this.$window.open(PrivacyPolicyUrl, '_blank');
            }
        };
        FooterController.prototype.showTOU = function () {
            this.$window.open("https://marketing.testallmedia.com/terms-of-use/", '_blank');
        };
        FooterController.prototype.redirectLocalLink = function () {
            this.$window.open(this.localLink, '_blank');
        };
        FooterController.$inject = ['$http', '$translate', '$mdDialog', '$sce', '$location', '$window'];
        return FooterController;
    }());
    App.FooterController = FooterController;
    ;
    function FooterDirective() {
        return {
            scope: {
                menumode: '=',
            },
            restrict: 'EA',
            controller: FooterController,
            controllerAs: 'footer',
            bindToController: true,
            templateUrl: 'components/footer/footer.html'
        };
    }
    ;
    angular.module('app.footer', [])
        .controller('FooterController', FooterController)
        .directive('footer', FooterDirective);
})(App || (App = {}));
//# sourceMappingURL=footer.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
var App;
(function (App) {
    var BlankfooterController = /** @class */ (function () {
        function BlankfooterController() {
        }
        BlankfooterController.prototype.$onInit = function () {
        };
        BlankfooterController.prototype.activate = function ($scope) {
        };
        BlankfooterController.$inject = [];
        return BlankfooterController;
    }());
    App.BlankfooterController = BlankfooterController;
    ;
    angular.module('app.blankfooter', [])
        .controller('BlankfooterController', BlankfooterController);
})(App || (App = {}));
//# sourceMappingURL=blankfooter.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
var App;
(function (App) {
    var MainmenuController = /** @class */ (function () {
        function MainmenuController($http, authenticationService, $translate, $sce, $mdDialog, $location, $anchorScroll, $window) {
            this.themeStyle = { color: 'inherit', background: 'inherit' };
            this.themeControlStyle = { color: 'inherit', background: 'inherit' };
            this.themeHeaderStyle = { color: 'inherit', background: 'inherit' };
            this.logout = function () {
                this.authenticationService.logOut();
                App.Helper.GoToLogin();
            };
            this.goToLogin = function () {
                App.Helper.GoToLogin(true);
            };
            this.authenticated = App.Global.Authenticated;
            this.participant = App.Global.Participant;
            this.authenticationService = authenticationService;
            this.$http = $http;
            this.$mdDialog = $mdDialog;
            this.$translate = $translate;
            this.$window = $window;
            this.$sce = $sce;
            this.$location = $location;
            this.limitedProfile = false; //App.Global.Client.LimitedParticipantProfile;
            this.showPreferences = false;
            this.showTopSongs = false;
            var date = new Date();
            this.showDoNotSell = date.getFullYear() != 2019;
            this.loadTheme();
        }
        MainmenuController.prototype.activate = function ($scope) {
            var _this = this;
            this.loadTheme();
            this.loadParticipantData($scope);
            $scope.$watch(function () {
                return $scope.mainmenu.authenticated != App.Global.Authenticated;
            }, function () {
                $scope.mainmenu.authenticated = App.Global.Authenticated;
                _this.loadParticipantData($scope);
            });
        };
        MainmenuController.prototype.loadParticipantData = function ($scope) {
            var _this = this;
            if (App.Global.Participant != null && App.Global.Authenticated) {
                if (App.Global.Participant.Name == null || App.Global.Participant.EMail == null) {
                    var ps = new App.ParticipantService(this.$http);
                    ps.GetBasicParticipantInfo(App.Global.Participant.ID).then(function (data) {
                        _this.participant = App.Helper.LoadParticipantData(data);
                        //refresh the view if it is not laready refreshing
                        if (!$scope.$$phase) {
                            $scope.$apply();
                        }
                    });
                }
                else {
                    this.participant = App.Global.Participant;
                    //refresh the view if it is not laready refreshing
                    if (!$scope.$$phase) {
                        $scope.$apply();
                    }
                }
            }
        };
        MainmenuController.prototype.loadTheme = function () {
            var _this = this;
            if (App.Helper.LoadingClientPromise != null)
                App.Helper.LoadingClientPromise.then(function () {
                    _this.applyTheme();
                    _this.loadOptionalPages();
                });
            else {
                this.applyTheme();
                this.loadOptionalPages();
            }
        };
        MainmenuController.prototype.loadOptionalPages = function () {
            if (App.Global.Client != null) {
                this.limitedProfile = App.Global.Client.LimitedParticipantProfile;
                this.showPreferences = App.Global.Client.ShowPreferencesPage;
                this.showMontages = App.Global.Client.ShowMontagesPage;
                this.showTopSongs = App.Global.Client.ShowTopSongs;
            }
        };
        MainmenuController.prototype.applyTheme = function () {
            if (App.Global.Client == null || App.Global.Client.Theme == null) {
                this.themeStyle.color = '#FFF';
                this.themeHeaderStyle.color = '#FFF';
                this.displayRadioHabits = false;
                return;
            }
            this.displayRadioHabits = App.Global.Client.DisplayRadioHabits && (App.Global.Client.LimitedParticipantProfile == false);
            if (App.Global.Client.Theme.BackgroundColor != null)
                this.themeStyle.background = '#' + App.Global.Client.Theme.BackgroundColor;
            if (App.Global.Client.Theme.FontColor != null)
                this.themeStyle.color = '#' + App.Global.Client.Theme.FontColor;
            if (App.Global.Client.Theme.ControlFontColor != null)
                this.themeControlStyle.color = '#' + App.Global.Client.Theme.ControlFontColor;
            if (App.Global.Client.Theme.HeaderBackgroundColor != null)
                this.themeHeaderStyle.background = '#' + App.Global.Client.Theme.HeaderBackgroundColor;
            if (App.Global.Client.Theme.HeaderFontColor != null)
                this.themeHeaderStyle.color = '#' + App.Global.Client.Theme.HeaderFontColor;
            if (App.Global.Client.Theme.HeaderFont != null)
                this.themeHeaderStyle["font-family"] = App.Global.Client.Theme.HeaderFont;
            if (App.Global.Client.Theme.HeaderFontSize != null)
                this.themeHeaderStyle["font-size"] = App.Global.Client.Theme.HeaderFontSize + 'px';
        };
        ;
        MainmenuController.prototype.redirectDoNotSellInfo = function () {
            this.$window.open(DoNotSellInfoUrl, '_blank');
        };
        ;
        MainmenuController.prototype.showDisclaimer = function () {
            var _this = this;
            var date = new Date();
            var year = date.getFullYear();
            if (year < 2020) {
                this.$translate('Privacy Policy').then(function (tr) {
                    _this.$mdDialog.show({
                        controller: MenupopupdisclaimerController,
                        templateUrl: 'components/mainmenu/menupopupdisclaimer.html',
                        parent: angular.element(document.body),
                        locals: {
                            name: 'Test All Media ' + tr,
                            clientid: undefined,
                            $http: _this.$http,
                            $location: _this.$location,
                            $sce: _this.$sce
                        }
                    })
                        .then(function (answer) { }, function () { });
                });
            }
            else {
                this.$window.open(PrivacyPolicyUrl, '_blank');
            }
        };
        MainmenuController.$inject = ['$http', 'authenticationService', '$translate', '$sce', '$mdDialog', '$location', '$anchorScroll', '$window'];
        return MainmenuController;
    }());
    App.MainmenuController = MainmenuController;
    function MenupopupdisclaimerController($scope, $mdDialog, name, clientid, $http, $location, $sce) {
        $scope.name = name;
        $scope.showinvalid = false;
        $scope.clientid = clientid;
        $scope.$http = $http;
        $scope.$location = $location;
        $scope.$sce = $sce;
        $scope.data = "";
        $scope.cancel = function () {
            $scope.$location.hash('');
            $mdDialog.cancel();
        };
        $scope.scrollTo = function (event) {
            var location;
            var item = event.target;
            while (item != undefined && location == undefined) {
                if (item.attributes.scrolltarget == undefined)
                    item = item.parentNode;
                else
                    location = item.attributes.scrolltarget.value;
            }
            //$scope.$location.hash(location);
            //App.Helper.GoToAnchor(location);
            $location.hash(location);
        };
        var activate = function () {
            if ($scope.clientid != undefined) {
                //Get client disclaimer
                var cs = new App.ClientService($scope.$http);
                cs.GetClientDisclaimer($scope.clientid).then(function (data) {
                    $scope.data = $scope.$sce.trustAsHtml(data.split("href=\"#").join("ng-click=scrollTo($event) scrolltarget=\""));
                    if (!$scope.$$phase) {
                        $scope.$apply();
                    }
                });
            }
            else {
                //Get system disclaimer
                var ss = new App.SystemService($scope.$http);
                ss.GetDisclaimer().then(function (data) {
                    $scope.data = $scope.$sce.trustAsHtml(data.split("href=\"#").join("ng-click=scrollTo($event) scrolltarget=\""));
                    //$scope.data = $scope.$sce.trustAsHtml(data.split("href=\"#terms024\"").join("href=\"##terms024\" My-Bind-Once target=\"_self\"").split("name=\"terms024\"").join("id=\"terms024\""));
                    //$scope.data = $scope.$sce.trustAsHtml(data);
                    if (!$scope.$$phase) {
                        $scope.$apply();
                    }
                });
            }
        };
        activate();
    }
    angular.module('app.mainmenu', [])
        .controller('MainmenuController', MainmenuController);
})(App || (App = {}));
//# sourceMappingURL=mainmenu.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
var App;
(function (App) {
    var MenubarController = /** @class */ (function () {
        function MenubarController($http, authenticationService, $translate, $sce, $mdDialog, $location, $anchorScroll) {
            this.disableInkBar = true;
            this.currentNavItem = 'login';
            this.themeStyle = { color: 'inherit', background: 'inherit' };
            this.themeControlStyle = { color: 'inherit', background: 'inherit' };
            this.themeHeaderStyle = { color: 'inherit', background: 'inherit' };
            this.logout = function () {
                this.authenticationService.logOut();
                App.Helper.GoToLogin();
            };
            this.goToLogin = function () {
                App.Helper.GoToLogin(true);
            };
            this.authenticated = App.Global.Authenticated;
            this.participant = App.Global.Participant;
            this.authenticationService = authenticationService;
            this.$http = $http;
            this.$mdDialog = $mdDialog;
            this.$translate = $translate;
            this.$sce = $sce;
            this.$location = $location;
            this.limitedProfile = false;
            this.showPreferences = false;
            this.showTopSongs = false;
            this.loadTheme();
        }
        MenubarController.prototype.activate = function ($scope) {
            this.loadTheme();
            //this.loadParticipantData($scope);
            $scope.$watch(function () {
                return $scope.menubar.authenticated != App.Global.Authenticated;
            }, function () {
                $scope.menubar.authenticated = App.Global.Authenticated;
                $scope.menubar.loadParticipantData($scope);
            });
        };
        MenubarController.prototype.loadParticipantData = function ($scope) {
            if (App.Global.Participant != null && App.Global.Authenticated) {
                if (App.Global.Participant.Name == null || App.Global.Participant.EMail == null) {
                    var ps = new App.ParticipantService(this.$http);
                    ps.GetBasicParticipantInfo(App.Global.Participant.ID).then(function (data) {
                        $scope.menubar.participant = App.Helper.LoadParticipantData(data);
                        if (!$scope.$$phase) {
                            $scope.$apply();
                        }
                    });
                }
                else {
                    $scope.menubar.participant = App.Global.Participant;
                    if (!$scope.$$phase) {
                        $scope.$apply();
                    }
                }
            }
        };
        MenubarController.prototype.loadTheme = function () {
            var _this = this;
            if (App.Helper.LoadingClientPromise != null)
                App.Helper.LoadingClientPromise.then(function () {
                    _this.applyTheme();
                    _this.loadOptionalPages();
                });
            else {
                this.applyTheme();
                this.loadOptionalPages();
            }
        };
        MenubarController.prototype.loadOptionalPages = function () {
            if (App.Global.Client != null) {
                this.limitedProfile = App.Global.Client.LimitedParticipantProfile;
                this.showPreferences = App.Global.Client.ShowPreferencesPage;
                this.showMontages = App.Global.Client.ShowMontagesPage;
                this.showTopSongs = App.Global.Client.ShowTopSongs;
            }
        };
        MenubarController.prototype.applyTheme = function () {
            if (App.Global.Client == null || App.Global.Client.Theme == null) {
                if (this.themeStyle != null)
                    this.themeStyle.color = '#FFF';
                if (this.themeHeaderStyle != null)
                    this.themeHeaderStyle.color = '#FFF';
                this.displayRadioHabits = false;
                return;
            }
            this.displayRadioHabits = App.Global.Client.DisplayRadioHabits && (App.Global.Client.LimitedParticipantProfile == false);
            if (App.Global.Client.Theme.BackgroundColor != null)
                if (this.themeStyle != null)
                    this.themeStyle.background = '#' + App.Global.Client.Theme.BackgroundColor;
            if (App.Global.Client.Theme.FontColor != null)
                if (this.themeStyle != null)
                    this.themeStyle.color = '#' + App.Global.Client.Theme.FontColor;
            if (App.Global.Client.Theme.ControlFontColor != null)
                if (this.themeControlStyle != null)
                    this.themeControlStyle.color = '#' + App.Global.Client.Theme.ControlFontColor;
            if (this.themeHeaderStyle != null) {
                if (App.Global.Client.Theme.HeaderBackgroundColor != null)
                    this.themeHeaderStyle.background = '#' + App.Global.Client.Theme.HeaderBackgroundColor;
                if (App.Global.Client.Theme.HeaderFontColor != null)
                    this.themeHeaderStyle.color = '#' + App.Global.Client.Theme.HeaderFontColor;
                if (App.Global.Client.Theme.HeaderFont != null)
                    this.themeHeaderStyle["font-family"] = App.Global.Client.Theme.HeaderFont;
                if (App.Global.Client.Theme.HeaderFontSize != null)
                    this.themeHeaderStyle["font-size"] = App.Global.Client.Theme.HeaderFontSize + 'px';
            }
        };
        MenubarController.prototype.showDisclaimer = function () {
            var _this = this;
            this.$translate('Privacy Policy').then(function (tr) {
                _this.$mdDialog.show({
                    controller: MenupopupdisclaimerController,
                    templateUrl: 'components/menubar/menupopupdisclaimer.html',
                    parent: angular.element(document.body),
                    locals: {
                        name: 'Test All Media ' + tr,
                        clientid: undefined,
                        $http: _this.$http,
                        $location: _this.$location,
                        $sce: _this.$sce
                    }
                })
                    .then(function (answer) { }, function () { });
            });
        };
        MenubarController.$inject = ['$http', 'authenticationService', '$translate', '$sce', '$mdDialog', '$location', '$anchorScroll'];
        return MenubarController;
    }());
    App.MenubarController = MenubarController;
    function MenupopupdisclaimerController($scope, $mdDialog, name, clientid, $http, $location, $sce) {
        $scope.name = name;
        $scope.showinvalid = false;
        $scope.clientid = clientid;
        $scope.$http = $http;
        $scope.$location = $location;
        $scope.$sce = $sce;
        $scope.data = "";
        $scope.cancel = function () {
            $scope.$location.hash('');
            $mdDialog.cancel();
        };
        $scope.scrollTo = function (event) {
            var location;
            var item = event.target;
            while (item != undefined && location == undefined) {
                if (item.attributes.scrolltarget == undefined)
                    item = item.parentNode;
                else
                    location = item.attributes.scrolltarget.value;
            }
            //$scope.$location.hash(location);
            //App.Helper.GoToAnchor(location);
            $location.hash(location);
        };
        var activate = function () {
            if ($scope.clientid != undefined) {
                //Get client disclaimer
                var cs = new App.ClientService($scope.$http);
                cs.GetClientDisclaimer($scope.clientid).then(function (data) {
                    $scope.data = $scope.$sce.trustAsHtml(data.split("href=\"#").join("ng-click=scrollTo($event) scrolltarget=\""));
                    if (!$scope.$$phase) {
                        $scope.$applyAsync();
                    }
                });
            }
            else {
                //Get system disclaimer
                var ss = new App.SystemService($scope.$http);
                ss.GetDisclaimer().then(function (data) {
                    $scope.data = $scope.$sce.trustAsHtml(data.split("href=\"#").join("ng-click=scrollTo($event) scrolltarget=\""));
                    //$scope.data = $scope.$sce.trustAsHtml(data.split("href=\"#terms024\"").join("href=\"##terms024\" My-Bind-Once target=\"_self\"").split("name=\"terms024\"").join("id=\"terms024\""));
                    //$scope.data = $scope.$sce.trustAsHtml(data);
                    if (!$scope.$$phase) {
                        $scope.$applyAsync();
                    }
                });
            }
        };
        activate();
    }
    function MenubarDirective() {
        return {
            scope: {},
            restrict: 'EA',
            controller: MenubarController,
            controllerAs: 'menubar',
            bindToController: true,
            templateUrl: 'components/menubar/menubar.html',
            link: function ($scope) {
                MenubarController.prototype.activate($scope);
            }
        };
    }
    ;
    angular.module('app.menubar', [])
        .controller('MenubarController', MenubarController)
        .directive('menubar', MenubarDirective);
})(App || (App = {}));
//# sourceMappingURL=menubar.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    angular.module('app.usermenu', [])
        .controller('UsermenuController', ['$http', 'authenticationService', UsermenuController]);
    function UsermenuController($http, authenticationService) {
        var $scope = this;
        this.logout = function () {
            authenticationService.logOut();
            App.Helper.GoToLogin();
        };
    }
})(App || (App = {}));
//# sourceMappingURL=usermenu.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    var HomeController = /** @class */ (function () {
        function HomeController($http, $location, $timeout, $translate, $document) {
            this.self = this;
            this.surveys = [];
            this.homeTitle = 'Available Surveys';
            this.showDefaultText = false;
            this.showSVPMessage = false;
            this.$http = $http;
            this.$location = $location;
            this.$timeout = $timeout;
            this.$translate = $translate;
            this.$document = $document;
            this.audioActivated = false;
        }
        HomeController.prototype.activate = function () {
            var _this = this;
            if (!App.Helper.AuthenticationCheck())
                return false;
            if (this.$translate.use() != 'en') {
                this.$translate('HomePageTitle').then(function (tr) {
                    _this.homeTitle = tr;
                });
            }
            //Get participant surveys
            var surveyService = new App.SurveyService(this.$http);
            surveyService.GetSurveys(App.Global.Participant.ID).then(function (data) {
                _this.showDefaultText = data.length == 0;
                App.Global.Participant.Surveys = data;
                _this.surveys = App.Global.Participant.Surveys;
                for (var i = 0; i < _this.surveys.length; i++) {
                    var s = _this.surveys[i];
                    s.StartDate = (new Date(s.StartDate)).toDateString(); //.toLocaleDateString();
                }
                _this.showSVPMessage = App.Global.Client != null && App.Global.Client.ShowSVPMessage != null ? App.Global.Client.ShowSVPMessage : false;
            });
        };
        HomeController.prototype.activateAudioPlayer = function () {
            if (this.audioActivated)
                return;
            this.loadAduioElement();
            this.setAudioSource(App.ActivationAudioPath);
            this.audioElement.play();
            this.loadVideoElement();
            this.setVideoSource(App.ActivationVideoPath);
            this.videoElement1.play();
            this.videoElement2.play();
            this.audioActivated = true;
        };
        HomeController.prototype.setAudioSource = function (audioSource) {
            this.audioElement.src = audioSource;
        };
        HomeController.prototype.setVideoSource = function (videoSource) {
            this.videoElement1.src = videoSource;
            this.videoElement2.src = videoSource;
        };
        HomeController.prototype.loadAduioElement = function () {
            if (this.audioElement == null)
                this.audioElement = this.$document[0].getElementById('audioElement');
        };
        HomeController.prototype.loadVideoElement = function () {
            if (this.videoElement1 == null)
                this.videoElement1 = this.$document[0].getElementById('videoElement1');
            if (this.videoElement2 == null)
                this.videoElement2 = this.$document[0].getElementById('videoElement2');
        };
        HomeController.prototype.openSurvey = function (id) {
            var _this = this;
            this.activateAudioPlayer();
            var timer = this.$timeout(function () {
                _this.$timeout.cancel(timer);
                _this.$location.path('/survey/' + id);
            }, 100);
        };
        //public string Name;
        //public int ID;
        //public DateTime? CreationDate;
        //public bool? HasStarted;
        //public int? PercentComplete;
        //public DateTime? CompletionDate;
        //public DateTime? StartDate;
        HomeController.$inject = ['$http', '$location', '$timeout', '$translate', '$document'];
        return HomeController;
    }());
    App.HomeController = HomeController;
    angular.module('app.home', [])
        .controller('HomeController', HomeController);
})(App || (App = {}));
//# sourceMappingURL=home.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
//
// this is the template for the page where the user would be entering their address & verifying award info
// 
//
var App;
(function (App) {
    var HomeAwardController = /** @class */ (function () {
        function HomeAwardController($http, $location, $timeout, $translate, $document) {
            this.self = this;
            this.surveys = [];
            this.homeTitle = 'Available Surveys';
            this.showDefaultText = false;
            this.showSVPMessage = false;
            this.$http = $http;
            this.$location = $location;
            this.$timeout = $timeout;
            this.$translate = $translate;
            this.$document = $document;
            this.audioActivated = false;
        }
        HomeAwardController.prototype.activate = function () {
            var _this = this;
            if (!App.Helper.AuthenticationCheck())
                return false;
            if (this.$translate.use() != 'en') {
                this.$translate('HomePageTitle').then(function (tr) {
                    _this.homeTitle = tr;
                });
            }
            //Get participant surveys
            var surveyService = new App.SurveyService(this.$http);
            surveyService.GetSurveys(App.Global.Participant.ID).then(function (data) {
                _this.showDefaultText = data.length == 0;
                App.Global.Participant.Surveys = data;
                _this.surveys = App.Global.Participant.Surveys;
                for (var i = 0; i < _this.surveys.length; i++) {
                    var s = _this.surveys[i];
                    s.StartDate = (new Date(s.StartDate)).toDateString(); //.toLocaleDateString();
                }
                _this.showSVPMessage = App.Global.Client != null && App.Global.Client.ShowSVPMessage != null ? App.Global.Client.ShowSVPMessage : false;
            });
        };
        HomeAwardController.prototype.activateAudioPlayer = function () {
            if (this.audioActivated)
                return;
            this.loadAduioElement();
            this.setAudioSource(App.ActivationAudioPath);
            this.audioElement.play();
            this.loadVideoElement();
            this.setVideoSource(App.ActivationVideoPath);
            this.videoElement1.play();
            this.videoElement2.play();
            this.audioActivated = true;
        };
        HomeAwardController.prototype.setAudioSource = function (audioSource) {
            this.audioElement.src = audioSource;
        };
        HomeAwardController.prototype.setVideoSource = function (videoSource) {
            this.videoElement1.src = videoSource;
            this.videoElement2.src = videoSource;
        };
        HomeAwardController.prototype.loadAduioElement = function () {
            if (this.audioElement == null)
                this.audioElement = this.$document[0].getElementById('audioElement');
        };
        HomeAwardController.prototype.loadVideoElement = function () {
            if (this.videoElement1 == null)
                this.videoElement1 = this.$document[0].getElementById('videoElement1');
            if (this.videoElement2 == null)
                this.videoElement2 = this.$document[0].getElementById('videoElement2');
        };
        HomeAwardController.prototype.openSurvey = function (id) {
            var _this = this;
            this.activateAudioPlayer();
            var timer = this.$timeout(function () {
                _this.$timeout.cancel(timer);
                _this.$location.path('/survey/' + id);
            }, 100);
        };
        //public string Name;
        //public int ID;
        //public DateTime? CreationDate;
        //public bool? HasStarted;
        //public int? PercentComplete;
        //public DateTime? CompletionDate;
        //public DateTime? StartDate;
        HomeAwardController.$inject = ['$http', '$location', '$timeout', '$translate', '$document'];
        return HomeAwardController;
    }());
    App.HomeAwardController = HomeAwardController;
    angular.module('app.homeAward', [])
        .controller('HomeAwardController', HomeAwardController);
})(App || (App = {}));
//# sourceMappingURL=homeAward.js.map;
// Path: /about
angular.module('app.about', [])
.controller('AboutController', ['$location', '$window', function ( $location, $window) {
    this.$root.title = 'Test All Media® | About';
    this.$on('$viewContentLoaded', function () {
        $window.ga('send', 'pageview', { 'page': $location.path(), 'title': this.$root.title });
    });
}]);
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    angular.module('app.ratethemusic', ['ngNewRouter'])
        .controller('RatethemusicController', ['$rootScope', '$http', '$router', '$location', '$timeout', '$translate', 'authenticationService', 'ngAuthSettings', 'cfpLoadingBar', '$mdDialog', '$window', '$routeParams', RatethemusicController]);
    function RatethemusicController($rootScope, $http, $router, $location, $timeout, $translate, authenticationService, ngAuthSettings, cfpLoadingBar, $mdDialog, $window, $routeParams) {
        var $self = this;
        this.$routeParams = $routeParams;
        this.$translate = $translate;
        this.dialog = $mdDialog;
        this.loginData = {
            userName: "",
            password: "",
            useRefreshTokens: false
        };
        this.logo;
        this.clientid;
        this.requiredClass = '';
        this.message = "";
        this.disableSubmit = false;
        this.showPassword = false;
        this.limitedProfile = false; //App.Global.Client.LimitedParticipantProfile;
        this.showLogin = false;
        // Set the default value of inputType
        this.passwordInputType = 'password';
        this.randomBackground = '1';
        this.emailFormat = App.Global.EmailValidationRegEx;
        this.showPrivacyPolicyBanner = false; // (new Date()).getFullYear() == 2020 && (new Date()).getMonth() < 3;
        this.showPrivacyPolicy = function () {
            $window.open(PrivacyPolicyUrl, '_blank');
        };
        // Hide & show password function
        this.hideShowPassword = function () {
            if ($self.passwordInputType == 'password')
                $self.passwordInputType = 'text';
            else
                $self.passwordInputType = 'password';
        };
        this.forgotpass = function () {
            $router.parent.navigate('/forgotpassword');
        };
        this.login = function (form) {
            var _this = this;
            this.disableSubmit = true;
            //Validate
            if (form.$invalid) {
                this.requiredClass = "highlight-required";
                this.disableSubmit = false;
                if (form.emailInput.$error.pattern != null && form.emailInput.$error.pattern == true) {
                    App.Helper.ShowTranslatedAlert("Please enter a valid e-mail address.", this, $mdDialog, $translate);
                }
                else {
                    App.Helper.ShowTranslatedAlert('Please fill out all of the required fields.', this, $mdDialog, $translate);
                }
                return false;
            }
            else {
                this.message = "";
                this.requiredClass = "";
            }
            var ps = new App.ParticipantService($http);
            ps.GetParticipantEntities(this.loginData.userName).then(function (rsp) {
                if (rsp.length < 2) {
                    if (rsp != null && rsp[0] != null && rsp[0].ClientURL != null)
                        ngAuthSettings.clientCallLetters = rsp[0].ClientURL;
                    //proceed with login
                    authenticationService.login(_this.loginData).then(function (response) {
                        _this.processLogin(response); //.data);//adan
                    }, function (err) {
                        console.log("ratethemusic error B");
                        _this.disableSubmit = false;
                        if (err != null && err.data != null && err.data.error_description != null)
                            _this.message = err.data.error_description;
                    });
                }
                else {
                    //display a popup with client entities
                    _this.$translate('Your email address is registered to multiple stations. Please select the station you wish to continue logging in to.').then(function (tr) {
                        _this.dialog.show({
                            controller: App.EntitypickerController,
                            templateUrl: 'components/entitypicker/entitypicker.html',
                            locals: {
                                message: tr,
                                entities: rsp,
                                parent: _this.self
                            }
                        })
                            .then(function (callLetters) {
                            ngAuthSettings.clientCallLetters = callLetters;
                            //proceed with login
                            authenticationService.login(_this.loginData).then(function (response) {
                                _this.processLogin(response); //.data);//adan
                            }, function (err) {
                                console.log("ratethemusic error A");
                                _this.disableSubmit = false;
                                if (err != null && err.data != null && err.data.error_description != null)
                                    _this.message = err.data.error_description;
                            });
                        }, function () {
                            //alert('You cancelled the dialog.');
                            _this.disableSubmit = false;
                        });
                    });
                }
            });
        };
        this.processLogin = function (response) {
            App.Helper.LoadParticipantData(App.Helper.GetParticipantDataFromAuth(response));
            //authorizationdata
            var authorizationdata = response.data.callLetters + 'authorizationdata';
            window.localStorage.setItem(authorizationdata, JSON.stringify(App.Global.AuthorizationData));
            //participant
            var participant = response.data.callLetters + 'participant';
            window.localStorage.setItem(participant, JSON.stringify(App.Global.Participant));
            //authenticated
            var authenticated = response.data.callLetters + 'authenticated';
            window.localStorage.setItem(authenticated, App.Global.Authenticated);
            //set login source - App.Global.LoginRoute = '/rtm';
            var loginroute = response.data.callLetters + 'loginroute';
            window.localStorage.setItem(loginroute, JSON.stringify(App.Global.LoginRoute));
            var locationChange = response.data.callLetters + 'deregisterlocationchangestartlistener';
            window.localStorage.setItem(locationChange, App.Global.DeregisterLocationChangeStartListener);
            if (App.Global.Participant.CompleteRegistration == false)
                $window.location.href = SiteSubFolder + response.data.callLetters + '#!/radiohabits';
            else if (App.Global.Participant.ForceRescreen == true)
                $window.location.href = SiteSubFolder + response.data.callLetters + '#!/signup';
            else
                $window.location.href = SiteSubFolder + response.data.callLetters + '#!/home';
        };
        this.change = function () {
            $self.message = "";
        };
        this.placeholderText = "";
        this.focus = function (event) {
            $self.placeholderText = event.target.placeholder;
            event.target.placeholder = "";
            return true;
        };
        this.blur = function (event) {
            event.target.placeholder = $self.placeholderText;
            return true;
        };
        this.authExternalProvider = function (provider) {
            console.log(location);
            '/' + location.pathname.split('/')[1];
            var sitepath = '';
            var paths = location.pathname.split('/');
            for (var i = 0; i < (paths.length - 1); i++) {
                if (paths[i] != null && paths[i] != '')
                    sitepath = sitepath + '/' + paths[i];
            }
            var redirectUri = location.protocol + '//' + location.host + sitepath + '/authcomplete';
            var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
                + "&response_type=token&client_id=" + ngAuthSettings.appClientID
                + "&call_letters=" + ngAuthSettings.clientCallLetters
                + "&redirect_uri=" + redirectUri;
            window.$windowScope = this;
            window.localStorage.setItem('exloginlocationhref', window.location.href);
            window.location.href = externalProviderUrl;
            //var oauthWindow = window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0");
        };
        this.authCompletedCB = function (fragment) {
            if (App.Global.Participant == null)
                App.Global.Participant = {};
            App.Global.Participant.ExternalAuthData = {
                Provider: fragment.provider,
                UserName: fragment.external_user_name,
                ExternalAccessToken: fragment.external_access_token
            };
            if (fragment.haslocalaccount == 'False') {
                //if no local account is found - redirect to register with external credentials.
                //authenticationService.logOut();
                if (fragment.email != null)
                    App.Global.Participant.EMail = fragment.email;
                if (fragment.first_name != null)
                    App.Global.Participant.FirstName = fragment.first_name;
                if (fragment.last_name != null)
                    App.Global.Participant.LastName = fragment.last_name;
                $timeout(function () { $location.path('/signup'); }, 500);
            }
            else {
                //Obtain access token and redirect to home
                var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token };
                authenticationService.obtainAccessToken(externalData).then(function (response) {
                    var ps = new App.ParticipantService($http);
                    ps.GetBasicParticipantInfo(App.Global.Participant.ID).then(function (data) {
                        App.Helper.LoadParticipantDataAndRedirect(data, $location);
                    });
                }, function (err) {
                    console.log("ratethemusic error C");
                    $self.disableSubmit = false;
                    if (err != null && err.data != null && err.data.error_description != null)
                        $self.message = err.data.error_description;
                });
            }
        };
        function activate() {
            App.Global.LoginRoute = '/rtm';
            if (ClientCallLetters.toLowerCase() != NationalEntity.toLowerCase()) {
                document.location.href = SiteSubFolder + NationalEntity + '#!' + App.Global.LoginRoute;
            }
            var date = new Date();
            if (date.getFullYear() == 2020 && date.getMonth() < 3) {
                $self.showPrivacyPolicyBanner = true;
            }
            //set random background image
            $self.randomBackground = App.Helper.GetRandomInt(8).toString(); //8 is excluded - will return 0 to 7
            if ($self.$routeParams != undefined && $self.$routeParams.login != undefined && $self.$routeParams.login != "") {
                $self.showLogin = $self.$routeParams.login;
            }
            var authFragment = window.localStorage.getItem('authfragment');
            if (authFragment != null && authFragment != '') {
                window.localStorage.setItem('authfragment', '');
                $self.authCompletedCB(JSON.parse(authFragment));
                return;
            }
            //cfpLoadingBar.latencyThreshold = 10000;
            //Set the logo data here
            if (App.Helper.LoadingClientPromise == null) {
                if (App.Global.Client != null && App.Global.Client.Theme != null) {
                    $self.logo = App.Global.Client.Theme.LogoPath != null ? App.Global.Client.Theme.LogoPath : "Images/tam.png"; //if there is theme load from them
                }
                else {
                    $self.logo = (App.Global.Client != null && App.Global.Client.LogoPath != null) ? App.Global.Client.LogoPath : "Images/tam.png"; //if no theme - load the client logo
                }
                if (App.Global.Client != null) {
                    $self.limitedProfile = App.Global.Client.LimitedParticipantProfile;
                    $self.clientid = App.Global.Client.ID;
                }
            }
            else {
                App.Helper.LoadingClientPromise.then(function () {
                    if (App.Global.Client != null && App.Global.Client.Theme != null)
                        $self.logo = App.Global.Client.Theme.LogoPath != null ? App.Global.Client.Theme.LogoPath : "Images/tam.png"; //if there is theme load from them
                    else
                        $self.logo = (App.Global.Client != null && App.Global.Client.LogoPath != null) ? App.Global.Client.LogoPath : "Images/tam.png"; //if no theme - load the client logo
                    if (App.Global.Client != null) {
                        $self.limitedProfile = App.Global.Client.LimitedParticipantProfile;
                        $self.clientid = App.Global.Client.ID;
                    }
                });
            }
            var rememberedUserName = authenticationService.getUserName();
            if (rememberedUserName != null) {
                $self.loginData.userName = rememberedUserName;
                $self.loginData.useRefreshTokens = true;
            }
            if (App.Global.Authenticated) {
                if ($self.loginData.useRefreshTokens) {
                    authenticationService.refreshToken().then(function () {
                        if (App.Global.Authenticated) {
                            //authenticationService.fillAuthData();
                            App.Helper.GoToHome();
                        }
                    });
                }
                else {
                    authenticationService.logOut();
                }
            }
            //cfpLoadingBar.latencyThreshold = 100;
            cfpLoadingBar.complete();
        }
        ;
        activate();
    }
})(App || (App = {}));
//# sourceMappingURL=ratethemusic.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    angular.module('app.login', ['ngNewRouter'])
        .controller('LoginController', ['$rootScope', '$http', '$router', '$location', '$timeout', 'authenticationService', 'ngAuthSettings', 'cfpLoadingBar', '$translate', '$mdDialog', '$window', LoginController]);
    function LoginController($rootScope, $http, $router, $location, $timeout, authenticationService, ngAuthSettings, cfpLoadingBar, $translate, $mdDialog, $window) {
        var $self = this;
        this.loginData = {
            userName: "",
            password: "",
            useRefreshTokens: false
        };
        this.address = null;
        this.contact = null;
        this.logo;
        this.requiredClass = '';
        this.message = "";
        this.disableSubmit = false;
        this.showPassword = false;
        this.limitedProfile = false; //App.Global.Client.LimitedParticipantProfile;
        this.emailFormat = App.Global.EmailValidationRegEx;
        this.showPrivacyPolicyBanner = false; // (new Date()).getFullYear() == 2020 && (new Date()).getMonth() < 3;
        this.showPrivacyPolicy = function () {
            $window.open(PrivacyPolicyUrl, '_blank');
        };
        // Set the default value of inputType
        this.passwordInputType = 'password';
        // Hide & show password function
        this.hideShowPassword = function () {
            if ($self.passwordInputType == 'password')
                $self.passwordInputType = 'text';
            else
                $self.passwordInputType = 'password';
        };
        this.forgotpass = function () {
            $router.parent.navigate('/forgotPassword');
        };
        this.login = function (form) {
            var _this = this;
            this.disableSubmit = true;
            //Validate
            if (form.$invalid) {
                this.requiredClass = "highlight-required";
                this.disableSubmit = false;
                if (form.emailInput.$error.pattern == true) {
                    App.Helper.ShowTranslatedAlert("Please enter a valid e-mail address.", this, $mdDialog, $translate);
                }
                else {
                    App.Helper.ShowTranslatedAlert("Please fill out required fields.", this, $mdDialog, $translate);
                }
                return false;
            }
            else {
                this.message = "";
                this.requiredClass = "";
            }
            authenticationService.login(this.loginData).then(function (response) {
                var ps = new App.ParticipantService($http);
                ps.GetBasicParticipantInfo(App.Global.Participant.ID).then(function (data) {
                    App.Helper.LoadParticipantDataAndRedirect(data, $location);
                });
            }, function (err) {
                console.log("login error B");
                _this.disableSubmit = false;
                if (err != null && err.data != null && err.data.error_description != null)
                    _this.message = err.data.error_description;
            });
        };
        this.change = function () {
            $self.message = "";
        };
        this.placeholderText = "";
        this.focus = function (event) {
            $self.placeholderText = event.target.placeholder;
            event.target.placeholder = "";
            return true;
        };
        this.blur = function (event) {
            event.target.placeholder = $self.placeholderText;
            return true;
        };
        this.authExternalProvider = function (provider) {
            console.log(location);
            //'/' + location.pathname.split('/')[1]
            var sitepath = '';
            var paths = location.pathname.split('/');
            for (var i = 0; i < (paths.length - 1); i++) {
                if (paths[i] != null && paths[i] != '')
                    sitepath = sitepath + '/' + paths[i];
            }
            var redirectUri = location.protocol + '//' + location.host + sitepath + '/authcomplete';
            var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
                + "&response_type=token&client_id=" + ngAuthSettings.appClientID
                + "&call_letters=" + ngAuthSettings.clientCallLetters
                + "&redirect_uri=" + redirectUri;
            window.$windowScope = this;
            window.localStorage.setItem('exloginlocationhref', window.location.href);
            window.location.href = externalProviderUrl;
            //var oauthWindow = window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0");
        };
        this.authCompletedCB = function (fragment) {
            if (App.Global.Participant == null)
                App.Global.Participant = {};
            App.Global.Participant.ExternalAuthData = {
                Provider: fragment.provider,
                UserName: fragment.external_user_name,
                ExternalAccessToken: fragment.external_access_token
            };
            if (fragment.haslocalaccount == 'False') {
                //if no local account is found - redirect to register with external credentials.
                //authenticationService.logOut();
                if (fragment.email != null)
                    App.Global.Participant.EMail = fragment.email;
                if (fragment.first_name != null)
                    App.Global.Participant.FirstName = fragment.first_name;
                if (fragment.last_name != null)
                    App.Global.Participant.LastName = fragment.last_name;
                $timeout(function () { $location.path('/signup'); }, 500);
            }
            else {
                //Obtain access token and redirect to home
                var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token };
                authenticationService.obtainAccessToken(externalData).then(function (response) {
                    var ps = new App.ParticipantService($http);
                    ps.GetBasicParticipantInfo(App.Global.Participant.ID).then(function (data) {
                        App.Helper.LoadParticipantDataAndRedirect(data, $location);
                    });
                }, function (err) {
                    console.log("login error A");
                    $self.disableSubmit = false;
                    if (err != null && err.data != null && err.data.error_description != null)
                        $self.message = err.data.error_description;
                });
            }
        };
        function activate() {
            App.Global.LoginRoute = '/login';
            var authFragment = window.localStorage.getItem('authfragment');
            if (authFragment != null && authFragment != '') {
                window.localStorage.setItem('authfragment', '');
                $self.authCompletedCB(JSON.parse(authFragment));
                return;
            }
            var date = new Date();
            if (date.getFullYear() == 2020 && date.getMonth() < 3) {
                $self.showPrivacyPolicyBanner = true;
            }
            //cfpLoadingBar.latencyThreshold = 10000;
            //Set the logo data here
            if (App.Helper.LoadingClientPromise == null) {
                if (App.Global.Client != null && App.Global.Client.Theme != null)
                    $self.logo = App.Global.Client.Theme.LogoPath != null ? App.Global.Client.Theme.LogoPath : "Images/tam.png"; //if there is theme load from them
                else
                    $self.logo = (App.Global.Client != null && App.Global.Client.LogoPath != null) ? App.Global.Client.LogoPath : "Images/tam.png"; //if no theme - load the client logo
                if (App.Global.Client != null) {
                    $self.limitedProfile = App.Global.Client.LimitedParticipantProfile;
                    $self.address = App.Global.Client.Address;
                    $self.contact = App.Global.Client.Contact;
                }
            }
            else {
                App.Helper.LoadingClientPromise.then(function () {
                    if (App.Global.Client != null && App.Global.Client.Theme != null)
                        $self.logo = App.Global.Client.Theme.LogoPath != null ? App.Global.Client.Theme.LogoPath : "Images/tam.png"; //if there is theme load from them
                    else
                        $self.logo = (App.Global.Client != null && App.Global.Client.LogoPath != null) ? App.Global.Client.LogoPath : "Images/tam.png"; //if no theme - load the client logo
                    if (App.Global.Client != null) {
                        $self.limitedProfile = App.Global.Client.LimitedParticipantProfile;
                        $self.address = App.Global.Client.Address;
                        $self.contact = App.Global.Client.Contact;
                    }
                });
            }
            var rememberedUserName = authenticationService.getUserName();
            if (rememberedUserName != null) {
                $self.loginData.userName = rememberedUserName;
                $self.loginData.useRefreshTokens = true;
            }
            if (App.Global.Authenticated) {
                if ($self.loginData.useRefreshTokens) {
                    authenticationService.refreshToken().then(function () {
                        if (App.Global.Authenticated) {
                            //authenticationService.fillAuthData();
                            App.Helper.GoToHome();
                        }
                    });
                }
                else {
                    authenticationService.logOut();
                }
            }
            //cfpLoadingBar.latencyThreshold = 100;
            cfpLoadingBar.complete();
        }
        ;
        $timeout(function () { activate(); }, 0);
    }
})(App || (App = {}));
//# sourceMappingURL=login.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    var SignupController = /** @class */ (function () {
        function SignupController($rootScope, $locale, $location, $timeout, $http, $mdDialog, authenticationService, setfocus, $anchorScroll, $window, $translate, $sce, $document) {
            this.isNational = IsNationalLogin;
            this.savedSuccessfully = false;
            this.message = "";
            this.requiredClass = false;
            this.authenticated = App.Global.Authenticated;
            this.acceptTerms = false;
            this.disableSubmit = false;
            this.ageOnly = false;
            this.age = "";
            this.otherGenderText = "";
            this.emailFormat = App.Global.EmailValidationRegEx;
            this.ispasswordreset = App.Global.IsPasswordReset;
            this.presign = true;
            this.showChangePassword = false;
            this.externalAuthentication = false;
            this.passwordText = 'Create Password (optional)';
            this.emailsOptInMessage = null;
            this.selectedEnthnicity = "";
            this.address = null;
            this.contact = null;
            this.registration = {
                ClientID: "",
                FirstName: "",
                LastName: "",
                DateOfBirth: "",
                Gender: "",
                GenderOther: "",
                otherGenderText: "",
                EMail: "",
                Password: "",
                ConfirmPassword: "",
                CountryID: 1,
                StateID: "",
                State: "",
                City: "",
                PostalCode: "",
                Ethnicity: "",
                birthDay: "",
                birthYear: "",
                birthMonth: "",
                Address1: "",
                Address2: "",
                MobilePhone: "",
                HomePhone: "",
                EthnicityBilingual: "",
                EthnicityBilingualQ1: "",
                EthnicityBilingualQ2: "",
                EmailsOptIn: false,
                OldPassword: "",
                NoOldPassword: true,
                ExternalLoginProvider: "",
                ExternalLoginToken: "",
                OldEmailsOptIn: false,
                OldForceRescreen: false,
                OptInMessage: null,
                Salt: null,
                PasswordHash: null,
                PasswordHashVersion: 1
            };
            this.ethnicities = [];
            this.countries = [];
            this.usStates = [];
            this.canadaStates = [];
            this.genders = [];
            this.yesno = [];
            this.ages = [];
            this.years = [];
            this.months = [];
            this.days = [];
            this.alert = null;
            this.placeholderText = "";
            this.$rootScope = $rootScope;
            this.$locale = $locale;
            this.$location = $location;
            this.$timeout = $timeout;
            this.$http = $http;
            this.$mdDialog = $mdDialog;
            this.authenticationService = authenticationService;
            this.setfocus = setfocus;
            this.$anchorScroll = $anchorScroll;
            this.$window = $window;
            this.$translate = $translate;
            this.$sce = $sce;
            this.$document = $document;
            this.genders = [
                { Name: this.$translate.instant('Male'), ID: '1' },
                { Name: this.$translate.instant('Female'), ID: '2' }
            ];
            this.yesno = [
                { Name: this.$translate.instant('Yes'), ID: 'true' },
                { Name: this.$translate.instant('No'), ID: 'false' }
            ];
        }
        SignupController.prototype.getStatesByCountryID = function (countryID) {
            var filteredStates = [];
            if (App.Global.System.States == null) {
                var ss = new App.SystemService(this.$http);
                ss.GetStates().then(function (data) {
                    App.Global.System.States = data;
                    App.Global.System.States.forEach(function (o) {
                        if (o.CountryID == countryID)
                            filteredStates.push(o);
                    });
                });
            }
            else {
                App.Global.System.States.forEach(function (o) {
                    if (o.CountryID == countryID)
                        filteredStates.push(o);
                });
            }
            return filteredStates;
        };
        SignupController.prototype.getAge = function (birthDate) {
            if (birthDate != null) {
                var today = new Date();
                var age = today.getFullYear() - birthDate.getFullYear();
                var m = today.getMonth() - birthDate.getMonth();
                if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
                    age--;
                }
                return age;
            }
            return 0;
        };
        SignupController.prototype.gotoTop = function () {
            // set the location.hash to the id of
            // the element you wish to scroll to.
            //this.$location.hash('top');
            // call $anchorScroll()
            this.$anchorScroll('top');
            //this.$window.scrollTo(0, 0);
            //this.$broadcast('scroll.scrollTop');
        };
        SignupController.prototype.scrollToTop = function () {
            var elem = angular.element(this.$document[0].getElementById('maincontent'));
            var scrollableContentController = elem.controller('scrollableContent');
            scrollableContentController.scrollTo(0);
        };
        SignupController.prototype.signUp = function (form) {
            var _this = this;
            //prevent double click 
            this.disableSubmit = true;
            //validate required fields
            if (form.$invalid) {
                this.requiredClass = true;
                this.savedSuccessfully = false;
                this.disableSubmit = false;
                if (form.emailInput != null && form.emailInput.$error.pattern == true) {
                    this.showTranslatedAlert("Please enter a valid e-mail address.");
                }
                else {
                    this.showTranslatedAlert("Please fill out all of the required fields.");
                }
                return false;
            }
            else {
                this.savedSuccessfully = true;
                this.requiredClass = false;
                this.message = "";
            }
            //set dob if ageOnly
            if (this.ageOnly == true) {
                var currentDate = new Date();
                var numAge;
                if (this.age == "")
                    numAge = 0;
                else
                    numAge = Number(this.age);
                this.registration.birthYear = (currentDate.getFullYear() - numAge).toString();
                this.registration.birthMonth = (currentDate.getMonth() + 1).toString();
                this.registration.birthDay = currentDate.getDate().toString();
            }
            //mandatory registration.EmailsOptIn
            if (this.presign == false && this.registration.EmailsOptIn == false) {
                this.showTranslatedAlert('Before proceeding, you must read, understand and agree to the Electronic Communications message.');
                this.disableSubmit = false;
                return false;
            }
            this.disableSubmit = false;
            if (this.registration.Gender == "4") {
                this.registration.Gender = "3"; // set to 'other'
            }
            else {
                // didn't pick let me type, so be sure to clear out the text field
                this.registration.GenderOther = "";
            }
            //submit
            if (this.authenticated) {
                var ps = new App.ParticipantService(this.$http);
                ps.UpdateProfile(this.registration).then(function (response) {
                    //remove navigation listener 
                    App.Helper.DeregisterLocationChangeStartListenerIfExists();
                    _this.savedSuccessfully = true;
                    _this.disableSubmit = false;
                    if (App.Global.Client.DisplayRadioHabits == true &&
                        App.Global.Client.LimitedParticipantProfile == false) {
                        if (App.Global.Participant.CompleteRegistration == false || App.Global.Participant.ForceRescreen == true) {
                            _this.$location.path('/radiohabits');
                        }
                        else {
                            _this.executeTranslatedPrompt("Your profile was successfully updated. Would you like to review your radio habits?"
                            //"Your profile was successfully updated, please review your radio habits."
                            , function () { _this.$location.path('/radiohabits'); }, function () { _this.$location.path('/home'); });
                        }
                    }
                    else {
                        _this.showTranslatedAlert("Your profile was successfully updated.");
                        _this.startTimer('/home');
                    }
                    //if (this.showChangePassword) {
                    //    this.showTranslatedAlert("Your password was successfully updated.");
                    //    startTimer('/home');
                    //}
                    //else {
                    //    this.showTranslatedAlert("Your profile was successfully updated, please review your radio habits.");
                    //    startTimer('/radiohabits');
                    //}
                }, function (err) {
                    _this.disableSubmit = false;
                    if (err != null && err.data != null && err.data.ModelState != null)
                        _this.$translate('Failed to update user profile').then(function (tr) {
                            var errtext = err.data.ModelState.error[0].trim();
                            _this.$translate(errtext).then(function (trerr) {
                                if (errtext.toLowerCase().indexOf('new password') !== -1) {
                                    _this.registration.Password = null;
                                    _this.registration.ConfirmPassword = null;
                                }
                                else if (errtext.toLowerCase().indexOf('old password') !== -1) {
                                    _this.registration.OldPassword = null;
                                }
                                _this.showAlert(tr + ": " + trerr);
                            });
                        });
                    else
                        _this.showTranslatedAlert("Failed to update user profile");
                });
            }
            else {
                this.registration.DateOfBirth = new Date(this.registration.birthYear.toString()
                    + '/' + this.registration.birthMonth.toString()
                    + '/' + this.registration.birthDay.toString()).toDateString();
                if (this.presign) {
                    // validate age
                    var age = this.getAge(new Date(this.registration.DateOfBirth));
                    if (age < 13) {
                        App.Helper.GoToError('Thank you for your interest, we are not currently looking for new participants.');
                        return false;
                    }
                    else {
                        if (!this.acceptTerms) {
                            this.showTranslatedAlert('You must accept the Privacy Policy');
                            this.disableSubmit = false;
                            return false;
                        }
                        this.presign = false;
                        this.disableSubmit = false;
                        //App.Helper.GoToAnchor('signuptop');
                        this.$timeout(function () {
                            //$document[0].getElementById('firstNameInput').blur();
                            var elem = angular.element(_this.$document[0].getElementById('scrollableSignupDiv'));
                            var scrollableContentController = elem.controller('scrollableContent');
                            scrollableContentController.scrollTo(0, 0);
                        }, 200);
                        return false;
                    }
                }
                if (App.Global.Participant != null && App.Global.Participant.ExternalAuthData != null) {
                    this.registration.ExternalLoginProvider = App.Global.Participant.ExternalAuthData.Provider;
                    this.registration.ExternalLoginToken = App.Global.Participant.ExternalAuthData.ExternalAccessToken;
                }
                this.authenticationService.saveRegistration(this.registration).then(function (response) {
                    //remove navigation listener 
                    App.Helper.DeregisterLocationChangeStartListenerIfExists();
                    _this.savedSuccessfully = true;
                    _this.acceptTerms = _this.disableSubmit;
                    if (App.Global.Participant != null && App.Global.Participant.ExternalAuthData != null) {
                        //Obtain access token and redirect to home
                        var externalData = { provider: App.Global.Participant.ExternalAuthData.Provider, externalAccessToken: App.Global.Participant.ExternalAuthData.ExternalAccessToken };
                        _this.authenticationService.obtainAccessToken(externalData).then(function (response) {
                            var ps = new App.ParticipantService(_this.$http);
                            ps.GetBasicParticipantInfo(App.Global.Participant.ID).then(function (data) {
                                App.Helper.LoadParticipantDataAndRedirect(data, _this.$location);
                            });
                        }, function (err) {
                            console.log("signup error A");
                            _this.disableSubmit = false;
                            if (err != null && err.data != null && err.data.error_description != null)
                                _this.message = err.data.error_description;
                        });
                    }
                    else {
                        var loginData = {
                            userName: _this.registration.EMail,
                            password: _this.registration.Password,
                            useRefreshTokens: false
                        };
                        _this.authenticationService.login(loginData).then(function (response) {
                            //this.showAlert("Your user was registered successfully. Please enter your radio habits.");
                            //startTimer('/radiohabits');
                            if (App.Global.Client.DisplayRadioHabits == true && App.Global.Client.LimitedParticipantProfile == false) {
                                App.Global.Participant.CompleteRegistration = false;
                                _this.$location.path('/radiohabits');
                            }
                            else
                                _this.$location.path('/home');
                        }, function (err) {
                            _this.showTranslatedAlert("Registration succeeded, but login failed. Please try again.");
                            _this.disableSubmit = false;
                        });
                    }
                }, function (err) {
                    _this.disableSubmit = false;
                    if (err != null && err.data != null && err.data.ModelState != null)
                        _this.$translate('Failed to register user').then(function (tr) {
                            _this.$translate(err.data.ModelState.error[0].trim()).then(function (trerr) {
                                _this.showAlert(tr + ": " + trerr);
                            }, function (err) {
                                _this.showAlert(tr + ": " + err);
                            });
                        });
                    else
                        _this.showTranslatedAlert("Failed to register user");
                });
            }
        };
        SignupController.prototype.showAlert = function (message) {
            this.closeAlert();
            this.alert = this.$mdDialog.alert()
                .parent(angular.element(document.body))
                .clickOutsideToClose(true)
                .content(message)
                .ariaLabel(message)
                .ok('OK');
            this.$mdDialog.show(this.alert);
        };
        SignupController.prototype.showTranslatedAlert = function (message) {
            var _this = this;
            this.$translate(message).then(function (tr) {
                _this.closeAlert();
                _this.alert = _this.$mdDialog.alert()
                    .parent(angular.element(document.body))
                    .clickOutsideToClose(true)
                    .content(tr)
                    .ariaLabel(message)
                    .ok('OK');
                _this.$mdDialog.show(_this.alert);
            });
        };
        SignupController.prototype.executeTranslatedPrompt = function (message, yes, no) {
            var _this = this;
            this.$translate(message).then(function (tr) {
                _this.closeAlert();
                _this.alert = _this.$mdDialog.confirm()
                    .parent(angular.element(document.body))
                    .clickOutsideToClose(true)
                    .content(tr)
                    .ariaLabel(message)
                    .ok('Yes')
                    .cancel('No');
                _this.$mdDialog.show(_this.alert).then(yes, no);
            });
        };
        SignupController.prototype.focusElement = function (condition, element) {
            if (condition == true)
                this.setfocus(element);
        };
        SignupController.prototype.closeAlert = function () {
            if (this.alert != null)
                this.$mdDialog.hide(this.alert, "finished");
            this.alert = null;
        };
        SignupController.prototype.showDisclaimer = function () {
            var _this = this;
            var date = new Date();
            var year = date.getFullYear();
            if (year < 2020) {
                this.$translate('Privacy Policy').then(function (tr) {
                    _this.$mdDialog.show({
                        controller: PopupdisclaimerController,
                        templateUrl: 'components/signup/popupdisclaimer.html',
                        parent: angular.element(document.body),
                        locals: {
                            name: 'Test All Media ' + tr,
                            clientid: undefined,
                            $http: _this.$http,
                            $location: _this.$location,
                            $sce: _this.$sce
                        }
                    })
                        .then(function (answer) { }, function () { });
                });
            }
            else {
                this.$window.open(PrivacyPolicyUrl, '_blank');
            }
        };
        SignupController.prototype.showClientDisclaimer = function () {
            var _this = this;
            var date = new Date();
            var year = date.getFullYear();
            if (year > 2019 && this.isNational) {
                this.$window.open(PrivacyPolicyUrl, '_blank');
            }
            else {
                this.$translate('Privacy Policy').then(function (tr) {
                    _this.$mdDialog.show({
                        controller: PopupdisclaimerController,
                        templateUrl: 'components/signup/popupdisclaimer.html',
                        parent: angular.element(document.body),
                        locals: {
                            name: _this.clientName + ' ' + tr,
                            clientid: App.Global.Client.ID,
                            $http: _this.$http,
                            $location: _this.$location,
                            $sce: _this.$sce
                        }
                    })
                        .then(function (answer) { }, function () { });
                });
            }
        };
        SignupController.prototype.change = function () {
            this.message = "";
        };
        SignupController.prototype.startTimer = function (redirectPath) {
            var _this = this;
            this.$timeout(function () {
                _this.closeAlert();
                _this.$location.path(redirectPath);
            }, 3000);
        };
        SignupController.prototype.LoadUserData = function () {
            var _this = this;
            if (App.Global.Authenticated) {
                var ps = new App.ParticipantService(this.$http);
                ps.GetParticipantInfo(App.Global.Participant.ID).then(function (data) {
                    _this.$timeout(function () {
                        if (_this.ageOnly == true) {
                            if (data.DateOfBirth == null || data.DateOfBirth == "") {
                                _this.age = "";
                            }
                            else {
                                _this.age = _this.getAge(new Date(data.DateOfBirth)).toString();
                            }
                        }
                        if (data.GenderOther != "") {
                            data.Gender = 4;
                        }
                        if (_this.settings.EthnicityBilingualOn && (data.Ethnicity != _this.settings.ShowEthnicityBilingualOnEthnicityID)) {
                            data.EthnicityBilingual = "";
                            data.EthnicityBilingualQ1 = "";
                            data.EthnicityBilingualQ2 = "";
                        }
                        else {
                            if (data.EthnicityBilingual != null)
                                data.EthnicityBilingual = data.EthnicityBilingual.toString();
                            else {
                                data.EthnicityBilingual = 'false';
                            }
                            if (data.EthnicityBilingual == 'false') {
                                data.EthnicityBilingualQ1 = "";
                                data.EthnicityBilingualQ2 = "";
                            }
                        }
                        data.Gender = data.Gender.toString();
                        data.birthMonth = data.birthMonth.toString();
                        data.birthDay = data.birthDay.toString();
                        data.birthYear = data.birthYear.toString();
                        _this.registration = data; //note this is overwriting the structure of registration as its defined in this file
                        if (App.Global.IsPasswordReset == true) {
                            _this.showChangePassword = true;
                            _this.registration.NoOldPassword = true;
                        }
                        _this.acceptTerms = true;
                        if (_this.registration.NoOldPassword) {
                            _this.$translate('Create Password (optional)').then(function (tr) {
                                _this.passwordText = tr;
                            });
                        }
                        else {
                            _this.$translate('Change Password').then(function (tr) {
                                _this.passwordText = tr;
                            });
                        }
                        _this.updateEmailsOptIn();
                    }, 100);
                });
            }
            else {
                this.updateEmailsOptIn();
            }
        };
        SignupController.prototype.activate = function ($scope) {
            var _this = this;
            if (App.Global.DeregisterLocationChangeStartListener == null
                && App.Global.Participant != null && (App.Global.Participant.CompleteRegistration == false || App.Global.Participant.ForceRescreen == true)) {
                //add handler only if we have not added one already. 
                App.Global.DeregisterLocationChangeStartListener = this.$rootScope.$on('$locationChangeStart', function (event, next, current) {
                    if (current.indexOf('/signup') > 0 && next.indexOf('/signup') < 0 && App.Global.Participant != null && (App.Global.Participant.CompleteRegistration == false || App.Global.Participant.ForceRescreen == true)) {
                        event.preventDefault();
                    }
                });
                // remove handler on destroy of the local scope.
                //$scope.$on('$destroy', () => {
                //    App.Helper.DeregisterLocationChangeStartListenerIfExists();
                //});
                // remove handler on destroy of the local scope.
                $scope.$on('$locationChangeSuccess', function () {
                    App.Helper.DeregisterLocationChangeStartListenerIfExists();
                });
            }
            if ((App.Global.Authenticated == undefined || App.Global.Authenticated == false) && this.registration.DateOfBirth == "")
                this.presign = true;
            else
                this.presign = false;
            if (App.Global.Participant != null && App.Global.Participant.ExternalAuthData != null) {
                this.externalAuthentication = true;
            }
            //Load the states first - there was one case below in which we were not loading the states
            this.usStates = this.getStatesByCountryID(1); //1 is US
            this.canadaStates = this.getStatesByCountryID(36); //36 is Canada
            // then proceed with the loading of the rest of the data...
            //Get Client Signup Settings
            if (App.Global.Client != null && App.Global.Client.SignupSettings != null) {
                this.settings = App.Global.Client.SignupSettings;
                this.clientName = App.Global.Client.Name;
                this.limitedProfile = App.Global.Client.LimitedParticipantProfile;
                this.ageOnly = App.Global.Client.AgeOnly;
                this.otherGenderText = App.Global.Client.otherGenderText;
                if (this.otherGenderText.length > 0) {
                    this.genders[2] = { Name: this.$translate.instant('Prefer not to say'), ID: '3' };
                    this.genders[3] = { Name: this.$translate.instant('Other'), ID: '4' };
                }
                this.registration.ClientID = App.Global.Client.ID;
                this.registration.CountryID = App.Global.Client.CountryID;
                this.address = App.Global.Client.Address;
                this.contact = App.Global.Client.Contact;
            }
            else {
                var clientService = new App.ClientService(this.$http);
                if (App.Global.Client == null) {
                    clientService.GetClientInfo(ClientCallLetters).then(function (data) {
                        if (data == null) {
                            App.Helper.GoToError();
                        }
                        else {
                            App.Global.Client = data;
                            _this.registration.ClientID = App.Global.Client.ID;
                            _this.registration.CountryID = App.Global.Client.CountryID;
                            _this.clientName = App.Global.Client.Name;
                            _this.limitedProfile = App.Global.Client.LimitedParticipantProfile;
                            _this.ageOnly = App.Global.Client.AgeOnly;
                            _this.otherGenderText = App.Global.Client.otherGenderText;
                            if (_this.otherGenderText.length > 0) {
                                _this.genders[2] = { Name: _this.$translate.instant('Prefer not to say'), ID: '3' };
                                _this.genders[3] = { Name: _this.$translate.instant('Other'), ID: '4' };
                            }
                            _this.address = App.Global.Client.Address;
                            _this.contact = App.Global.Client.Contact;
                            clientService.GetSignupSettings(App.Global.Client.ID).then(function (s) {
                                _this.settings = s;
                                App.Global.Client.SignupSettings = s;
                            }, function (err) {
                                App.Helper.GoToError();
                            });
                        }
                    }, function (err) {
                        App.Helper.GoToError();
                    });
                }
                else {
                    // But we still need to set the client not signup settings related info for the local form:
                    this.registration.ClientID = App.Global.Client.ID;
                    this.registration.CountryID = App.Global.Client.CountryID;
                    this.clientName = App.Global.Client.Name;
                    this.limitedProfile = App.Global.Client.LimitedParticipantProfile;
                    this.ageOnly = App.Global.Client.AgeOnly;
                    this.otherGenderText = App.Global.Client.otherGenderText;
                    if (this.otherGenderText.length > 0) {
                        this.genders[2] = { Name: this.$translate.instant('Prefer not to say'), ID: '3' };
                        this.genders[3] = { Name: this.$translate.instant('Other'), ID: '4' };
                    }
                    this.address = App.Global.Client.Address;
                    this.contact = App.Global.Client.Contact;
                    // and then load the client signup settings...
                    clientService.GetSignupSettings(App.Global.Client.ID).then(function (s) {
                        _this.settings = s;
                        App.Global.Client.SignupSettings = s;
                    }, function (err) {
                        App.Helper.GoToError();
                    });
                    //we were not loading states here ... now it is not needed as we are loading them first above
                }
            }
            if (this.ageOnly == true) {
                //Add ages
                for (var i = 6; i <= 99; i += 1) {
                    this.ages.push(i.toString());
                }
            }
            else {
                //Add years
                var d = new Date();
                var nowYear = d.getFullYear();
                for (var n = 1; n <= 150; n += 1) {
                    this.years.push((nowYear - n).toString());
                }
                //Add months
                var datetime = this.$locale.DATETIME_FORMATS;
                for (var m = 0; m < datetime.MONTH.length; m++) {
                    this.months.push({ Name: datetime.MONTH[m], Value: (m + 1).toString() });
                }
                //Add days
                for (var i = 1; i <= 31; i += 1) {
                    this.days.push(i.toString());
                }
            }
            //Load needed data from API
            //LaodSignupData();
            if (App.Global.System == null || App.Global.System.Countries == null || App.Global.System.Ethnicities == null) {
                //set the logo to the defualt image and add promise 
                var ss = new App.SystemService(this.$http);
                ss.GetEthnicities().then(function (data) {
                    _this.ethnicities = data;
                    App.Global.System.Ethnicities = data;
                    ss.GetCountries().then(function (data) {
                        _this.countries = data;
                        App.Global.System.Countries = data;
                        _this.LoadUserData();
                    });
                });
            }
            else {
                this.ethnicities = App.Global.System.Ethnicities;
                this.countries = App.Global.System.Countries;
                this.LoadUserData();
            }
            //Load the data transferred from external login
            if (App.Global.Participant != null) {
                if (this.externalAuthentication) {
                    if (App.Global.Participant.EMail != null)
                        this.registration.EMail = App.Global.Participant.EMail;
                    if (App.Global.Participant.FirstName != null)
                        this.registration.FirstName = App.Global.Participant.FirstName;
                    if (App.Global.Participant.LastName != null)
                        this.registration.LastName = App.Global.Participant.LastName;
                }
                else {
                    this.registration = App.Global.Participant; //note this is overwriting the structure of registration as its defined in this file           
                }
                this.updateEmailsOptIn();
            }
        };
        SignupController.prototype.focus = function (event) {
            this.placeholderText = event.target.placeholder;
            event.target.placeholder = "";
            return true;
        };
        SignupController.prototype.blur = function (event) {
            event.target.placeholder = this.placeholderText;
            return true;
        };
        SignupController.prototype.PreferNot = function () {
            this.registration.GenderOther = "";
        };
        SignupController.prototype.focusDynamiclyShownSelect = function (event, test) {
            //if (test) {
            //    var elem = angular.element(event.target);
            //    //elem.trigger("change");
            //    //console.log("changed");
            //    elem.next().find('select').trigger('touchstart');
            //    console.log("next touchstarted");
            //}
        };
        SignupController.prototype.updateEmailsOptIn = function () {
            //if (this.authenticated == true && this.registration.EmailsOptIn == true) {
            //    return;
            //}
            var _this = this;
            var clientService = new App.ClientService(this.$http);
            clientService.GetCountryEmailsOptInMessage(App.Global.Client.CountryID, App.Global.Client.ID, this.$translate.proposedLanguage() || this.$translate.use()).then(function (data) {
                if (data == null) {
                    _this.emailsOptInMessage = null;
                    _this.registration.EmailsOptIn = true;
                }
                else {
                    _this.registration.OptInMessage = data.Message;
                    _this.emailsOptInMessage = _this.$sce.trustAsHtml(data.Message.split("href=\"#").join("ng-click=scrollTo($event) scrolltarget=\""));
                    _this.registration.EmailsOptIn = false;
                }
            }, function (err) {
                console.log("signup error B");
                _this.emailsOptInMessage = null;
            });
        };
        SignupController.$inject = ['$rootScope', '$locale', '$location', '$timeout', '$http', '$mdDialog', 'authenticationService', 'setfocus', '$anchorScroll', '$window', '$translate', '$sce', '$document'];
        return SignupController;
    }());
    App.SignupController = SignupController;
    angular.module('app.signup', [])
        .controller('SignupController', SignupController);
    function PopupdisclaimerController($scope, $mdDialog, name, clientid, $http, $location, $sce) {
        $scope.name = name;
        $scope.showinvalid = false;
        $scope.clientid = clientid;
        $scope.$http = $http;
        $scope.$location = $location;
        $scope.$sce = $sce;
        $scope.data = "";
        $scope.cancel = function () {
            $scope.$location.hash('');
            $mdDialog.cancel();
        };
        $scope.scrollTo = function (event) {
            var location;
            var item = event.target;
            while (item != undefined && location == undefined) {
                if (item.attributes.scrolltarget == undefined)
                    item = item.parentNode;
                else
                    location = item.attributes.scrolltarget.value;
            }
            //this.$location.hash(location);
            App.Helper.GoToAnchor(location);
        };
        var activate = function () {
            if ($scope.clientid != undefined) {
                //Get client disclaimer
                var cs = new App.ClientService($scope.$http);
                cs.GetClientDisclaimer($scope.clientid).then(function (data) {
                    $scope.data = $scope.$sce.trustAsHtml(data.split("href=\"#").join("ng-click=scrollTo($event) scrolltarget=\""));
                    if (!$scope.$$phase) {
                        $scope.$apply();
                    }
                });
            }
            else {
                //Get system disclaimer
                var ss = new App.SystemService($scope.$http);
                ss.GetDisclaimer().then(function (data) {
                    $scope.data = $scope.$sce.trustAsHtml(data.split("href=\"#").join("ng-click=scrollTo($event) scrolltarget=\""));
                    if (!$scope.$$phase) {
                        $scope.$apply();
                    }
                });
            }
        };
        activate();
    }
})(App || (App = {}));
//# sourceMappingURL=signup.js.map;
var App;
(function (App) {
    angular.module('app.forgotpassword', ['ngNewRouter'])
        .controller('ForgotpasswordController', ['$router', '$location', '$timeout', '$http', '$mdDialog', 'authenticationService', 'ngAuthSettings', '$translate', ForgotpasswordController]);
    function ForgotpasswordController($router, $location, $timeout, $http, $mdDialog, authenticationService, ngAuthSettings, $translate) {
        var $scope = this;
        this.dialog = $mdDialog;
        this.success = false;
        this.requiredClass = "";
        this.message = "";
        this.requiredClass = "";
        this.authenticated = App.Global.Authenticated;
        this.acceptTerms = false;
        this.disableSubmit = false;
        this.limitedProfile = false; //App.Global.Client.LimitedParticipantProfile;
        this.isNational = IsNationalLogin;
        this.emailFormat = App.Global.EmailValidationRegEx;
        this.loginData = {
            EMail: "",
            ClientCallLetters: ngAuthSettings.clientCallLetters
        };
        this.message = "";
        this.activate = function () {
            if (App.Helper.LoadingClientPromise == null) {
                if (App.Global.Client != null)
                    $scope.limitedProfile = App.Global.Client.LimitedParticipantProfile;
            }
            else {
                App.Helper.LoadingClientPromise.then(function () {
                    if (App.Global.Client != null)
                        $scope.limitedProfile = App.Global.Client.LimitedParticipantProfile;
                });
            }
        };
        this.setSuccess = function () {
            $scope.success = true;
            $translate('An email containing your password reset link is on the way').then(function (tr) {
                $scope.message = tr;
            });
            $scope.disableSubmit = false;
            startTimer();
        };
        this.setError = function (err) {
            $scope.disableSubmit = false;
            $scope.success = false;
            if (err != null && err.data != null && err.data.ModelState != null)
                $translate(err.data.ModelState.error[0].trim()).then(function (trerr) {
                    $scope.message = trerr;
                });
            else
                $translate('Failed to email user password reset link.').then(function (tr) {
                    $scope.message = tr;
                });
            startErrorTimer();
        };
        this.emailPassword = function (form) {
            $scope.disableSubmit = true;
            //validate required fields
            if (form.$invalid) {
                $scope.requiredClass = "highlight-required";
                $scope.success = false;
                $scope.disableSubmit = false;
                if (form.emailInput.$error.pattern != null && form.emailInput.$error.pattern == true) {
                    $translate("Please enter a valid e-mail address.").then(function (tr) {
                        $scope.message = tr;
                    });
                }
                else {
                    $translate('Please fill out all of the required fields.').then(function (tr) {
                        $scope.message = tr;
                    });
                }
                return false;
            }
            else {
                $scope.success = true;
                $scope.requiredClass = "";
                $scope.message = "";
            }
            //submit
            authenticationService.forgotPassword(this.loginData).then(function (response) {
                $scope.setSuccess();
            }, function (err) {
                console.log("forgotPassword error C");
                if ($scope.isNational) {
                    var ps = new App.ParticipantService($http);
                    ps.GetParticipantEntities($scope.loginData.EMail).then(function (rsp) {
                        if (rsp.length < 2) {
                            //send the credentials for the client to which they have subscription
                            if (rsp != null && rsp[0] != null && rsp[0].ClientURL != null)
                                $scope.loginData.ClientCallLetters = rsp[0].ClientURL;
                            authenticationService.forgotPassword($scope.loginData).then(function (response) {
                                $scope.setSuccess();
                            }, function (err) {
                                console.log("forgotPassword error B");
                                $scope.setError(err);
                            });
                        }
                        else {
                            //prompt
                            $translate('Your email address is registered to multiple stations. Please select the station, for which you wish to reset your password.').then(function (tr) {
                                $scope.dialog.show({
                                    controller: App.EntitypickerController,
                                    templateUrl: 'components/entitypicker/entitypicker.html',
                                    locals: {
                                        message: tr,
                                        entities: rsp,
                                        parent: $scope.self
                                    }
                                }).then(function (callLetters) {
                                    $scope.loginData.ClientCallLetters = callLetters;
                                    authenticationService.forgotPassword($scope.loginData).then(function (response) {
                                        $scope.setSuccess();
                                    }, function (err) {
                                        console.log("forgotPassword error A");
                                        $scope.setError(err);
                                    });
                                }, function () {
                                    $scope.disableSubmit = false;
                                    //alert('You cancelled the dialog.');
                                });
                            });
                        }
                    });
                }
                else {
                    $scope.setError(err);
                }
            });
        };
        this.change = function () {
            $scope.message = "";
        };
        var startTimer = function () {
            var timer = $timeout(function () {
                $timeout.cancel(timer);
                App.Helper.GoToLogin();
            }, 5000);
        };
        var startErrorTimer = function () {
            var timer = $timeout(function () {
                $timeout.cancel(timer);
                $scope.message = "";
            }, 5000);
        };
        this.placeholderText = "";
        this.focus = function (event) {
            $scope.placeholderText = event.target.placeholder;
            event.target.placeholder = "";
            return true;
        };
        this.blur = function (event) {
            event.target.placeholder = $scope.placeholderText;
            return true;
        };
    }
})(App || (App = {}));
//# sourceMappingURL=forgotPassword.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
var App;
(function (App) {
    var ResetpasswordController = /** @class */ (function () {
        function ResetpasswordController($location, $timeout, $routeParams, authenticationService) {
            console.log('con - resetpassword');
            this.$routeParams = $routeParams;
            this.authenticationService = authenticationService;
            this.$location = $location;
            this.$timeout = $timeout;
        }
        ResetpasswordController.prototype.getResetPWGuid = function () {
            console.log('get pwguid');
            if (this.$routeParams != undefined && this.$routeParams.guid != undefined && this.$routeParams.guid != "")
                return this.$routeParams.guid;
            return null;
        };
        ResetpasswordController.prototype.doResetpassword = function () {
            var _this = this;
            console.log('loginresetpassword');
            var guid = this.getResetPWGuid();
            if (guid == null) {
                App.Helper.GoToLogin();
            }
            this.authenticationService.loginresetPassword(guid).then(function (response) {
                App.Helper.LoadParticipantData(App.Helper.GetParticipantDataFromAuth(response));
                App.Global.IsPasswordReset = true;
                _this.$location.path('/signup');
            }, function (err) {
                console.log("resetpassword error A");
                App.Helper.GoToLogin();
            });
        };
        ResetpasswordController.prototype.activate = function () {
            console.log('reset - activate');
            //do authentication by guid - get the guid
            this.doResetpassword();
        };
        return ResetpasswordController;
    }());
    App.ResetpasswordController = ResetpasswordController;
    angular.module('app.resetpassword', [])
        .controller('ResetpasswordController', ResetpasswordController);
})(App || (App = {}));
//# sourceMappingURL=resetpassword.js.map;
angular.module('app.detail', ['ngNewRouter'])
  .controller('DetailController', ['$routeParams', DetailController]);

function DetailController($routeParams) {
    this.id = $routeParams.id;
    //alert("assignign detail id");
};
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    var DisclaimerController = /** @class */ (function () {
        function DisclaimerController($scope, $http, $anchorScroll, $location, $routeParams, $sce, $compile, $timeout, $window) {
            this.data = "";
            this.$scope = $scope;
            this.$http = $http;
            this.$anchorScroll = $anchorScroll;
            this.$location = $location;
            this.$sce = $sce;
            this.$compile = $compile;
            this.$routeParams = $routeParams;
            this.$timeout = $timeout;
            this.$window = $window;
        }
        DisclaimerController.prototype.$onInit = function () {
            if (this.showHeader == undefined)
                this.showHeader = true;
            //this.activate();
            this.calls = ClientCallLetters;
            this.activate(this.$scope);
        };
        DisclaimerController.prototype.scrollTo = function (event) {
            var location;
            var item = event.target;
            while (item != undefined && location == undefined) {
                if (item.attributes.scrolltarget == undefined)
                    item = item.parentNode;
                else
                    location = item.attributes.scrolltarget.value;
            }
            //this.$location.search('#' + location);
            //this.$location.path("disclaimer").search({'hash': location });
            //this.$window.location.reload();	
            //this.$window.location.href = this.$location.$$absUrl;
            this.$location.hash(location);
            //this.$anchorScroll(location);
        };
        DisclaimerController.prototype.activate = function ($scope) {
            var _this = this;
            if ($scope.disclaimer.showHeader == undefined)
                $scope.disclaimer.showHeader = true;
            if ($scope.disclaimer.clientid != undefined) {
                //Get client disclaimer
                var cs = new App.ClientService($scope.disclaimer.$http);
                cs.GetClientDisclaimer($scope.disclaimer.clientid).then(function (data) {
                    $scope.disclaimer.data = _this.$sce.trustAsHtml(data.split("href=\"#").join("href=\"\" ng-click=scrollTo(this) scrolltarget=\"")); //data.split("href=\"#").join("name=\"")
                    if (!$scope.$$phase) {
                        //$digest or $apply
                        $scope.$apply();
                    }
                    if (_this.$routeParams != undefined && _this.$routeParams.hash != undefined && _this.$routeParams.hash != "") {
                        var timer = _this.$timeout(function () {
                            _this.$timeout.cancel(timer);
                            _this.$location.hash(_this.$routeParams.scrolltarget);
                            _this.$anchorScroll();
                        }, 0);
                    }
                });
            }
            else {
                //Get system disclaimer
                var ss = new App.SystemService($scope.disclaimer.$http);
                ss.GetDisclaimer().then(function (data) {
                    //home({queryParams: {foo: 5, bar:10}})
                    $scope.disclaimer.data = _this.$sce.trustAsHtml(data.split("href=\"#").join("ng-click=disclaimer.scrollTo($event) scrolltarget=\"")); //.join("ng-anchor=\""));//.join("class=\"ng-binding\" ng-href=\"{{disclaimer.calls}}#/disclaimer#"));//.join("href=\"" + ClientCallLetters +"#/disclaimer#"));(data.split("href=\"#").join("ng-click=\"disclaimer.scrollTo($event)\" scrolltarget=\""));//ng-link=\"disclaimer\" 
                    if (!$scope.$$phase) {
                        //$digest or $apply
                        $scope.$apply();
                    }
                    var locSearch = _this.$location.search();
                    var locationSearch = _this.$location.path() + _this.$location.search();
                    //
                    if (_this.$routeParams != undefined && _this.$routeParams.scrolltarget != undefined && _this.$routeParams.scrolltarget != "") {
                        var timer = _this.$timeout(function () {
                            _this.$timeout.cancel(timer);
                            _this.$location.hash(_this.$routeParams.scrolltarget);
                            _this.$anchorScroll();
                        }, 0);
                    }
                });
            }
        };
        DisclaimerController.$inject = ['$scope', '$http', '$anchorScroll', '$location', '$routeParams', '$sce', '$compile', '$timeout', '$window'];
        return DisclaimerController;
    }());
    App.DisclaimerController = DisclaimerController;
    function DisclaimerDirective() {
        return {
            scope: {
                clientid: '=',
                showHeader: '='
            },
            restrict: 'EA',
            controller: DisclaimerController,
            controllerAs: 'disclaimer',
            bindToController: true,
            templateUrl: 'components/disclaimer/disclaimer.html',
            link: function ($scope) {
                DisclaimerController.prototype.activate($scope);
            }
        };
    }
    ;
    angular.module('app.disclaimer', [])
        .controller('DisclaimerController', DisclaimerController)
        .directive('disclaimer', DisclaimerDirective);
})(App || (App = {}));
//# sourceMappingURL=disclaimer.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    var DisclaimerpopupController = /** @class */ (function () {
        function DisclaimerpopupController($scope, $mdDialog, name, clientid, $http, $location, $sce) {
            $scope.name = name;
            $scope.showinvalid = false;
            $scope.clientid = clientid;
            $scope.$http = $http;
            $scope.$location = $location;
            $scope.$sce = $sce;
            $scope.data = "";
            $scope.cancel = function () {
                $scope.$location.hash('');
                $mdDialog.cancel();
            };
            $scope.scrollTo = function (event) {
                var location;
                var item = event.target;
                while (item != undefined && location == undefined) {
                    if (item.attributes.scrolltarget == undefined)
                        item = item.parentNode;
                    else
                        location = item.attributes.scrolltarget.value;
                }
                App.Helper.GoToAnchor(location);
            };
            this.activate($scope);
        }
        DisclaimerpopupController.prototype.$onInit = function () {
        };
        DisclaimerpopupController.prototype.activate = function ($scope) {
            if ($scope.clientid != undefined) {
                //Get client disclaimer
                var cs = new App.ClientService($scope.$http);
                cs.GetClientDisclaimer($scope.clientid).then(function (data) {
                    $scope.data = $scope.$sce.trustAsHtml(data.split("href=\"#").join("ng-click=scrollTo($event) scrolltarget=\""));
                    //if (!$scope.$$phase) {
                    //    $scope.$apply();
                    //}
                });
            }
            else {
                //Get system disclaimer
                var ss = new App.SystemService($scope.$http);
                ss.GetDisclaimer().then(function (data) {
                    $scope.data = $scope.$sce.trustAsHtml(data.split("href=\"#").join("ng-click=scrollTo($event) scrolltarget=\""));
                    //if (!$scope.$$phase) {
                    //    $scope.$apply();
                    //}
                });
            }
        };
        DisclaimerpopupController.$inject = ['$scope', '$mdDialog', 'name', 'clientid', '$http', '$location', '$sce'];
        return DisclaimerpopupController;
    }());
    App.DisclaimerpopupController = DisclaimerpopupController;
    angular.module('app.disclaimerpopup', [])
        .controller('DisclaimerpopupController', DisclaimerpopupController);
})(App || (App = {}));
//# sourceMappingURL=disclaimerpopup.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
/// <reference path="../../scripts/typings/angular/jqlite.d.ts" />
'use strict';
var App;
(function (App) {
    var PopupquestionsController = /** @class */ (function () {
        function PopupquestionsController($scope, $mdDialog, name, questions, parent) {
            $scope.name = name;
            $scope.questions = questions;
            $scope.showinvalid = false;
            $scope.message = '';
            $scope.parent = parent;
            $scope.hide = function () {
                $mdDialog.hide();
            };
            $scope.cancel = function () {
                $mdDialog.cancel();
            };
            $scope.answer = function (form) {
                var _this = this;
                //Validate
                if (form.$invalid) {
                    $scope.showinvalid = true;
                    $scope.parent.$translate('Please review the highlighted questions').then(function (tr) { _this.message = tr; });
                    return false;
                }
                else {
                    this.showinvalid = false;
                    this.message = "";
                    $mdDialog.hide($scope.questions);
                }
            };
        }
        PopupquestionsController.prototype.$onInit = function () {
        };
        PopupquestionsController.$inject = ['$scope', '$mdDialog', 'name', 'questions', 'parent'];
        return PopupquestionsController;
    }());
    App.PopupquestionsController = PopupquestionsController;
    angular.module('app.popupquestions', [])
        .controller('PopupquestionsController', PopupquestionsController);
})(App || (App = {}));
//# sourceMappingURL=popupquestions.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    var EntitypickerController = /** @class */ (function () {
        function EntitypickerController($scope, $mdDialog, message, entities, parent) {
            $scope.entities = entities;
            $scope.showinvalid = false;
            $scope.message = message;
            $scope.parent = parent;
            $scope.cancel = function () {
                $mdDialog.cancel();
            };
            $scope.hide = function () {
                $mdDialog.hide();
            };
            $scope.openEntity = function (callLetters) {
                $mdDialog.hide(callLetters);
                return true;
            };
        }
        EntitypickerController.prototype.$onInit = function () {
        };
        EntitypickerController.$inject = ['$scope', '$mdDialog', 'message', 'entities', 'parent'];
        return EntitypickerController;
    }());
    App.EntitypickerController = EntitypickerController;
    angular.module('app.entitypicker', [])
        .controller('EntitypickerController', EntitypickerController);
})(App || (App = {}));
//# sourceMappingURL=entitypicker.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
var App;
(function (App) {
    var ContactusController = /** @class */ (function () {
        function ContactusController($http, $translate, $window, $location, $timeout, $mdDialog) {
            this.showCoolHeader = IsNationalLogin;
            this.request = {
                Language: "",
                ParticipantID: 0,
                ClientID: App.Global.Client.ID,
                Name: "",
                EMail: "",
                Message: "",
                RemoteAddress: "",
                UserAgent: "",
                ContactEMail: ""
            };
            this.contactOptions = {};
            this.placeholderText = "";
            this.savedSuccessfully = false;
            this.message = "";
            this.requiredClass = '';
            this.disableSubmit = false;
            this.$http = $http;
            this.$translate = $translate;
            this.$window = $window;
            this.$location = $location;
            this.$timeout = $timeout;
            this.$mdDialog = $mdDialog;
            this.request.Language = this.$translate.proposedLanguage() || this.$translate.use();
            this.request.UserAgent = this.$window.navigator.userAgent;
            if (App.Global.Authenticated == true)
                this.height = 'calc(100% - 100px)';
            else
                this.height = 'calc(100% - 100px)';
            this.emailFormat = App.Global.EmailValidationRegEx;
        }
        ContactusController.prototype.activate = function () {
            var _this = this;
            if (App.Global.Authenticated && App.Global.Participant != null) {
                if (App.Global.Participant.Name != null)
                    this.request.Name = App.Global.Participant.Name;
                if (App.Global.Participant.EMail != null)
                    this.request.EMail = App.Global.Participant.EMail;
            }
            var ss = new App.SystemService(this.$http);
            this.contactOptions = ss.GetContactOptions(App.Global.Client.ID).then(function (response) {
                _this.contactOptions = response;
            });
        };
        ContactusController.prototype.sendSupportRequest = function (form) {
            var _this = this;
            this.disableSubmit = true;
            //validate required fields
            if (form.$invalid) {
                this.requiredClass = "highlight-required";
                this.savedSuccessfully = false;
                this.disableSubmit = false;
                if (form.emailInput.$error.pattern != null && form.emailInput.$error.pattern == true) {
                    this.$translate("Please enter a valid e-mail address.").then(function (tr) {
                        _this.message = tr;
                    });
                }
                else {
                    this.$translate('Please fill out all of the required fields.').then(function (tr) {
                        _this.message = tr;
                    });
                }
                return false;
            }
            else {
                this.savedSuccessfully = true;
                this.requiredClass = "";
                this.message = "";
            }
            //submit
            var ss = new App.SystemService(this.$http);
            ss.PostSupportRequest(this.request).then(function (response) {
                _this.savedSuccessfully = true;
                _this.message = response; //Thank you for contacting us, we will respond shortly.
                _this.disableSubmit = false;
                if (App.Global.Authenticated)
                    _this.$timeout(function () {
                        _this.$location.path('/home');
                    }, 6000);
                else
                    _this.$timeout(function () {
                        App.Helper.GoToLogin();
                    }, 6000);
            }, function (err) {
                console.log("Contactus error A");
                if (err != null && err.data != null && err.data.ModelState != null) {
                    _this.$translate(err.data.ModelState.error[0].trim()).then(function (trerr) {
                        _this.message = trerr;
                    });
                }
                else {
                    _this.$translate('Failed to send message').then(function (trerr) {
                        _this.message = trerr;
                    });
                }
                _this.disableSubmit = false;
            });
        };
        ContactusController.prototype.focus = function (event) {
            this.placeholderText = event.target.placeholder;
            event.target.placeholder = "";
            return true;
        };
        ContactusController.prototype.blur = function (event) {
            event.target.placeholder = this.placeholderText;
            return true;
        };
        return ContactusController;
    }());
    App.ContactusController = ContactusController;
    angular.module('app.contactus', [])
        .controller('ContactusController', ContactusController);
})(App || (App = {}));
//# sourceMappingURL=contactus.js.map;
'use strict';
var App;
(function (App) {
    var MessageController = /** @class */ (function () {
        function MessageController() {
            this.activate();
        }
        MessageController.prototype.$onInit = function () {
        };
        MessageController.prototype.activate = function () {
        };
        return MessageController;
    }());
    App.MessageController = MessageController;
    function MessageDirective() {
        return {
            scope: {
                content: '=',
                title: '='
            },
            restrict: 'EA',
            controller: MessageController,
            controllerAs: 'message',
            bindToController: true,
            templateUrl: 'components/message/message.html'
        };
    }
    ;
    angular.module('app.message', [])
        .controller('MessageController', [MessageController])
        .directive('message', MessageDirective);
})(App || (App = {}));
//# sourceMappingURL=message.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    angular.module('app.error', [])
        .controller('ErrorController', ['$routeParams', '$translate', ErrorController]);
    function ErrorController($routeParams, $translate) {
        var $scope = this;
        this.message = 'The page you are looking for was not found.';
        function activate() {
            $translate('The page you are looking for was not found.').then(function (tr) {
                $scope.message = tr;
                if ($routeParams != undefined && $routeParams.message != undefined && $routeParams.message != "")
                    $translate($routeParams.message).then(function (tr) { $scope.message = tr; });
                else
                    $translate('You have requested an unknown entity.').then(function (tr) { $scope.message = tr; }); //"The page was not found";
            });
        }
        ;
        activate();
    }
})(App || (App = {}));
//# sourceMappingURL=error.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    var RadiohabitsController = /** @class */ (function () {
        function RadiohabitsController($http, $location, $anchorScroll, $timeout, $translate, $mdDialog, $rootScope) {
            this.questions = [];
            this.answers = [];
            this.message = '';
            this.cms = null;
            this.showinvalid = false;
            this.disableSubmit = false;
            this.questionResponseTime = 0;
            this.scrollableFooterClass = "scrollable-footer";
            this.isNational = IsNationalLogin;
            this.alert = null;
            this.$http = $http;
            this.$location = $location;
            this.$anchorScroll = $anchorScroll;
            this.$timeout = $timeout;
            this.$translate = $translate;
            this.$mdDialog = $mdDialog;
            this.$rootScope = $rootScope;
        }
        RadiohabitsController.prototype.activate = function ($scope) {
            var _this = this;
            if (!App.Helper.AuthenticationCheck())
                return false;
            if (App.Global.DeregisterLocationChangeStartListener == null
                && App.Global.Participant != null && (App.Global.Participant.CompleteRegistration == false || App.Global.Participant.ForceRescreen == true)) {
                App.Global.DeregisterLocationChangeStartListener = this.$rootScope.$on('$locationChangeStart', function (event, next, current) {
                    if (current.indexOf('/radiohabits') > 0 && next.indexOf('/radiohabits') < 0 && App.Global.Participant != null && (App.Global.Participant.CompleteRegistration == false || App.Global.Participant.ForceRescreen == true)) {
                        event.preventDefault();
                    }
                });
                //$scope.$on('$destroy', function () {
                //    App.Helper.DeregisterLocationChangeStartListenerIfExists();
                //});
                // remove handler on destroy of the local scope.
                $scope.$on('$locationChangeSuccess', function () {
                    App.Helper.DeregisterLocationChangeStartListenerIfExists();
                });
            }
            this.scrollableFooterClass = (($(window).innerWidth() > $(window).innerHeight())) ? 'scrollable-footer addBrowserButtonBarPadding' : 'scrollable-footer';
            $(window).on("resize.doResize", App.Helper.Debounce(function () {
                $scope.$apply(function () {
                    //apply updates
                    $scope.radiohabits.scrollableFooterClass = (($(window).innerWidth() > $(window).innerHeight())) ? 'scrollable-footer addBrowserButtonBarPadding' : 'scrollable-footer';
                });
            }, 200, $scope));
            //Get radio habit questions
            var ps = new App.ParticipantService(this.$http);
            ps.GetRadioHabitsQuestions(App.Global.Participant.ID, App.Global.Client.ID).then(function (data) {
                (_this.questions = data);
                //Add child questions
                for (var i = 0; i < _this.questions.length; i++) {
                    var q = _this.questions[i];
                    if (q.ChildIndexes != null) {
                        q.Children = [];
                        for (var ci = 0; ci < q.ChildIndexes.length; ci++) {
                            q.Children.push(_this.questions[q.ChildIndexes[ci]]);
                        }
                    }
                }
                _this.$timeout(function () { App.Helper.ScrollToTop(); }, 1000);
                //return data;
            });
        };
        ;
        RadiohabitsController.prototype.executeTranslatedPrompt = function (message, yes, no) {
            var _this = this;
            this.$translate(message).then(function (tr) {
                _this.closeAlert();
                _this.alert = _this.$mdDialog.confirm()
                    .parent(angular.element(document.body))
                    .clickOutsideToClose(true)
                    .content(tr)
                    .ariaLabel(message)
                    .ok('Yes')
                    .cancel('No');
                _this.$mdDialog.show(_this.alert).then(yes, no);
            });
        };
        RadiohabitsController.prototype.SaveHabits = function (form) {
            var _this = this;
            //prevent double click 
            this.disableSubmit = true;
            //validate required fields
            if (form.$invalid) {
                this.showinvalid = true;
                this.savedSuccessfully = false;
                this.disableSubmit = false;
                this.showTranslatedAlert('Please fill out all of the required fields.');
                return false;
            }
            else {
                this.savedSuccessfully = true;
                this.showinvalid = false;
                this.message = "";
            }
            var ps = new App.ParticipantService(this.$http);
            ps.SaveRadioHabits(App.Global.Participant.ID, App.Global.Client.ID, this.questions)
                .then(function (response) {
                //remove listened if successful save
                App.Helper.DeregisterLocationChangeStartListenerIfExists();
                if (App.Global.Participant.CompleteRegistration == true && App.Global.Participant.ForceRescreen == false) {
                    _this.savedSuccessfully = true;
                    if (App.Global.Client.ShowMontagesPage == true && App.Global.Client.LimitedParticipantProfile == false) {
                        _this.executeTranslatedPrompt("Your radio habits were saved successfully. Would you like to review your montages?", function () { _this.$location.path('/montages'); }, function () { _this.$location.path('/home'); });
                    }
                    else if (App.Global.Client.ShowPreferencesPage == true && App.Global.Client.LimitedParticipantProfile == false) {
                        _this.executeTranslatedPrompt("Your radio habits were saved successfully. Would you like to review your preferences?", function () { _this.$location.path('/preferences'); }, function () { _this.$location.path('/home'); });
                    }
                    else {
                        App.Global.Participant.CompleteRegistration = true;
                        App.Global.Participant.ForceRescreen = false;
                        _this.showTranslatedAlert('Your radio habits were saved successfully.');
                        _this.startTimer('/home');
                    }
                }
                else {
                    if (App.Global.Client.ShowMontagesPage == true && App.Global.Client.LimitedParticipantProfile == false)
                        _this.$location.path('/montages');
                    else if (App.Global.Client.ShowPreferencesPage == true && App.Global.Client.LimitedParticipantProfile == false)
                        _this.$location.path('/preferences');
                    else {
                        ps.GetThanksForSubscribingMessage(App.Global.Participant.ID, App.Global.Client.ID)
                            .then(function (cms) {
                            if (cms != null && cms.Message != null) {
                                _this.cms = cms;
                                _this.$timeout(function () { App.Helper.ScrollToTop(); }, 1000);
                            }
                        });
                        App.Global.Participant.CompleteRegistration = true;
                        App.Global.Participant.ForceRescreen = false;
                    }
                }
            }, function (err) {
                _this.savedSuccessfully = false;
                if (err != null && err.data != null && err.data.ModelState != null)
                    _this.$translate('Failed to save user radio habits:').then(function (tr) {
                        _this.$translate(err.data.ModelState.error[0].trim()).then(function (trerr) {
                            _this.showAlert(tr + ": " + trerr);
                        });
                    });
                else
                    _this.showTranslatedAlert('Failed to save user radio habits');
            });
            this.disableSubmit = false;
        };
        RadiohabitsController.prototype.goHome = function () {
            App.Helper.GoToHome();
        };
        RadiohabitsController.prototype.showAlert = function (message) {
            this.closeAlert();
            this.alert = this.$mdDialog.alert()
                .parent(angular.element(document.body))
                .clickOutsideToClose(true)
                .content(message)
                .ariaLabel(message)
                .ok('OK');
            this.$mdDialog.show(self.alert);
        };
        RadiohabitsController.prototype.showTranslatedAlert = function (message) {
            var _this = this;
            this.$translate(message).then(function (tr) {
                _this.closeAlert();
                _this.alert = _this.$mdDialog.alert()
                    .parent(angular.element(document.body))
                    .clickOutsideToClose(true)
                    .content(tr)
                    .ariaLabel(message)
                    .ok('OK');
                _this.$mdDialog.show(_this.alert);
            });
        };
        RadiohabitsController.prototype.closeAlert = function () {
            if (this.alert != null)
                this.$mdDialog.hide(this.alert, "finished");
            this.alert = null;
        };
        RadiohabitsController.prototype.startTimer = function (redirectPath) {
            var _this = this;
            var timer = this.$timeout(function () {
                _this.closeAlert();
                _this.$timeout.cancel(timer);
                _this.$location.path(redirectPath);
            }, 3000);
        };
        RadiohabitsController.$inject = ['$http', '$location', '$anchorScroll', '$timeout', '$translate', '$mdDialog', '$rootScope'];
        return RadiohabitsController;
    }());
    App.RadiohabitsController = RadiohabitsController;
    angular.module('app.radiohabits', [])
        .controller('RadiohabitsController', RadiohabitsController);
})(App || (App = {}));
//# sourceMappingURL=radioHabits.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    angular.module('app.question', [])
        .controller('QuestionController', ['$http', '$rootScope', '$document', '$timeout', '$window', '$translate', '$mdDialog', QuestionController])
        .directive('question', QuestionDirective);
    function QuestionController($http, $rootScope, $document, $timeout, $window, $translate, $mdDialog) {
        var vm = this;
        // Put initialization logic inside `$onInit()`
        // to make sure bindings have been initialized.
        vm.$onInit = function () {
            this.isNational = IsNationalLogin;
            this.SelectedValue;
            this.selectedValues = []; //For list of checkboxes
            this.selectedValuesRequired = this.data != null ? this.data.Required : false; //For list of checkboxes
            this.showMoreAnswers = false;
            this.customValue = '';
            this.mediaAutoStart = false;
            this.mediaForceListen = false;
            this.displayContentProgress = false;
            this.toolTipWidth = 200;
            this.mediaPlayProgress = 0;
            this.mediaPlayTime = 0;
            this.dialog = $mdDialog;
            this.addedAnswerID = 0;
            this.alert = '';
            this.thedata = this.data;
            activate();
        };
        // Prior to v1.5, we need to call `$onInit()` manually.
        // (Bindings will always be pre-assigned in these versions.)
        if (angular.version.major === 1 && angular.version.minor < 5) {
            this.$onInit();
        }
        //this.activateAudioPlayer = function (id) {
        //    var audioElement = vm.getAduioElement(id);
        //    audioElement.play();
        //};
        //this.setAudioSource = function (id, audioSource) {
        //    var audioElement = vm.getAduioElement(id);
        //    audioElement.src = audioSource;
        //};
        this.getAduioElement = function (id) {
            return $document[0].getElementById(id);
        };
        this.audioOnPlay = function (answer) {
            vm.loadAudioAnswer(answer, true);
        };
        this.audioOnStop = function () {
            return false;
        };
        this.loadAudioAnswer = function (answer, play) {
            if (answer.Media != null && answer.Media.Type == 1) {
                //Activate audio
                //if(vm.audioElement == null)
                var audioElement = vm.getAduioElement(answer.ID.toString());
                if (audioElement != null) {
                    //load audio
                    if (audioElement.src != answer.Media.Url)
                        audioElement.src = answer.Media.Url;
                    ////pay this audio
                    if (play) {
                        //    audioElement.play();
                        vm.pauseAllAudioButThis(answer.Media.Url);
                    }
                    //else
                    //    audioElement.pause();
                    ////pause any other audio that might be playing 
                }
            }
        };
        //this.audioplay = function (answer) {
        //    vm.loadAudioAnswer(answer, true);
        //};
        //this.setSelected = function ($event) {
        //    $event.target.Selected = true;
        //};
        this.toggleSelection = function (item, list) {
            var idx = list.indexOf(item);
            if (idx > -1) {
                list.splice(idx, 1);
                //item.Selected = false;
            }
            else {
                list.push(item);
                //item.Selected = true;
                item.AnswerTime = vm.getTime();
                this.onanswered();
            }
            //Set required
            vm.selectedValuesRequired = (!vm.someSelected(list)) && vm.data.Required;
        };
        this.someSelected = function (object) {
            return object != null && object.length > 0;
        };
        this.enterCustomValue = function (answer) {
            answer.Value = vm.customValue;
            vm.customValue = '';
            if (vm.data.Children != null && answer.Value != '') {
                for (var i = 0; i < vm.data.Children.length; i++) {
                    vm.data.Children[i].Answers.push({ Value: answer.Value, ID: answer.ID, Selected: false });
                }
            }
            else if (answer.Value.trim() == '') {
                vm.data.Answers.pop(); //removing last item
                //this.removeAnswer(answer);
                //if (!$rootScope.$$phase) {
                //    //$digest or $apply
                //    $rootScope.$apply();
                //}
            }
        };
        this.eatTheClick = function (event) {
            event.stopPropagation();
            return false;
        };
        this.addAnswer = function () {
            //limit to 3 extra answers
            if ((vm.data.CustomAnswers.length) < 3 && vm.data.Answers[vm.data.Answers.length - 1].Value != '') {
                vm.data.Answers.push({ Value: '', ID: vm.addedAnswerID, Selected: true });
                vm.data.CustomAnswers.push({ Value: '', ID: vm.addedAnswerID, Selected: true });
                vm.addedAnswerID = vm.addedAnswerID - 1;
            }
            $timeout(function () {
                var theInput = $document[0].getElementsByClassName("input_custom_answer");
                if (theInput != null) {
                    theInput[0].focus();
                    //theInput[0].autofocus = false;
                }
            }, 500);
            return;
        };
        this.removeAnswer = function (answer) {
            if (answer == null) {
                if (vm.data.CustomAnswers.length > 0) {
                    answer = vm.data.Answers.pop();
                    vm.data.CustomAnswers.pop();
                }
                else {
                    return;
                }
            }
            //if (answer.Selected != true || answer.Value == '') {
            if (vm.data.Children != null /*&& vm.data.Answers[vm.data.Answers.length - 1].Value != ''*/) {
                for (var i = 0; i < vm.data.Children.length; i++) {
                    vm.data.Children[i].Answers.pop();
                }
            }
            //}
            //else {
            //    vm.data.Answers.push(answer);
            //    vm.data.CustomAnswers.push(answer);
            //    vm.showTranslatedAlert("Please uncheck the item before deleting it.");
            //}
        };
        this.deselectAnswers = function () {
            if (vm.data.Answers != null) {
                for (var i = 0; i < vm.data.Answers.length; i++) {
                    vm.data.Answers[i].Selected == false;
                }
                if (vm.data.Type == 1) {
                    vm.SelectedValue = null;
                }
            }
            else {
                vm.data.Answers = [{ Value: '', Tooltip: '', ID: -1, Selected: false }];
            }
            if (vm.data.MoreAnswers != null) {
                for (var i = 0; i < vm.data.MoreAnswers.length; i++) {
                    vm.data.MoreAnswers[i].Selected == false;
                }
                if (vm.data.Type == 1) {
                    vm.SelectedValue = null;
                }
            }
        };
        this.showDependant = function () {
            if (vm.data == null)
                return true;
            if (vm.data.ParentAnswers == null || vm.data.ParentAnswers.length == 0)
                return true;
            for (var i = 0; i < vm.data.ParentAnswers.length; i++) {
                var num = vm.data.ParentAnswers[i];
                var idx = num - 1;
                if (vm.parent == null)
                    return false;
                var answer = vm.parent.Answers[idx];
                if (answer == null)
                    return false;
                if (answer.Selected)
                    return true;
            }
            return false;
        };
        this.showFamiliar = function () {
            if (vm.data == null)
                return true;
            if (vm.familiarityquestion == null)
                return true;
            if (vm.familiarityquestion == vm.data)
                return true;
            if (vm.familiarityquestion.AllowAnswersFromUnfamilarUser) {
                //no matter if the user is familiar or not - reuire answer to the scale question.
                //if ((vm.familiarityquestion.Answers[1].Selected && vm.familiarityquestion.Answers[1].NumericValue == 2) || (vm.familiarityquestion.Answers[0].Selected && vm.familiarityquestion.Answers[0].NumericValue == 2)) { //if not familiar Value
                //    vm.data.Required = false; // scaling is not required!
                //}
                return true;
            }
            if ((vm.familiarityquestion.Answers[0].Selected && vm.familiarityquestion.Answers[0].NumericValue == 1) || (vm.familiarityquestion.Answers[1].Selected && vm.familiarityquestion.Answers[1].NumericValue == 1))
                return true;
            return false;
        };
        this.onRadioSelected = function () {
            if (vm.data == null)
                vm.presetTiredOf = false;
            if (vm.data.For == 4) {
                if (vm.data.setPresetTiredOf != null)
                    vm.data.setPresetTiredOf();
            }
            //$("[aria_label='NoFavorites']").first().classList.remove("md-checked");
            //var elem = vm.data.getElementById("NoFave");
            //elem.classList.remove("md-checked");
            //vm.data.NoAnswer.classList.remove("md-checked");
            //vm.data.NoAnswer.checked = false;
            if (vm.data.NoAnswer != null) {
                vm.data.NoAnswer.Selected = false;
                vm.data.NoAnswer.click = false;
            }
        };
        this.addTiredOfSetter = function () {
            if (vm.data == null)
                vm.presetTiredOf = false;
            if (vm.data.For == 6) {
                if (vm.familiarityquestion != null)
                    vm.familiarityquestion.setPresetTiredOf = vm.setPresetTiredOf;
            }
        };
        this.presetTiredOf = false;
        this.setPresetTiredOf = function () {
            if (vm.data == null)
                vm.presetTiredOf = false;
            if (vm.data.For == 6) {
                if (vm.familiarityquestion == null)
                    vm.presetTiredOf = false;
                if (vm.familiarityquestion.AllowAnswersFromUnfamilarUser) {
                    if ((vm.familiarityquestion.Answers[1].Selected && vm.familiarityquestion.Answers[1].NumericValue == 2) || (vm.familiarityquestion.Answers[0].Selected && vm.familiarityquestion.Answers[0].NumericValue == 2)) {
                        if (vm.data.Answers[1].NumericValue == 2) {
                            vm.SelectedValue = vm.data.Answers[1].ID; //Select No! 
                            vm.data.Answers[0].Selected = false;
                            vm.data.Answers[1].Selected = true;
                        }
                        else {
                            vm.SelectedValue = vm.data.Answers[0].ID; //Reversed Values! No is first!
                            vm.data.Answers[1].Selected = false;
                            vm.data.Answers[0].Selected = true;
                        }
                        vm.presetTiredOf = true;
                        vm.onanswered();
                    }
                    else {
                        if (vm.presetTiredOf == true) {
                            vm.SelectedValue = null;
                            vm.presetTiredOf = false;
                            vm.data.Answers[0].Selected = false;
                            vm.data.Answers[1].Selected = false;
                            vm.onanswered();
                        }
                    }
                }
            }
            else {
                vm.presetTiredOf = false;
            }
        };
        this.setSelected = function (selAnswerID) {
            for (var i = 0; i < vm.data.Answers.length; i++) {
                var answer = vm.data.Answers[i];
                answer.Selected = (answer.ID == selAnswerID);
                if (answer.Selected == true) {
                    answer.AnswerTime = vm.getTime();
                }
            }
            this.onanswered();
            vm.resetMoreSelected();
        };
        this.resetSelected = function () {
            for (var i = 0; i < vm.data.Answers.length; i++) {
                var answer = vm.data.Answers[i];
                answer.Selected = false;
            }
        };
        this.resetMoreSelected = function () {
            if (vm.data.MoreAnswers != null) {
                for (var i = 0; i < vm.data.MoreAnswers.length; i++) {
                    var answer = vm.data.MoreAnswers[i];
                    answer.Selected = false;
                }
            }
        };
        this.setMoreSelected = function (selAnswerID) {
            for (var i = 0; i < vm.data.MoreAnswers.length; i++) {
                var answer = vm.data.MoreAnswers[i];
                answer.Selected = (answer.ID == selAnswerID);
                if (answer.Selected == true) {
                    answer.AnswerTime = vm.getTime();
                }
            }
            this.onanswered();
            vm.resetSelected();
        };
        this.getTime = function () {
            //Get Time
            var curTime = vm.time;
            //Reset Time
            vm.time = 0;
            //Return Saved Time
            return curTime;
        };
        this.pauseAllAudioButThis = function (url) {
            $rootScope.$broadcast('pauseAllButThisMediaPlayback', { sourceurl: url });
        };
        this.answering = function (answer) {
            var prevSelected = answer.Selected;
            answer.Selected = (answer.Value != null && answer.Value != '');
            if (prevSelected == false && answer.Selected == true) {
                answer.AnswerTime = vm.getTime();
            }
            this.onanswered();
        };
        this.showPopupImage = function (source) {
            this.dialog.show({
                escapeToClose: true,
                clickOutsideToClose: true,
                template: '<md-dialog>' +
                    '  <md-content>' +
                    '    <img style="max-width:100%;" src="' + source + '" />' +
                    '  </md-content>' +
                    '  <md-dialog-actions>' +
                    '    <md-button ng-click="closeDialog()">' +
                    '      OK' +
                    '    </md-button>' +
                    '  </md-dialog-actions>' +
                    '</md-dialog>',
                controller: SimplePopupController,
                //parent: this.self,
                locals: {}
            });
            //.then(() => {});
        };
        this.showTranslatedAlert = function (message) {
            //$translate(message).then((tr) => {
            this.alert = this.dialog.alert()
                .parent(angular.element(document.body))
                .clickOutsideToClose(true)
                .content(message)
                .ariaLabel(message)
                .ok('OK');
            this.dialog.show(this.alert);
            // });
        };
        this.showPopupVideo = function ($source) {
            this.dialog.show({
                escapeToClose: true,
                clickOutsideToClose: true,
                template: '<md-dialog>' +
                    '  <md-content>' +
                    '<videoplayer source="source" autostart="mediaAutoStart" forcelisten="mediaForceListen" artist="Artist" title="Title" audioplayprogress="mediaPlayProgress" audiotime="mediaPlayTime" aria-label="surveyquestionvideoplayer" lengthinseconds="ContentLengthInSeconds" displaycontentprogress="true" playbuttonview="false" ></videoplayer>' +
                    //'    <img style="max-width:100%;" src="' + source + '" />' +
                    '  </md-content>' +
                    '  <md-dialog-actions>' +
                    '    <md-button ng-click="closeDialog()">' +
                    '      OK' +
                    '    </md-button>' +
                    '  </md-dialog-actions>' +
                    '</md-dialog>',
                controller: VideoPopupController,
                //parent: this,
                locals: { source: $source }
            });
            //.then(() => {});
        };
        function activate() {
            vm.toolTipWidth = $window.width - 100;
            if (vm.data.ID == 1000) {
                $translate('Artists like').then(function (tr) {
                    for (var i = 0; i < vm.data.Answers.length; i++) {
                        vm.data.Answers[i].Tooltip = tr + '... ' + vm.data.Answers[i].Tooltip;
                    }
                    for (var i = 0; i < vm.data.MoreAnswers.length; i++) {
                        vm.data.MoreAnswers[i].Tooltip = tr + '... ' + vm.data.MoreAnswers[i].Tooltip;
                    }
                });
            }
            if (vm.data.Type == 1 || vm.data.Type == 3) {
                $timeout(function () {
                    for (var i = 0; i < vm.data.Answers.length; i++) {
                        //Activate the player and load the audio.
                        vm.loadAudioAnswer(vm.data.Answers[i], false);
                    }
                }, 0);
            }
            if (vm.data.Answers != null) {
                if (vm.data.Type == 1 || vm.data.Type == 2) {
                    //set selected value for radio buttons/ddlists/checkboxes
                    for (var i = 0; i < vm.data.Answers.length; i++) {
                        if (vm.data.Answers[i].Selected == true)
                            vm.SelectedValue = vm.data.Answers[i].ID;
                    }
                }
                else if (vm.data.Type == 3) {
                    for (var i = 0; i < vm.data.Answers.length; i++) {
                        if (vm.data.Answers[i].Selected == true)
                            vm.toggleSelection(vm.data.Answers[i], vm.selectedValues);
                    }
                }
            }
            else {
                vm.data.Answers = [{ Value: '', Tooltip: '', ID: -1, Selected: false }];
            }
            vm.addTiredOfSetter();
            if (vm.time == null)
                vm.time = 0;
        }
        ;
        //activate();
    }
    function QuestionDirective() {
        return {
            scope: {
                data: '=',
                showinvalid: '=',
                invalid: '=',
                form: '=',
                parent: '=',
                onanswered: '&onAnswered',
                time: '=',
                familiarityquestion: '='
            },
            restrict: 'EA',
            controller: QuestionController,
            controllerAs: 'question',
            bindToController: true,
            templateUrl: 'components/question/question.html'
        };
    }
    function SimplePopupController($scope, $mdDialog) {
        $scope.closeDialog = function () {
            $mdDialog.hide();
        };
    }
    function VideoPopupController($scope, $mdDialog, source) {
        $scope.source = source;
        $scope.mediaAutoStart = true;
        $scope.mediaForceListen = false;
        $scope.Artist = "";
        $scope.Title = "";
        $scope.mediaPlayProgress = 0;
        $scope.mediaPlayTime = 0;
        $scope.ContentLengthInSeconds = 0;
        $scope.closeDialog = function () {
            $mdDialog.hide();
        };
    }
})(App || (App = {}));
//# sourceMappingURL=question.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
var App;
(function (App) {
    var SurveyController = /** @class */ (function () {
        function SurveyController($http, $routeParams, authenticationService, $mdDialog, $rootScope, $timeout, ngAudio, $document, $translate, $window) {
            var _this = this;
            this.self = this;
            this.audioSource = 'audioElement';
            this.videoSource = 'videoElement';
            this.subScrollClass = 'scrollable-content';
            this.forceListenMedia = false;
            this.enableAutonext = false;
            this.enableAutonextSurveySetting = false;
            this.preview = false;
            this.hideButton = false;
            this.savingQSetAnswers = false;
            this.preview = this.getIsPreview($routeParams);
            if (!App.Helper.AuthenticationCheck(this.preview) && this.preview == false)
                return;
            //this.$scope = $scope;
            this.$translate = $translate;
            this.$window = $window;
            this.authenticationService = authenticationService;
            this.$http = $http;
            this.surveyID = $routeParams.id;
            this.currentQsetIndex = -1;
            this.percentComplete = 0;
            this.details = null;
            this.questions = null;
            this.popQuestions = null;
            this.message = '';
            this.savedSuccessfully = false;
            this.cms = null;
            $translate('Next').then(function (tr) { _this.buttonText = tr; });
            this.media = null;
            this.savedMedia = null;
            this.showinvalid = false;
            this.dialog = $mdDialog;
            this.mediaPlayProgress = 0;
            this.mediaPlayTime = 0;
            this.currentQuestionSetID = 0;
            this.currentQuestionSet = null;
            this.showPlaylist = false;
            this.cmsAtStart = true;
            this.popupTriggered = false;
            this.rootScope = $rootScope;
            this.$timeout = $timeout;
            this.questionSetTime = 0;
            this.timePlayed = 0;
            this.questionResponseTime = 0;
            this.ngAudio = ngAudio;
            this.$document = $document;
            this.radioFaceOffPlayed = false;
            this.allStationsFinished = false;
            this.introMediaLoaded = false;
            this.outroMediaLoaded = false;
        }
        SurveyController.prototype.getIsPreview = function (params) {
            if (params != undefined && params.preview != undefined && params.preview == "preview")
                return true;
            return false;
        };
        SurveyController.prototype.setSubScrollableClass = function () {
            this.subScrollClass = ($(window).innerWidth() > 500 || ($(window).innerWidth() < 500 && $(window).innerWidth() < $(window).innerHeight())) ? 'scrollable-content' : '';
            if ($(window).innerWidth() > 500 && (this.media != null && (this.media.Type == 2 || this.media.Type == 3)))
                this.subScrollClass += ' limit-max-width';
        };
        SurveyController.prototype.showTranslatedAlert = function (message) {
            var _this = this;
            this.$translate(message).then(function (tr) {
                _this.alert = _this.dialog.alert()
                    .parent(angular.element(document.body))
                    .clickOutsideToClose(true)
                    .content(tr)
                    .ariaLabel(tr)
                    .ok('OK');
                _this.dialog.show(_this.alert);
            });
        };
        SurveyController.prototype.loadClientID = function () {
            var _this = this;
            if (this.clientID != null)
                return;
            if (App.Global.Client != null) {
                this.clientID = App.Global.Client.ID;
                return;
            }
            if (App.Helper.LoadingClientPromise == null) {
                if (App.Global.Client != null) {
                    this.clientID = App.Global.Client.ID;
                }
                else {
                    var loadCDdefer = App.Helper.LoadClientData();
                    if (loadCDdefer != null) {
                        loadCDdefer.then(function () {
                            _this.clientID = App.Global.Client.ID;
                        });
                    }
                }
            }
            else {
                App.Helper.LoadingClientPromise.then(function () {
                    if (App.Global.Client != null)
                        _this.clientID = App.Global.Client.ID;
                });
            }
        };
        SurveyController.prototype.activate = function ($scope) {
            var _this = this;
            if (!App.Helper.AuthenticationCheck(this.preview) && this.preview == false)
                return false;
            this.$scope = $scope;
            //set participant
            if (this.preview) {
                this.participant = { ID: 0 };
            }
            else {
                this.participant = App.Global.Participant;
            }
            //set client
            this.loadClientID();
            this.setSubScrollableClass();
            $(window).on("resize.doResize", App.Helper.Debounce(function () {
                $scope.$apply(function () {
                    //apply updates
                    //$scope.survey.subScrollClass = ($(window).innerWidth() > 500 || ($(window).innerWidth() < 500 && $(window).innerWidth() < $(window).innerHeight())) ? 'scrollable-content' : '';
                    //if ($(window).innerWidth() > 500 && (this.media != null && (this.media.Type == 2 || this.media.Type == 3)))
                    //    $scope.survey.subScrollClass += ' limit-max-width';
                    $scope.survey.setSubScrollableClass();
                });
            }, 0, $scope));
            var ss = new App.SurveyService(this.$http);
            ss.GetSurveyDetails(this.surveyID, this.participant.ID).then(function (data) {
                if (data == null) {
                    _this.showTranslatedAlert('You already took this survey. Thank you for participating');
                    _this.$timeout(function () {
                        App.Helper.GoToHome();
                    }, 3000);
                }
                else {
                    _this.details = data;
                    _this.enableAutonextSurveySetting = data.EnableAutonext;
                    _this.percentComplete = data.Invite != null ? data.Invite.PercentComplete : 100;
                    _this.cmsAtStart = true;
                    _this.loadMessage(_this.cmsAtStart, null);
                }
            });
        };
        SurveyController.prototype.isAutonextEnabled = function (autonext, qsType, theQuestions) {
            if (autonext == false)
                return false;
            if (!(qsType == 1 || qsType == 6 || qsType == 7))
                return false;
            if (theQuestions == null || theQuestions.length < 1)
                return false; // no question - disable autonext
            //if there is any of these question types in the list of questions - disbale the autonext
            for (var i = 0; i < theQuestions.length; i++) {
                var q = theQuestions[i];
                //any optional questions
                if (q.Required == false) {
                    return false;
                }
                //open ended question - Type: OpenEndedTextSingleRowText = 5, OpenEndedTextCommentBox = 6, 
                //multiple choice checkbox question - Type: MultipleChoiceCheckbox = 3,
                if (q.Type == 5 || q.Type == 6 || q.Type == 3) {
                    return false;
                }
            }
            return true; //autonext!!!
        };
        SurveyController.prototype.startTimer = function () {
            var _this = this;
            //if (this.timer != null)
            //    return;
            this.timer = this.$timeout(function () {
                _this.questionSetTime += 1;
                _this.questionResponseTime += 1;
                _this.startTimer();
            }, 1000);
        };
        SurveyController.prototype.stopTimer = function () {
            if (this.timer != null) {
                this.$timeout.cancel(this.timer);
                this.timer = null;
            }
            this.questionSetTime = 0;
            this.questionResponseTime = 0;
        };
        SurveyController.prototype.resetTimer = function () {
            this.stopTimer();
            this.startTimer();
        };
        SurveyController.prototype.resetQuestionResponseTime = function () {
            this.questionResponseTime = 0;
        };
        SurveyController.prototype.setAudioSource = function (audioSource) {
            this.loadAduioElement();
            this.audioElement.src = audioSource;
        };
        SurveyController.prototype.loadAduioElement = function () {
            if (this.audioElement == null)
                this.audioElement = this.$document[0].getElementById('audioElement');
        };
        SurveyController.prototype.setVideoSource = function (videoSource) {
            this.loadVideoElement();
            this.videoElement.src = videoSource;
        };
        SurveyController.prototype.loadVideoElement = function () {
            if (this.videoElement == null)
                this.videoElement = this.$document[0].getElementById('videoElement');
        };
        SurveyController.prototype.onAnsweredHandler = function (surveyForm, question) {
            this.audiostopped();
            this.autonext(surveyForm, question);
        };
        SurveyController.prototype.autonext = function (form, question) {
            var _this = this;
            if (this.enableAutonext == false)
                return;
            if (question.For == 6) {
                if (question.Answers[0].Selected == true || question.Answers[1].Selected == true)
                    question.IsAnswered = true;
                else
                    question.IsAnswered = false;
            }
            else {
                question.IsAnswered = true;
            }
            for (var i = 0; i < this.questions.length; i++) {
                if (this.questions[i].IsAnswered == false) {
                    if (this.familiarityQuestion != null && this.familiarityQuestion.AllowAnswersFromUnfamilarUser == false && this.familiarityQuestion != this.questions[i]) {
                        if ((this.familiarityQuestion.Answers[1].Selected && this.familiarityQuestion.Answers[1].NumericValue == 2) || (this.familiarityQuestion.Answers[0].Selected && this.familiarityQuestion.Answers[0].NumericValue == 2)) {
                            continue;
                        }
                        else {
                            return;
                        }
                    }
                    else {
                        return;
                    }
                }
            }
            if (this.popQuestions != null && this.popQuestions.length > 0) {
                for (var i = 0; i < this.popQuestions.length; i++) {
                    if (this.popQuestions[i].IsAnswered == false) {
                        return;
                    }
                }
            }
            //all reuired questions are answered - auto proceed to the next page
            this.$timeout(function () {
                if (form.$invalid == false) {
                    _this.next(form);
                }
            }, 200);
        };
        SurveyController.prototype.next = function (form) {
            var _this = this;
            if (this.disableSubmit == true)
                return;
            this.disableSubmit = true;
            //Stop Audio Playback
            this.broadcastAudioStop();
            if (this.cms != null) {
                if (this.cmsAtStart == false && this.showPlaylist == true)
                    this.showPlaylist = false;
                this.loadMessage(this.cmsAtStart, null); //Load next message - will load a questions set if there is no message
                //Stop here if there is another message
                this.disableSubmit = false;
                return true;
            }
            if (this.introMediaLoaded == true && this.details.IntroMedia != null) {
                this.details.IntroMedia = null;
                //Load next quesionset
                this.loadQuestionSet();
                //Enable again the next button
                this.disableSubmit = false;
                return true;
            }
            if (this.outroMediaLoaded == true && this.details.OutroMedia != null) {
                this.details.OutroMedia = null;
                //Load next quesionset
                this.loadQuestionSet(); // this will actually start loading the messages at the end of the survey
                //Enable again the next button
                this.disableSubmit = false;
                return true;
            }
            //Validate
            if (form.$invalid) {
                this.showinvalid = true;
                this.savedSuccessfully = false;
                this.$translate('Please review the highlighted questions').then(function (tr) { _this.message = tr; });
                this.disableSubmit = false;
                this.media = this.savedMedia;
                return false;
            }
            if (this.currentQuestionSet.Type == 3 && this.radioFaceOffPlayed == false) {
                this.savedSuccessfully = false;
                this.$translate('Please listen to at least one station.').then(function (tr) { _this.showTranslatedAlert(tr); });
                this.media = this.savedMedia;
                this.disableSubmit = false;
                return false;
            }
            //valid
            this.showinvalid = false;
            this.savedSuccessfully = true;
            this.message = "";
            //
            //Process final questions
            if (this.finalQuestions != null && this.finalQuestions.length > 0) {
                this.dialog.show({
                    controller: App.PopupquestionsController,
                    templateUrl: 'components/popupquestions/popupquestions.html',
                    locals: {
                        name: this.details.Name,
                        questions: this.finalQuestions,
                        parent: this.self
                    }
                })
                    .then(function (answer) {
                    _this.finalQuestions = answer;
                    //Save questionset answers
                    _this.saveQuestionSetAnswers();
                }, function () {
                    //alert('You cancelled the dialog.');
                });
            }
            else {
                //Save questionset answers
                this.saveQuestionSetAnswers();
            }
        };
        SurveyController.prototype.saveQuestionSetAnswers = function () {
            var _this = this;
            if (this.preview == true) {
                //Success saved
                this.postSaveProcessing();
                //Load next quesionset
                this.loadQuestionSet();
                return;
            }
            var ss = new App.SurveyService(this.$http);
            //var mediaID = this.media != null ? this.media.ID : 0;
            //Put pop questions back 
            var allquestions = [];
            if (this.currentQuestionSet.Type != 3) {
                allquestions = JSON.parse(JSON.stringify(this.questions));
                allquestions = this.appendQuesions(allquestions, this.popQuestions);
                //Set Media IDs on the Questions
                if (this.currentQuestionSet.Medias != null && this.currentQuestionSet.Medias.length > 0) {
                    var media = this.currentQuestionSet.Medias[0];
                    var savedMedia = media;
                    for (var q = 0; q < allquestions.length; q++) {
                        var question = allquestions[q];
                        question.MediaID = media.ID;
                        question.SurveyMediaID = media.SurveyMediaID;
                    }
                }
            }
            //put all media questions back for the radio face-off feature
            if (this.currentQuestionSet.Type == 3 && this.currentQuestionSet.FaceOff != null && this.currentQuestionSet.FaceOff.Stations.length > 0) {
                var stations = this.currentQuestionSet.FaceOff.Stations;
                for (var s = 0; s < stations.length; s++) {
                    var station = stations[s];
                    for (var m = 0; m < station.Medias.length; m++) {
                        var media = station.Medias[m];
                        allquestions = this.appendQuesions(allquestions, media.Questions);
                    }
                }
            }
            //put final questions back
            allquestions = this.appendQuesions(allquestions, this.finalQuestions);
            //update questions
            this.currentQuestionSet.Questions = allquestions;
            //Set QSet Time
            this.currentQuestionSet.TotalDuration = this.questionSetTime;
            this.currentQuestionSet.TimePlayed = Math.round(this.mediaPlayTime);
            //Save answers
            ss.SaveQuestionSetAnswers(this.participant.ID, this.surveyID, this.currentQuestionSet)
                .then(function (response) {
                //Success saved
                _this.postSaveProcessing();
                //Load next quesionset
                _this.loadQuestionSet();
            }, function (err) {
                _this.savedSuccessfully = false;
                //Enable again the next button
                _this.disableSubmit = false;
                if (err.data != null)
                    _this.$translate('Failed to save question answers').then(function (tr) {
                        _this.$translate(err.data.ModelState.error[0].trim()).then(function (trerr) {
                            _this.message = tr + ": " + trerr;
                        });
                    });
                else
                    _this.$translate('Failed to save question answers').then(function (tr) {
                        _this.message = tr;
                    });
            });
        };
        SurveyController.prototype.postSaveProcessing = function () {
            //Update the progress bar
            var percentFraction = Math.round(((100 - this.details.Invite.PercentComplete) / (this.details.QuestionSetIDs.length + this.details.WrapUpQuestionSetIDs.length)));
            this.percentComplete += percentFraction;
            //to avoid problems cased by the rounding...
            if (this.percentComplete >= 99 && this.percentComplete <= 101)
                this.percentComplete = 100;
            //Enable again the next button
            this.disableSubmit = false;
        };
        SurveyController.prototype.loadSurveyMedia = function (media) {
            //Load the media
            this.media = media;
            this.savedMedia = media;
            this.forceListenMedia = this.details.ForcedListenMedia;
            if (this.media.Type == 1) {
                this.setAudioSource(this.media.Url);
            }
            else if (this.media.Type == 2) {
                this.videoSource = this.media.Url;
            }
        };
        SurveyController.prototype.loadQuestionSet = function () {
            var _this = this;
            var ss = new App.SurveyService(this.$http);
            this.currentQsetIndex += 1;
            if (this.details.QuestionSetIDs.length > this.currentQsetIndex) {
                ss.GetSurveyQuestionSet(this.details.QuestionSetIDs[this.currentQsetIndex], this.clientID).then(function (qs) {
                    _this.currentQuestionSet = qs;
                    _this.questions = qs.Questions;
                    _this.enableAutonext = _this.isAutonextEnabled(_this.enableAutonextSurveySetting, qs.Type, _this.questions);
                    _this.currentQuestionSetID = _this.details.QuestionSetIDs[_this.currentQsetIndex];
                    _this.finalQuestions = _this.extractFinalQuestions(_this.questions);
                    _this.radioFaceOffPlayed = false;
                    _this.allStationsFinished = false;
                    if (qs.Type != 3) {
                        _this.popQuestions = _this.extractPopQuestions(_this.questions);
                        _this.familiarityQuestion = _this.getFamiliarityQuestion(_this.questions);
                    }
                    else {
                        _this.disableSubmit = true;
                        _this.$scope.$watch(function () {
                            return _this.allStationsFinished == true;
                        }, function (newVal) {
                            if (newVal) {
                                _this.disableSubmit = false;
                            }
                        });
                    }
                    if (qs.Type != 6 && qs.Type != 3) {
                        if (qs.Medias != null && qs.Medias.length > 0) {
                            //Load the media
                            _this.media = qs.Medias[0]; //always load one media for now - the first one in the list
                            _this.forceListenMedia = _this.details.ForcedListenMedia;
                            if (_this.media.Type == 1) {
                                _this.setAudioSource(_this.media.Url);
                                if (_this.details.DisplayArtist == false)
                                    _this.media.Artist = '';
                                if (_this.details.DisplayTitle == false)
                                    _this.media.Title = '';
                            }
                            else if (_this.media.Type == 2) {
                                _this.videoSource = _this.media.Url;
                                //this.setVideoSource(this.media.Url);
                                if (_this.details.DisplayArtist == false)
                                    _this.media.Artist = '';
                                if (_this.details.DisplayTitle == false)
                                    _this.media.Title = '';
                            }
                            _this.setSubScrollableClass();
                        }
                    }
                    else {
                        _this.media = null;
                    }
                    _this.popupTriggered = false;
                    _this.resetTimer();
                    if (_this.currentQuestionSet.PopupInstructions != null && _this.currentQuestionSet.PopupInstructions.trim() != "")
                        _this.$timeout(function () { _this.showPopupInstructions(); }, 300);
                    _this.$timeout(function () { App.Helper.GoToAnchor('survey_top', 'survey'); }, 500);
                });
            }
            else {
                //Load Wrap Up Question(s)
                var wrapQuestionIndex = this.currentQsetIndex - this.details.QuestionSetIDs.length;
                if (this.details.WrapUpQuestionSetIDs != null && this.details.WrapUpQuestionSetIDs.length > 0 && this.details.WrapUpQuestionSetIDs.length > wrapQuestionIndex) {
                    //load wrap up question
                    ss.GetSurveyQuestionSet(this.details.WrapUpQuestionSetIDs[wrapQuestionIndex], this.clientID).then(function (qs) {
                        _this.currentQuestionSet = qs;
                        _this.questions = qs.Questions;
                        _this.enableAutonext = _this.isAutonextEnabled(_this.enableAutonextSurveySetting, qs.Type, _this.questions);
                        _this.popQuestions = _this.extractPopQuestions(_this.questions);
                        _this.finalQuestions = _this.extractFinalQuestions(_this.questions);
                        _this.familiarityQuestion = _this.getFamiliarityQuestion(_this.questions);
                        _this.currentQuestionSetID = _this.details.WrapUpQuestionSetIDs[wrapQuestionIndex];
                        _this.media = null;
                        _this.popupTriggered = false;
                        _this.resetTimer();
                        if (_this.currentQuestionSet.PopupInstructions != null && _this.currentQuestionSet.PopupInstructions.trim() != "")
                            _this.$timeout(function () { _this.showPopupInstructions(); }, 300);
                    });
                }
                else {
                    //load trailing audio/video
                    if (this.details.OutroMedia != null) {
                        this.loadSurveyMedia(this.details.OutroMedia);
                        this.outroMediaLoaded = true;
                        //reset questions...
                        this.questions = null;
                        this.familiarityQuestion = null;
                        this.popQuestions = null;
                        this.finalQuestions = null;
                        this.enableAutonext = false;
                    }
                    else {
                        if (this.cms == null) {
                            // Load thank you page
                            this.cmsAtStart = false;
                            this.loadMessage(this.cmsAtStart, 'thanks_for_taking_survey.aspx');
                            //Show the playlist if the survey is set to show it
                            this.showPlaylist = this.details.DisplayPlaylist;
                            this.enableAutonext = false;
                        }
                        else {
                            this.showPlaylist = false;
                            this.endOfSurveyRedirect();
                            this.stopTimer();
                        }
                    }
                }
            }
        };
        SurveyController.prototype.endOfSurveyRedirect = function () {
            //redirect to URL if set at survey step 1
            if (this.details.EndOfSurveyRedirectUrl == null
                || this.details.EndOfSurveyRedirectUrl == '') {
                App.Helper.GoToHome(); //go to home
            }
            else {
                this.$window.location.href = this.details.EndOfSurveyRedirectUrl;
            }
        };
        SurveyController.prototype.getFamiliarityQuestion = function (questions) {
            for (var i = 0; i < questions.length; i++) {
                var q = questions[i];
                if (q.For == 4) {
                    q.AllowAnswersFromUnfamilarUser = this.details.AllowAnswersFromUnfamilarUser;
                    return q;
                }
            }
        };
        ;
        SurveyController.prototype.extractQuestions = function (questions, qFors) {
            var qidxs = [];
            for (var i = 0; i < questions.length; i++) {
                var q = questions[i];
                if (qFors.includes(q.For)) {
                    qidxs.push(i);
                }
            }
            var popqs = [];
            //move all items with indexes to a new array
            for (var m = qidxs.length - 1; m >= 0; m--) {
                var psq = questions.splice(qidxs[m], 1);
                popqs.unshift(psq[0]);
            }
            return popqs;
        };
        SurveyController.prototype.extractPopQuestions = function (questions) {
            return this.extractQuestions(questions, [2, 3]); //Popup = 2, and Stop = 3
        };
        SurveyController.prototype.extractFinalQuestions = function (questions) {
            return this.extractQuestions(questions, [9]); //Final Questions = 9
        };
        SurveyController.prototype.appendQuesions = function (questions, appendQuestions) {
            if (appendQuestions != null && questions != null) {
                for (var i = 0; i < appendQuestions.length; i++) {
                    questions.push(appendQuestions[i]);
                }
            }
            return questions;
        };
        SurveyController.prototype.removePopupQuestions = function (popQuestions) {
            var qidxs = [];
            for (var i = 0; i < popQuestions.length; i++) {
                if (popQuestions[i].For == 2) {
                    qidxs.push(i);
                }
            }
            //remove the item
            for (var m = qidxs.length - 1; m >= 0; m--) {
                var psq = popQuestions.splice(qidxs[m], 1);
            }
            return popQuestions;
        };
        SurveyController.prototype.loadMessage = function (start, page) {
            var _this = this;
            var ss = new App.SurveyService(this.$http);
            if (page == null)
                page = '';
            if (page == '' && this.cms != null) {
                page = this.cms.NextPage;
            }
            ss.GetSurveyMessage(this.clientID, this.surveyID, this.participant.ID, page).then(function (m) {
                if (start) {
                    if (m == null || m.Message == undefined || m.Message == '') {
                        _this.cms = null;
                        _this.$translate('Next').then(function (tr) { _this.buttonText = tr; });
                        if (_this.details.IntroMedia != null) {
                            _this.loadSurveyMedia(_this.details.IntroMedia);
                            _this.introMediaLoaded = true;
                        }
                        else {
                            _this.loadQuestionSet();
                        }
                    }
                    else {
                        if (m.Title == "Error") {
                            _this.$translate(m.Title).then(function (tr) {
                                m.Title = tr;
                                _this.$translate(m.Message).then(function (trm) {
                                    m.Message = trm;
                                    _this.cms = m;
                                });
                            });
                        }
                        else {
                            _this.cms = m;
                        }
                        _this.$translate(m.ButtonText).then(function (tr) { _this.buttonText = tr; });
                    }
                }
                else {
                    if (m == null || m.Message == undefined || m.Message == '') {
                        _this.cms = null;
                        _this.endOfSurveyRedirect(); // if no message just go to home page or external redirect page.                       
                    }
                    else {
                        if (m.Title == "Error") {
                            _this.$translate(m.Title).then(function (tr) {
                                m.Title = tr;
                                _this.$translate(m.Message).then(function (trm) {
                                    m.Message = trm;
                                    _this.cms = m;
                                });
                            });
                        }
                        else {
                            _this.cms = m;
                        }
                        if (_this.preview == true && m.ButtonText == 'Finish')
                            _this.hideButton = true;
                        else
                            _this.$translate(m.ButtonText).then(function (tr) { _this.buttonText = tr; });
                    }
                }
                _this.stopTimer();
                _this.$timeout(function () { App.Helper.GoToAnchor('survey_top', 'survey'); }, 500);
            });
        };
        SurveyController.prototype.stop = function () {
            //stop audio if playing
            this.popupTriggered = true; // do not show the popup
            this.broadcastAudioStop();
            //Show the exit message first
            this.cmsAtStart = false;
            this.loadMessage(this.cmsAtStart, 'surveyexit.aspx');
            this.disableSubmit = false;
            this.enableAutonext = false;
        };
        SurveyController.prototype.logout = function () {
            this.authenticationService.logOut();
            App.Helper.GoToLogin();
        };
        SurveyController.prototype.broadcastAudioStop = function () {
            this.rootScope.$broadcast('stopMediaPlayback', {});
            this.media = null;
        };
        SurveyController.prototype.broadcastAudioPause = function () {
            this.rootScope.$broadcast('pauseMediaPlayback', {});
        };
        SurveyController.prototype.broadcastAudioPlay = function () {
            this.rootScope.$broadcast('playMediaPlayback', {});
        };
        SurveyController.prototype.audiostopped = function () {
            var _this = this;
            if (this.popupTriggered)
                return;
            this.popupTriggered = true;
            var percent = this.mediaPlayProgress;
            //if no pop questions - return
            if (this.popQuestions == null || this.popQuestions.length == 0)
                return;
            if (percent > this.details.PopConfig) {
                //Remove all popup questions from the list of popQuestions - leave only the stop questions
                this.removePopupQuestions(this.popQuestions);
                //check if any stop questions have left
                if (this.popQuestions == null || this.popQuestions.length == 0)
                    return;
            }
            //alert("audio has been stopped:" + progress);
            this.dialog.show({
                controller: App.PopupquestionsController,
                templateUrl: 'components/popupquestions/popupquestions.html',
                //parent: this.self,//angular.element(document.body),
                //targetEvent: ev,
                locals: {
                    name: this.details.Name,
                    questions: this.popQuestions,
                    parent: this.self
                }
            })
                .then(function (answer) {
                _this.popQuestions = answer;
                //this.popQuestions - set all popup questions as answered
            }, function () {
                //alert('You cancelled the dialog.');
            });
        };
        SurveyController.prototype.showPopupInstructions = function () {
            var _this = this;
            this.broadcastAudioPause();
            this.dialog.show({
                template: '<md-dialog>' +
                    '  <md-content>' +
                    '       <message content="instructions" title=""></message>' +
                    '  </md-content>' +
                    '  <md-dialog-actions>' +
                    '    <md-button ng-click="closeDialog()">' +
                    '      OK' +
                    '    </md-button>' +
                    '  </md-dialog-actions>' +
                    '</md-dialog>',
                controller: InstructionsController,
                //parent: this.self,
                locals: { instructions: this.currentQuestionSet.PopupInstructions }
            }).then(function () {
                if (_this.details.AutoStartMedia && _this.currentQuestionSet.Type != 3)
                    _this.broadcastAudioPlay();
            });
        };
        SurveyController.prototype.showPopupImage = function (source) {
            this.dialog.show({
                escapeToClose: true,
                clickOutsideToClose: true,
                template: '<md-dialog>' +
                    '  <md-content>' +
                    '    <img style="max-width:100%;" src="' + source + '" />' +
                    '  </md-content>' +
                    '  <md-dialog-actions>' +
                    '    <md-button ng-click="closeDialog()">' +
                    '      OK' +
                    '    </md-button>' +
                    '  </md-dialog-actions>' +
                    '</md-dialog>',
                controller: SimplePopupController,
                //parent: this.self,
                locals: {}
            });
            //.then(() => {});
        };
        SurveyController.$inject = ['$http', '$routeParams', 'authenticationService', '$mdDialog', '$rootScope', '$timeout', 'ngAudio', '$document', '$translate', '$window'];
        return SurveyController;
    }());
    App.SurveyController = SurveyController;
    angular.module('app.survey', [])
        .controller('SurveyController', SurveyController);
    function InstructionsController($scope, $mdDialog, instructions) {
        $scope.instructions = instructions;
        $scope.closeDialog = function () {
            // Easily hides most recent dialog shown...
            // no specific instance reference is needed.
            $mdDialog.hide();
        };
    }
    function SimplePopupController($scope, $mdDialog) {
        $scope.closeDialog = function () {
            // Easily hides most recent dialog shown...
            // no specific instance reference is needed.
            $mdDialog.hide();
        };
    }
})(App || (App = {}));
//public class SurveyDetails {
//    public string Name;
//    public int ID;
//    public bool? DisplayArtist;
//    public bool? DisplayTitle;
//    public bool? DisplayOveralProgress;
//    public bool? DisplayContentProgress;
//    public bool? DisplayPlaylist;
//    public bool? ForcedListenMedia;
//    public byte? PopConfig;
//    public List<int> QuestionSetIDs;
//}
//public class CMS {
//    public string Message = string.Empty;
//    public string Title = string.Empty;
//    public string ButtonText = string.Empty;
//    public string NextPage = string.Empty;
//} 
//# sourceMappingURL=survey.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    var AudioPlayerController = /** @class */ (function () {
        function AudioPlayerController(ngAudio, $scope, ngAudioGlobals, $timeout, $window) {
            this.unmutedVolume = 1;
            $scope.Math = $window.Math;
            this.ngAudio = ngAudio;
            this.ngAudioGlobals = ngAudioGlobals;
            this.$timeout = $timeout;
            this.$scope = $scope;
        }
        Object.defineProperty(AudioPlayerController.prototype, "audioplayprogress", {
            get: function () {
                if (this.audio == null || this.audio.currentTime == null
                    || this.audio.duration == null || this.audio.progress == null
                    || this.playbuttonview == true)
                    return 0;
                if (this.audio.duration == Infinity) {
                    if (this.lengthinseconds > 0)
                        return (this.lengthinseconds / this.audio.currentTime) * 100.0;
                    else
                        return 100.0;
                }
                return this.audio.progress * 100.0;
            },
            set: function (value) {
                //this.audio.progress = value/100.0;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AudioPlayerController.prototype, "audiotime", {
            get: function () {
                if (this.audio == null || this.audio.currentTime == null)
                    return 0;
                return this.audio.currentTime;
            },
            set: function (value) {
                //this.audio.currentTime = value;
            },
            enumerable: true,
            configurable: true
        });
        AudioPlayerController.prototype.stringify = function (source) {
            if (source != null) {
                if (typeof source === 'string' || source instanceof String) {
                    return source; //it is a string
                }
                else {
                    // it's something else
                    return source.toString();
                }
            }
        };
        AudioPlayerController.prototype.$onInit = function () {
            var _this = this;
            if (this.source != null) {
                this.source = this.stringify(this.source);
            }
            this.isPaused = true;
            this.currentAudioPath = this.source;
            this.message = "constructing:" + this.source;
            this.ngAudio.performance = 1;
            this.ngAudio.unlock = true;
            this.ngAudioGlobals.performance = 1;
            this.ngAudioGlobals.unlock = true;
            if (this.ishidden == null)
                this.ishidden = false;
            this.$timeout(function () {
                if (_this.audio == null || (_this.audio != null && _this.audio.audio == null) || (_this.audio != null && _this.audio.audio != null && _this.audio.audio.src != _this.currentAudioPath)) {
                    _this.source = _this.stringify(_this.source);
                    if (_this.playbuttonview == true) {
                        _this.audio = _this.ngAudio.load(_this.source);
                        _this.audio.unbind();
                    }
                    else {
                        _this.audio = _this.ngAudio.load(_this.source);
                        //this.audio.unbind();
                    }
                    _this.audio.loop = 0;
                }
            }, 0);
            //this.activate();
            this.$scope.$watch(function () {
                return _this.audio != null && _this.audio.audio != null && _this.audio.audio.src != _this.currentAudioPath;
            }, function () {
                _this.activate();
            });
            this.$scope.$watch(function () {
                return _this.forcelisten == true && _this.audio != null && _this.audio.currentTime >= _this.forcelistenlength;
            }, function (newVal) {
                if (newVal) {
                    _this.forcelisten = false;
                    _this.setAudioProgressLook();
                }
            });
            this.$scope.$watch(function () {
                return _this.audio != null && ((_this.audio.remaining != null && _this.audio.remaining == 0) || (_this.audio.remaining == null && _this.audio.audio != null && _this.audio.audio.currentTime >= _this.audio.audio.duration));
            }, function (newVal) {
                if (newVal) {
                    _this.reportFirstStop();
                    _this.isPaused = true;
                }
            });
            this.$scope.$on('stopMediaPlayback', function (event, data) {
                if (_this.audio != null && _this.paused() == false)
                    _this.stop();
            });
            this.$scope.$on('pauseMediaPlayback', function (event, data) {
                if (_this.audio != null && _this.paused() == false) {
                    _this.manuallyPaused = true;
                    _this.audio.pause();
                    _this.isPaused = true;
                }
            });
            this.$scope.$on('pauseAllButThisMediaPlayback', function (event, data) {
                if (data.sourceurl != _this.currentAudioPath) {
                    if (_this.audio != null && _this.paused() == false) {
                        _this.manuallyPaused = true;
                        _this.audio.pause();
                        _this.isPaused = true;
                    }
                }
            });
            //this.rootScope.$broadcast('playMediaPlayback', {});
            this.$scope.$on('playMediaPlayback', function (event, data) {
                if (_this.audio != null && _this.paused() == true)
                    _this.play();
            });
            this.$scope.$on('muteAllButThisMediaPlayback', function (event, data) {
                if (data.sourceurl != _this.currentAudioPath) {
                    //if (this.audio != null && this.audio.volume != 0) {
                    if (_this.audio != null && _this.audio.muted != true) {
                        _this.mute2();
                    }
                }
                else {
                    if (_this.audio != null && _this.audio.muted != false) {
                        _this.unmute2();
                    }
                }
            });
        };
        AudioPlayerController.prototype.activate = function () {
            //if (this.audio != undefined)
            //    this.audio.stop();
            //this.ngAudioGlobals.performance = 1;
            //this.ngAudioGlobals.unlock = true;
            //this.message = "activating:" + this.source;
            var _this = this;
            this.isStopReported = false;
            if (this.audio != null && this.audio.audio != null) {
                this.currentAudioPath = this.audio.audio.src;
                if (this.playbuttonview == false && this.ishidden == false) {
                    if (this.autostart) {
                        this.manuallyPaused = false;
                        this.audio.play();
                        this.isPaused = false;
                    }
                    else {
                        this.manuallyPaused = true;
                        this.audio.pause();
                        this.isPaused = true;
                    }
                }
                this.$timeout(function () {
                    if (_this.lengthinseconds == null || _this.lengthinseconds <= 0)
                        _this.lengthinseconds = _this.audio.duration;
                }, 800);
            }
            this.setAudioProgressLook();
        };
        AudioPlayerController.prototype.paused = function () {
            if (this.audio.paused == null) {
                return this.isPaused;
            }
            else {
                return this.audio.paused;
            }
        };
        AudioPlayerController.prototype.playPauseClick = function () {
            if (this.forcelisten) {
                this.play();
            }
            else {
                if (this.paused())
                    this.play();
                else
                    this.stop();
            }
        };
        AudioPlayerController.prototype.setAudioProgressLook = function () {
            if (this.forcelisten)
                this.progressStyle = { 'width': '100%', 'padding': '12px' };
            else
                this.progressStyle = { 'width': '100%' /*, 'padding-top': '8px', 'padding-bottom': '12px', 'padding-left': '4px', 'padding-right' : '4px'*/ };
        };
        AudioPlayerController.prototype.stop = function () {
            var _this = this;
            this.manuallyPaused = true;
            this.audio.pause();
            this.reportFirstStop();
            this.isPaused = true;
            this.$timeout(function () { _this.manuallyPaused = false; }, 500);
        };
        AudioPlayerController.prototype.reportFirstStop = function () {
            if (!this.isStopReported) {
                this.onstop();
                this.isStopReported = true;
            }
        };
        AudioPlayerController.prototype.play = function () {
            if (this.onplay != null)
                this.onplay();
            this.audio.play();
            this.isPaused = false;
        };
        AudioPlayerController.prototype.startMuteTimer = function () {
            var _this = this;
            this.mutetimer = this.$timeout(function () {
                _this.audio.currentTime += 1;
                _this.startMuteTimer();
            }, 1000);
        };
        AudioPlayerController.prototype.stopMuteTimer = function () {
            if (this.mutetimer != null) {
                this.$timeout.cancel(this.mutetimer);
                this.mutetimer = null;
            }
        };
        AudioPlayerController.prototype.mute = function () {
            //this.audio.muting = !this.audio.muting;
            //this.audio.muted = true;
            //this.audio.volume = 0;
            this.audio.pause();
            this.startMuteTimer();
        };
        AudioPlayerController.prototype.unmute = function () {
            //this.audio.muted = false;
            //this.audio.volume = 1;
        };
        AudioPlayerController.prototype.mutetoggle = function () {
            if (this.audio.volume > 0) {
                this.unmutedVolume = this.audio.volume;
                this.audio.volume = 0;
            }
            else {
                this.audio.volume = this.unmutedVolume;
            }
        };
        AudioPlayerController.prototype.muteToggle = function () {
            this.audio.audio.muted = !this.audio.audio.muted;
            this.audio.audio.volume = this.audio.audio.muted ? 0 : 1;
        };
        AudioPlayerController.prototype.mute2 = function () {
            this.audio.audio.muted = true;
            this.audio.audio.volume = 0;
        };
        AudioPlayerController.prototype.unmute2 = function () {
            this.audio.audio.muted = false;
            this.audio.audio.volume = 1;
        };
        AudioPlayerController.$inject = ['ngAudio', '$scope', 'ngAudioGlobals', '$timeout', '$window'];
        return AudioPlayerController;
    }());
    App.AudioPlayerController = AudioPlayerController;
    function AudioPlayerDirective() {
        return {
            scope: {
                source: '=',
                autostart: '=',
                forcelisten: '=',
                artist: '=',
                title: '=',
                onstop: '&onStop',
                onplay: '&onPlay',
                audioplayprogress: '=',
                playbuttonview: '=',
                audiotime: '=',
                lengthinseconds: '=',
                displaycontentprogress: '=',
                forcelistenlength: '=',
                ishidden: '='
            },
            restrict: 'EA',
            controller: AudioPlayerController,
            controllerAs: 'audioplayer',
            bindToController: true,
            templateUrl: 'components/audioplayer/audioplayer.html' //,
            //link:  function(scope, element, attrs, ngModelCtrl) {
            //    var removeBehaviorsRestrictions = function () {
            //        element.load();
            //        window.removeEventListener('keydown', removeBehaviorsRestrictions);
            //        window.removeEventListener('mousedown', removeBehaviorsRestrictions);
            //        window.removeEventListener('touchstart', removeBehaviorsRestrictions);
            //    };
            //    window.addEventListener('keydown', removeBehaviorsRestrictions);
            //    window.addEventListener('mousedown', removeBehaviorsRestrictions);
            //    window.addEventListener('touchstart', removeBehaviorsRestrictions);
            //    scope.pkAudio = element[0];
            //}
        };
    }
    ;
    //class AudioPlayerDirective {
    //    public link: (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => void;
    //    public templateUrl = 'components/audioPlayer/audioPlayer.html';
    //    public scope = {
    //        source: '=',
    //        autostart: '=',
    //        forcelisten: '=',
    //        artist: '=',
    //        title: '=',
    //        onstop: '&onStop'
    //    };
    //    constructor(/*list of dependencies*/) {
    //        // It's important to add `link` to the prototype or you will end up with state issues.
    //        // See http://blog.aaronholmes.net/writing-angularjs-directives-as-typescript-classes/#comment-2111298002 for more information.
    //        AudioPlayerDirective.prototype.link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => {
    //            /*handle all your linking requirements here*/
    //        };
    //    }
    //    public static Factory() {
    //        var directive = (/*list of dependencies*/) => {
    //            return new AudioPlayerDirective(/*list of dependencies*/);
    //        };
    //        directive['$inject'] = ['/*list of dependencies*/'];
    //        return directive;
    //    }
    //}
    angular.module('app.audioplayer', ['ngAudio'])
        .directive('audioplayer', AudioPlayerDirective);
})(App || (App = {}));
//# sourceMappingURL=audioPlayer.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    var PlaylistController = /** @class */ (function () {
        function PlaylistController($http, $routeParams, authenticationService, $document, $rootScope, $timeout) {
            this.authenticationService = authenticationService;
            this.$http = $http;
            this.$document = $document;
            this.$rootScope = $rootScope;
            this.$timeout = $timeout;
        }
        //
        PlaylistController.prototype.$onInit = function () {
            this.data = null;
            this.message = '';
            //Audio Playback Settings
            this.mediaAutoStart = false;
            this.mediaForceListen = false;
            this.mediaPlayProgress = 0;
            this.mediaPlayTime = 0;
            this.displayContentProgress = false;
            //
            this.loadPlaylist();
        };
        PlaylistController.prototype.loadPlaylist = function () {
            var _this = this;
            var ss = new App.SurveyService(this.$http);
            ss.GetSurveySongs(this.surveyid, this.participantid).then(function (d) {
                _this.data = d;
                _this.$timeout(function () {
                    for (var i = 0; i < _this.data.length; i++) {
                        //Activate the player and load the audio.
                        _this.loadAudioAnswer(_this.data[i], false);
                    }
                }, 0);
            });
            //this.data = {
            //    header: "Example Playlist",
            //    playlist: [
            //        { artist: 'First Artist', song: 'First Song' },
            //        { artist: 'Second Artist', song: 'Second Song' }
            //    ]
            //};
        };
        PlaylistController.prototype.getAduioElement = function (id) {
            return this.$document[0].getElementById(id);
        };
        PlaylistController.prototype.pauseAllAudioButThis = function (url) {
            this.$rootScope.$broadcast('pauseAllButThisMediaPlayback', { sourceurl: url });
        };
        PlaylistController.prototype.loadAudioAnswer = function (answer, play) {
            if (answer.Media != null && answer.Media.Type == 1) {
                //Activate audio
                var audioElement = this.getAduioElement(answer.Media.ID.toString());
                if (audioElement != null) {
                    //load audio
                    if (audioElement.src != answer.Media.Url)
                        audioElement.src = answer.Media.Url;
                    //play this audio
                    if (play) {
                        //audioElement.play();
                        //pause any other audio that might be playing 
                        this.pauseAllAudioButThis(answer.Media.Url);
                    }
                    //else {
                    //    audioElement.pause();
                    //}
                }
            }
        };
        PlaylistController.prototype.audioOnPlay = function (answer) {
            this.loadAudioAnswer(answer, true);
        };
        PlaylistController.prototype.audioOnStop = function () {
            return false;
        };
        PlaylistController.$inject = ['$http', '$routeParams', 'authenticationService', '$document', '$rootScope', '$timeout'];
        return PlaylistController;
    }());
    App.PlaylistController = PlaylistController;
    function PlaylistDirective() {
        return {
            scope: {
                surveyid: '=',
                participantid: '=',
                preview: '='
            },
            restrict: 'EA',
            controller: PlaylistController,
            controllerAs: 'playlist',
            bindToController: true,
            templateUrl: 'components/playlist/playlist.html'
        };
    }
    ;
    angular.module('app.playlist', [])
        .directive('playlist', PlaylistDirective);
})(App || (App = {}));
//# sourceMappingURL=playlist.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    angular.module('app.audio', [])
        .controller('AudioController', ['$document', AudioController]);
    function AudioController($document) {
        this.src = 'audioElement'; //'/components/audio/sample.mp3';
        this.autostart = true;
        this.forcelisten = false;
        this.audioElement;
        var $scope = this;
        function activate() {
        }
        ;
        activate();
        this.doplay = function () {
            $scope.audioElement = $document[0].getElementById('audioElement');
            $scope.audioElement.play();
            //$scope.audioElement.pause();
            setTimeout(function () { $scope.audioElement.src = '/components/audio/sample.mp3'; $scope.audioElement.play(); }, 5000);
        };
    }
})(App || (App = {}));
//# sourceMappingURL=audio.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    var VideoPlayerController = /** @class */ (function () {
        function VideoPlayerController($scope, $timeout, $window, $sce, $document, vgFullscreen) {
            this.playsInline = true;
            this.notautoplay = false;
            this.fullScreen = false;
            this.onPlayerReady = function (API) {
                this.media = API;
                ////this.media.mediaElement[0] = this.$document[0].getElementById(this.sourceelement);
                //$('#vg-media-element').empty()
                //$("#videoElement").appendTo('#vgideogular-element');//
                //$("#videoElement").attr('src', this.source);
                //if (this.media.currentState != 'play') {
                //    //Force play if autoplay doesn't work
                //    this.media.play();
                //    this.media.currentState = 'play';
                //}
            };
            this.unmutedVolume = 1;
            this.$timeout = this.$timeout;
            this.$document = $document;
            this.vgFullscreen = vgFullscreen;
            this.$scope = $scope;
        }
        Object.defineProperty(VideoPlayerController.prototype, "audioplayprogress", {
            get: function () {
                if (this.media == null)
                    return 0;
                if (this.media.totalTime == Infinity) {
                    if (this.lengthinseconds > 0)
                        return (this.lengthinseconds / this.media.currentTime) * 100.0;
                    else
                        return 100.0;
                }
                var currentProgress = (this.media.currentTime / this.media.totalTime) * 100.0;
                if (currentProgress > 99)
                    currentProgress = 100;
                return currentProgress;
            },
            set: function (value) {
                //this.media.currentTime = value * this.media.totalTime / 100;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VideoPlayerController.prototype, "audiotime", {
            get: function () {
                if (this.media == null)
                    return 0;
                return this.media.currentTime;
            },
            set: function (value) {
                //this.audio.currentTime = value;
            },
            enumerable: true,
            configurable: true
        });
        VideoPlayerController.prototype.$onInit = function () {
            var _this = this;
            //deal with autoplay attribute needed on android!
            var isAndroid = /Android/i.test(navigator.userAgent);
            if ((!this.autostart) && isAndroid) {
                $('#vg-media-element').addClass('notautoplay');
            }
            else {
                if ($('#vg-media-element').hasClass('notautoplay')) {
                    $('#vg-media-element').removeClass('notautoplay');
                }
            }
            this.theme = App.VideoPlayerTheme; //"/packages/videogular-themes-default/videogular.css";
            //$scope.Math = $window.Math;
            if (typeof this.source === 'string' || this.source instanceof String) {
                // it's a string
            }
            else {
                // it's something else
                this.source = this.source.toString();
            }
            this.currentMediaPath = this.source;
            this.thesource = this.source;
            //if (vgFullscreen.isAvailable) {
            //    vgFullscreen.onchange = this.onFullScreenChange;
            //}
            //$scope.$watch(
            //    () => {
            //        return this.media != null && this.media.mediaElement != null && this.media.mediaElement[0].src != this.currentMediaPath;
            //    }
            //    , () => {
            //        this.activate();
            //    });
            //$scope.$watch(
            //    () => {
            //        return this.media != null && this.media.timeLeft == 0;
            //    }
            //    , (newVal) => {
            //        if (newVal) {
            //            this.reportFirstStop();
            //        }
            //    });
            //$scope.$on('$destroy', () => {
            //$("#videoElement").height(1).width(1).appendTo("#videoContainer");
            //});
            this.$scope.$watch(function () {
                return _this.isForceListen();
            }, function (newVal) {
                if (newVal) {
                    _this.forcelisten = false;
                }
            });
            //attempt to force playback on exit of full screen on iPhone.
            //this.$scope.$watch(
            //    () => {
            //        return this.fullScreen != this.media.isFullScreen;
            //    }
            //    , (newVal) => {
            //        if (newVal) {
            //            this.fullScreen = this.media.isFullScreen;
            //            if (!this.media.isFullScreen) {
            //                //if (this.fullScreenState == "play") {
            //                this.media.play();
            //                    this.$timeout(() => { this.media.play(); }, 2000);
            //                //}
            //            }
            //            else {
            //                this.fullScreenState = this.media.currentState;
            //            }
            //        }
            //    });
            this.$scope.$watch(function () {
                return _this.forcelisten == true && _this.media != null && _this.fullScreen != _this.media.isFullScreen;
            }, function (newVal) {
                if (_this.isForceListen()) {
                    _this.forcelisten = false;
                }
            });
            this.$scope.$on('stopMediaPlayback', function (event, data) {
                if (_this.media != null && _this.media.currentState == "play")
                    _this.stop();
            });
            this.$scope.$on('pauseMediaPlayback', function (event, data) {
                if (_this.media != null && _this.media.currentState == "play") {
                    _this.manuallyPaused = true;
                    _this.media.pause();
                }
            });
            this.$scope.$on('pauseAllButThisMediaPlayback', function (event, data) {
                if (data.sourceurl != _this.currentMediaPath) {
                    if (_this.media != null && _this.media.currentState == "play") {
                        _this.manuallyPaused = true;
                        _this.media.pause();
                    }
                }
            });
            this.$scope.$on('playMediaPlayback', function (event, data) {
                if (_this.media != null && _this.media.currentState == "pause")
                    _this.play();
            });
        };
        VideoPlayerController.prototype.activate = function () {
            this.isStopReported = false;
            if (this.media != null && this.media.mediaElement != null) {
                this.currentMediaPath = this.media.mediaElement[0].src;
                if (this.playbuttonview == false) {
                    if (this.autostart) {
                        this.manuallyPaused = false;
                        this.media.play();
                    }
                    else {
                        this.manuallyPaused = true;
                        this.media.stop();
                    }
                }
            }
        };
        VideoPlayerController.prototype.isForceListen = function () {
            return this.forcelisten == true && this.media != null && Math.round(this.media.currentTime / 1000 + 1) >= this.forcelistenlength;
        };
        VideoPlayerController.prototype.onFullScreenChange = function () {
            var _this = this;
            console.log("full screen:" + this.media.isFullScreen);
            if (!this.media.isFullScreen) {
                if (this.media != null) {
                    if (this.media.currentState != this.fullScreenState)
                        this.$timeout(function () {
                            while (_this.media.currentState != _this.fullScreenState)
                                switch (_this.fullScreenState) {
                                    case "play":
                                        _this.media.play();
                                        break;
                                    case "stop":
                                        _this.media.stop();
                                        break;
                                    case "pause":
                                        _this.media.pause();
                                        break;
                                }
                        }, 200);
                }
            }
        };
        VideoPlayerController.prototype.onUpdateState = function ($state) {
            console.log("state change:" + $state + "  full screen:" + this.media.isFullScreen);
            if ($state == "pause") {
                this.reportFirstStop();
            }
            if (this.isForceListen()) {
                this.forcelisten = false;
            }
            //attempt to force playback on full screen on iPhone.
            //if (this.forcelisten == true)
            //{
            //    this.fullScreenState = $state;
            //}
        };
        VideoPlayerController.prototype.onChangeSource = function ($source) {
            this.activate();
        };
        VideoPlayerController.prototype.reportFirstStop = function () {
            if (!this.isStopReported) {
                this.onstop();
                this.isStopReported = true;
            }
        };
        VideoPlayerController.prototype.stop = function () {
            var _this = this;
            this.manuallyPaused = true;
            this.media.pause();
            this.reportFirstStop();
            this.$timeout(function () { _this.manuallyPaused = false; }, 500);
        };
        VideoPlayerController.prototype.play = function () {
            if (this.onplay != null)
                this.onplay();
            this.media.play();
        };
        VideoPlayerController.prototype.mute = function () {
            this.media.volume = 0;
        };
        VideoPlayerController.prototype.unmute = function () {
            this.media.volume = 1;
        };
        VideoPlayerController.prototype.mutetoggle = function () {
            if (this.media.volume > 0) {
                this.unmutedVolume = this.media.volume;
                this.media.volume = 0;
            }
            else {
                this.media.volume = this.unmutedVolume;
            }
        };
        VideoPlayerController.$inject = ['$scope', '$timeout', '$window', '$sce', '$document', 'vgFullscreen'];
        return VideoPlayerController;
    }());
    App.VideoPlayerController = VideoPlayerController;
    function VideoPlayerDirective() {
        return {
            scope: {
                source: '=',
                sourceelement: '=',
                autostart: '=',
                forcelisten: '=',
                artist: '=',
                title: '=',
                onstop: '&onStop',
                onplay: '&onPlay',
                audioplayprogress: '=',
                playbuttonview: '=',
                audiotime: '=',
                lengthinseconds: '=',
                displaycontentprogress: '=',
                forcelistenlength: '='
            },
            restrict: 'EA',
            controller: VideoPlayerController,
            controllerAs: 'videoPlayer',
            bindToController: true,
            templateUrl: 'components/videoPlayer/videoPlayer.html'
        };
    }
    ;
    angular.module('app.videoPlayer', ['ngAudio'])
        .directive('videoplayer', VideoPlayerDirective);
})(App || (App = {}));
//# sourceMappingURL=videoPlayer.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
var App;
(function (App) {
    var AuthController = /** @class */ (function () {
        function AuthController($http, $translate, $window, $location, $timeout) {
            this.request = {
                Language: "",
                ParticipantID: 0,
                ClientID: App.Global.Client.ID,
                Name: "",
                EMail: "",
                Message: "",
                RemoteAddress: "",
                UserAgent: ""
            };
            this.getFragment = function getFragment() {
                if (window.location.hash.indexOf("#") === 0) {
                    return this.parseQueryString(window.location.hash.substr(1));
                }
                else {
                    return {};
                }
            };
            var fragment = this.getFragment();
            window.location.hash = fragment.state || '';
            window.opener.$windowScope.authCompletedCB(fragment);
            window.close();
        }
        AuthController.prototype.parseQueryString = function (queryString) {
            var data = {}, pairs, pair, separatorIndex, escapedKey, escapedValue, key, value;
            if (queryString === null) {
                return data;
            }
            pairs = queryString.split("&");
            for (var i = 0; i < pairs.length; i++) {
                pair = pairs[i];
                separatorIndex = pair.indexOf("=");
                if (separatorIndex === -1) {
                    escapedKey = pair;
                    escapedValue = null;
                }
                else {
                    escapedKey = pair.substr(0, separatorIndex);
                    escapedValue = pair.substr(separatorIndex + 1);
                }
                key = decodeURIComponent(escapedKey);
                value = decodeURIComponent(escapedValue);
                data[key] = value;
            }
            return data;
        };
        AuthController.prototype.activate = function () {
            if (App.Global.Authenticated && App.Global.Participant != null) {
                if (App.Global.Participant.Name != null)
                    this.request.Name = App.Global.Participant.Name;
                if (App.Global.Participant.EMail != null)
                    this.request.EMail = App.Global.Participant.EMail;
            }
        };
        return AuthController;
    }());
    App.AuthController = AuthController;
    angular.module('app.auth', [])
        .controller('AuthController', AuthController);
})(App || (App = {}));
//# sourceMappingURL=auth.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
/// <reference path="../../scripts/typings/angular/index.d.ts" />
var App;
(function (App) {
    var AutolinkController = /** @class */ (function () {
        function AutolinkController($location, $timeout, $routeParams, authenticationService) {
            this.$routeParams = $routeParams;
            this.authenticationService = authenticationService;
            this.$location = $location;
            this.$timeout = $timeout;
        }
        AutolinkController.prototype.getAutoLinkGuid = function () {
            if (this.$routeParams != undefined && this.$routeParams.guid != undefined && this.$routeParams.guid != "")
                return this.$routeParams.guid;
            return null;
        };
        AutolinkController.prototype.openSurvey = function (id) {
            var _this = this;
            //this.activateAudioPlayer();!!!!!
            var timer = this.$timeout(function () {
                _this.$timeout.cancel(timer);
                _this.$location.path('/survey/' + id);
            }, 100);
        };
        AutolinkController.prototype.loginAutoLink = function () {
            var _this = this;
            var guid = this.getAutoLinkGuid();
            if (guid == null) {
                App.Helper.GoToLogin();
            }
            this.authenticationService.loginAutoLink(guid).then(function (response) {
                App.Helper.LoadParticipantData(App.Helper.GetParticipantDataFromAuth(response));
                if (App.Helper.ForceRescreenCheck()) {
                    _this.$location.path('/signup'); //SiteSubFolder + response.data.callLetters + '#!/signup';
                }
                else {
                    _this.$location.path('/home');
                }
            }, function (err) {
                console.log("autolink error A");
                App.Helper.GoToLogin();
                //if (err != null && err.data != null &&  err.data.error_description != null)
                //    this.message = err.data.error_description;
            });
        };
        AutolinkController.prototype.activate = function () {
            //do authentication by guid - get the guid
            this.loginAutoLink();
        };
        return AutolinkController;
    }());
    App.AutolinkController = AutolinkController;
    angular.module('app.autolink', [])
        .controller('AutolinkController', AutolinkController);
})(App || (App = {}));
//# sourceMappingURL=autolink.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    angular.module('app.unsubscribe', ['ngNewRouter'])
        .controller('UnsubscribeController', ['$rootScope', '$http', '$router', '$location', '$timeout', '$mdDialog', '$translate', 'authenticationService', 'ngAuthSettings', 'cfpLoadingBar', UnsubscribeController]);
    function UnsubscribeController($rootScope, $http, $router, $location, $timeout, $mdDialog, $translate, authenticationService, ngAuthSettings, cfpLoadingBar) {
        var $self = this;
        this.dialog = $mdDialog;
        this.unsubscribeData = {
            ClientCallLetters: "",
            ParticipantID: "",
            Email: "",
            Password: "" //string
        };
        this.isNational = IsNationalLogin;
        this.requiredClass = false;
        this.message = "";
        this.disableSubmit = false;
        this.showPassword = false;
        // Set the default value of inputType
        this.passwordInputType = 'password';
        this.authenticated = App.Global.Authenticated;
        this.emailFormat = App.Global.EmailValidationRegEx;
        // Hide & show password function
        this.hideShowPassword = function () {
            if ($self.passwordInputType == 'password')
                $self.passwordInputType = 'text';
            else
                $self.passwordInputType = 'password';
        };
        this.forgotpass = function () {
            $router.parent.navigate('/forgotpassword');
        };
        this.cancel = function () {
            if ($self.authenticated) {
                $router.parent.navigate('/home');
            }
            else {
                //$router.parent.navigate('/login');
                App.Helper.GoToLogin();
            }
        };
        this.alert = null;
        this.showTranslatedAlert = function (message) {
            $translate(message).then(function (tr) {
                $self.closeAlert();
                $self.alert = $mdDialog.alert()
                    .parent(angular.element(document.body))
                    .clickOutsideToClose(true)
                    .content(tr)
                    .ariaLabel(message)
                    .ok('OK');
                $mdDialog.show($self.alert);
            });
        };
        this.showAlert = function (message) {
            $self.closeAlert();
            $self.alert = $mdDialog.alert()
                .parent(angular.element(document.body))
                .clickOutsideToClose(true)
                .content(message)
                .ariaLabel(message)
                .ok('OK');
            $mdDialog.show($self.alert);
        };
        this.setSuccess = function () {
            $self.disableSubmit = false;
            $self.showTranslatedAlert("You’ve been successfully unsubscribed. We’re sorry to see you go. You’ll no longer receive any further emails or communications from us.");
            authenticationService.logOut();
            $self.GoToLogin();
        };
        this.setError = function (err) {
            $self.disableSubmit = false;
            if (err != null && err.data != null && err.data.ModelState != null)
                $translate('Failed to unsubscribe.').then(function (tr) {
                    $translate(err.data.ModelState.error[0].trim()).then(function (trerr) {
                        $self.showAlert(tr + ": " + trerr);
                    });
                });
            else
                $self.showTranslatedAlert("Failed to unsubscribe.");
        };
        this.unsubscribe = function (form) {
            var _this = this;
            $self.disableSubmit = true;
            //Validate
            if (form.$invalid) {
                $self.requiredClass = true;
                $self.disableSubmit = false;
                if (form.emailInput.$error.pattern == true) {
                    $self.showTranslatedAlert("Please enter a valid e-mail address.");
                }
                else {
                    $self.showTranslatedAlert('Please fill out all of the required fields.');
                }
                return false;
            }
            else {
                $self.message = "";
                $self.requiredClass = false;
            }
            $self.unsubscribeData.ClientCallLetters = ClientCallLetters;
            if ($self.authenticated && App.Global.Participant != null)
                $self.unsubscribeData.ParticipantID = App.Global.Participant.ID;
            authenticationService.unsubscribe($self.unsubscribeData).then(function (response) {
                $self.setSuccess();
            }, function (err) {
                if ($self.isNational) {
                    var ps = new App.ParticipantService($http);
                    ps.GetParticipantEntities($self.unsubscribeData.Email).then(function (rsp) {
                        if (rsp.length < 2) {
                            //send the credentials for the client to which they have subscription
                            if (rsp != null && rsp[0] != null && rsp[0].ClientURL != null)
                                $self.unsubscribeData.ClientCallLetters = rsp[0].ClientURL;
                            authenticationService.unsubscribe($self.unsubscribeData).then(function (response) {
                                $self.setSuccess();
                            }, function (err) {
                                $self.setError(err);
                            });
                        }
                        else {
                            //prompt
                            $translate('Your email address is registered to multiple stations. Please select the station, from which you wish to unsubscribe.').then(function (tr) {
                                _this.dialog.show({
                                    controller: App.EntitypickerController,
                                    templateUrl: 'components/entitypicker/entitypicker.html',
                                    locals: {
                                        message: tr,
                                        entities: rsp,
                                        parent: $self.self
                                    }
                                }).then(function (callLetters) {
                                    $self.unsubscribeData.ClientCallLetters = callLetters;
                                    authenticationService.unsubscribe($self.unsubscribeData).then(function (response) {
                                        $self.setSuccess();
                                    }, function (err) {
                                        $self.setError(err);
                                    });
                                }, function () {
                                    //alert('You cancelled the dialog.');
                                    $self.disableSubmit = false;
                                });
                            });
                        }
                    });
                }
                else {
                    $self.setError(err);
                }
            });
        };
        this.GoToLogin = function () {
            var timer = $timeout(function () {
                $self.closeAlert();
                $timeout.cancel(timer);
                App.Helper.GoToLogin();
            }, 7000);
        };
        this.startTimer = function (redirectPath) {
            var timer = $timeout(function () {
                $self.closeAlert();
                $timeout.cancel(timer);
                $location.path(redirectPath);
            }, 7000);
        };
        this.closeAlert = function (message) {
            if ($self.alert != null)
                $mdDialog.hide($self.alert, "finished");
            $self.alert = null;
        };
        this.change = function () {
            $self.message = "";
        };
        this.placeholderText = "";
        this.focus = function (event) {
            $self.placeholderText = event.target.placeholder;
            event.target.placeholder = "";
            return true;
        };
        this.blur = function (event) {
            event.target.placeholder = $self.placeholderText;
            return true;
        };
        this.authExternalProvider = function (provider) {
            console.log(location);
            '/' + location.pathname.split('/')[1];
            var sitepath = '';
            var paths = location.pathname.split('/');
            for (var i = 0; i < (paths.length - 1); i++) {
                if (paths[i] != null && paths[i] != '')
                    sitepath = sitepath + '/' + paths[i];
            }
            var redirectUri = location.protocol + '//' + location.host + sitepath + '/authcomplete';
            var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
                + "&response_type=token&client_id=" + ngAuthSettings.appClientID
                + "&call_letters=" + ngAuthSettings.clientCallLetters
                + "&redirect_uri=" + redirectUri;
            window.$windowScope = this;
            window.localStorage.setItem('exloginlocationhref', window.location.href);
            window.location.href = externalProviderUrl;
            //var oauthWindow = window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0");
        };
        this.authCompletedCB = function (fragment) {
            if (App.Global.Participant == null)
                App.Global.Participant = {};
            App.Global.Participant.ExternalAuthData = {
                Provider: fragment.provider,
                UserName: fragment.external_user_name,
                ExternalAccessToken: fragment.external_access_token
            };
            if (fragment.haslocalaccount == 'False') {
                //if no local account is found 
                $self.showTranslatedAlert("No active " + fragment.provider + " registration found.");
            }
            else {
                //Obtain access token 
                var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token };
                authenticationService.obtainAccessToken(externalData).then(function (response) {
                    var ps = new App.ParticipantService($http);
                    ps.GetBasicParticipantInfo(App.Global.Participant.ID).then(function (data) {
                        App.Helper.LoadParticipantData(data);
                        App.Global.Authenticated = true;
                        $self.authenticated = App.Global.Authenticated;
                        $location.path('/unsubscribe');
                    });
                }, function (err) {
                    $self.disableSubmit = false;
                    if (err != null && err.data != null && err.data.error_description != null)
                        $self.message = err.data.error_description;
                });
            }
        };
        function activate() {
            var authFragment = window.localStorage.getItem('authfragment');
            if (authFragment != null && authFragment != '') {
                window.localStorage.setItem('authfragment', '');
                $self.authCompletedCB(JSON.parse(authFragment));
                $self.authenticated = App.Global.Authenticated;
                return;
            }
            var rememberedUserName = authenticationService.getUserName();
            if (rememberedUserName != null) {
                $self.unsubscribeData.Email = rememberedUserName;
            }
            $self.authenticated = App.Global.Authenticated;
            cfpLoadingBar.complete();
            $self.authenticated = App.Global.Authenticated;
        }
        ;
        activate();
    }
})(App || (App = {}));
//# sourceMappingURL=unsubscribe.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    var FaqsController = /** @class */ (function () {
        function FaqsController($http, $anchorScroll, $location, $routeParams, $sce, $compile, $timeout, $window) {
            this.data = "";
            this.$http = $http;
            this.$anchorScroll = $anchorScroll;
            this.$anchorScroll.yOffset = 60;
            this.$location = $location;
            this.$sce = $sce;
            this.$compile = $compile;
            this.$routeParams = $routeParams;
            this.$timeout = $timeout;
            this.$window = $window;
            this.calls = ClientCallLetters;
            this.authenticated = App.Global.Authenticated;
        }
        FaqsController.prototype.$onInit = function () {
        };
        FaqsController.prototype.scrollTo = function (event) {
            var location;
            var item = event.target;
            while (item != undefined && location == undefined) {
                if (item.attributes.scrolltarget == undefined)
                    item = item.parentNode;
                else
                    location = item.attributes.scrolltarget.value;
            }
            App.Helper.GoToAnchor(location, 'faqs');
        };
        FaqsController.prototype.activate = function ($scope) {
            if (this.$routeParams != undefined && this.$routeParams.scrolltarget != undefined && this.$routeParams.scrolltarget != "") {
                App.Helper.GoToAnchor(this.$routeParams.scrolltarget);
            }
        };
        FaqsController.$inject = ['$http', '$anchorScroll', '$location', '$routeParams', '$sce', '$compile', '$timeout', '$window'];
        return FaqsController;
    }());
    App.FaqsController = FaqsController;
    function FaqsDirective() {
        return {
            scope: {
                clientid: '=',
                showHeader: '='
            },
            restrict: 'EA',
            controller: FaqsController,
            controllerAs: 'faqs',
            bindToController: true,
            templateUrl: 'components/faqs/faqs.html',
            link: function ($scope) {
                FaqsController.prototype.activate($scope);
            }
        };
    }
    ;
    angular.module('app.faqs', [])
        .controller('FaqsController', FaqsController)
        .directive('faqs', FaqsDirective);
})(App || (App = {}));
//# sourceMappingURL=faqs.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    var TopsongsController = /** @class */ (function () {
        function TopsongsController($http, $anchorScroll, $location, $routeParams, $sce, $compile, $timeout, $window, $document, $rootScope, $scope) {
            this.data = "";
            this.allFormatsView = true;
            this.currentFormatName = "";
            this.$http = $http;
            this.$anchorScroll = $anchorScroll;
            this.$location = $location;
            this.$sce = $sce;
            this.$compile = $compile;
            this.$routeParams = $routeParams;
            this.$timeout = $timeout;
            this.$window = $window;
            this.$scope = $scope;
            this.win = angular.element($window);
            this.$document = $document;
            this.$rootScope = $rootScope;
            if (this.showHeader == undefined)
                this.showHeader = true;
            this.calls = ClientCallLetters;
            //Audio Playback Settings
            this.mediaAutoStart = false;
            this.mediaForceListen = false;
            this.mediaPlayProgress = 0;
            this.mediaPlayTime = 0;
            this.displayContentProgress = false;
            //
        }
        TopsongsController.prototype.$onInit = function () {
            var _this = this;
            this.$scope.$watch(function () {
                return _this.windowWidth != null && _this.win != null && _this.win.width() != _this.windowWidth;
            }, function () {
                _this.calculateBlockWidth();
                if (!_this.$scope.$$phase) {
                    //$digest or $apply
                    _this.$scope.$applyAsync();
                }
            });
        };
        TopsongsController.prototype.activate = function ($scope) {
            if (App.Helper.LoadingClientPromise == null) {
                if (App.Global.Client != null) {
                    $scope.topsongs.showDefaultText = false;
                    //Get Top Songs
                    $scope.topsongs.clientid = App.Global.Client.ID;
                    $scope.topsongs.loadAllFormats();
                }
            }
            else {
                App.Helper.LoadingClientPromise.then(function () {
                    if (App.Global.Client != null) {
                        $scope.topsongs.showDefaultText = false;
                        //Get Top Songs
                        $scope.topsongs.clientid = App.Global.Client.ID;
                        $scope.topsongs.loadAllFormats();
                    }
                    else
                        $scope.topsongs.showDefaultText = true;
                });
            }
        };
        TopsongsController.prototype.calculateBlockWidth = function () {
            this.windowWidth = this.win.width();
            if (this.songs != null && this.songs.length > 0) {
                var numPerRow = this.$window.Math.floor((this.windowWidth * 0.75) / 225);
                while (numPerRow > 1 && (this.songs.length % numPerRow) > 0)
                    numPerRow = numPerRow - 1;
                this.blockWidth = this.$window.Math.floor(100 / numPerRow).toString() + '%';
            }
        };
        TopsongsController.prototype.loadAllFormats = function () {
            var _this = this;
            var rs = new App.ResultService(this.$http);
            rs.GetTopSongs(this.clientid).then(function (data) {
                _this.songs = data;
                _this.allFormatsView = true;
                _this.calculateBlockWidth();
                _this.loadAudioList();
            });
        };
        TopsongsController.prototype.loadFormat = function (fID, fName) {
            var _this = this;
            var rs = new App.ResultService(this.$http);
            rs.GetTopSongsForFormat(this.clientid, fID).then(function (data) {
                _this.songs = data;
                _this.allFormatsView = false;
                _this.currentFormatName = fName;
                _this.calculateBlockWidth();
                _this.loadAudioList();
            });
        };
        TopsongsController.prototype.openTwitter = function (url) {
            this.$window.open(url, '_blank');
        };
        //Audio
        TopsongsController.prototype.loadAudio = function (song, play) {
            if (song.Media != null && song.Media.Type == 1) {
                //Activate audio
                var audioElement = this.getAduioElement(song.Media.ID.toString());
                if (audioElement != null) {
                    //load audio
                    if (audioElement.src != song.Media.Url)
                        audioElement.src = song.Media.Url;
                    //play this audio
                    if (play) {
                        //audioElement.play();
                        //pause any other audio that might be playing 
                        this.pauseAllAudioButThis(song.Media.Url);
                    }
                    //else {
                    //    audioElement.pause();
                    //}
                }
            }
        };
        TopsongsController.prototype.loadAudioList = function () {
            var _this = this;
            var msie = this.$document[0].documentMode;
            // if is IE (documentMode contains IE version)
            if (msie)
                return;
            this.$timeout(function () {
                for (var i = 0; i < _this.songs.length; i++) {
                    //Activate the player and load the audio.
                    _this.loadAudio(_this.songs[i], false);
                }
            }, 0);
        };
        TopsongsController.prototype.pauseAllAudioButThis = function (url) {
            this.$rootScope.$broadcast('pauseAllButThisMediaPlayback', { sourceurl: url });
        };
        TopsongsController.prototype.getAduioElement = function (id) {
            return this.$document[0].getElementById(id);
        };
        TopsongsController.prototype.audioOnPlay = function (answer) {
            this.loadAudio(answer, true);
        };
        TopsongsController.prototype.audioOnStop = function () {
            return false;
        };
        //
        TopsongsController.$inject = ['$http', '$anchorScroll', '$location', '$routeParams', '$sce', '$compile', '$timeout', '$window', '$document', '$rootScope', '$scope'];
        return TopsongsController;
    }());
    App.TopsongsController = TopsongsController;
    function TopsongsDirective() {
        return {
            scope: {
                clientid: '=?',
                showHeader: '=?'
            },
            restrict: 'EA',
            controller: TopsongsController,
            controllerAs: 'topsongs',
            bindToController: true,
            templateUrl: 'components/topsongs/topsongs.html',
            link: function ($scope) {
                TopsongsController.prototype.activate($scope);
            }
        };
    }
    ;
    angular.module('app.topsongs', [])
        .controller('TopsongsController', TopsongsController)
        .directive('topsongs', TopsongsDirective);
})(App || (App = {}));
//# sourceMappingURL=topSongs.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    var TopsongspageController = /** @class */ (function () {
        function TopsongspageController() {
            this.calls = ClientCallLetters;
        }
        TopsongspageController.prototype.activate = function ($scope) {
            if (App.Helper.LoadingClientPromise == null) {
                if (App.Global.Client != null) {
                    //Load Client ID
                    $scope.topsongspage.clientid = App.Global.Client.ID;
                }
            }
            else {
                App.Helper.LoadingClientPromise.then(function () {
                    if (App.Global.Client != null) {
                        $scope.topsongspage.clientid = App.Global.Client.ID;
                    }
                });
            }
        };
        TopsongspageController.$inject = [];
        return TopsongspageController;
    }());
    App.TopsongspageController = TopsongspageController;
    angular.module('app.topsongspage', [])
        .controller('TopsongspageController', TopsongspageController);
})(App || (App = {}));
//# sourceMappingURL=topSongsPage.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
/// <reference path="../../scripts/typings/jquery/jquery.d.ts" />
'use strict';
var App;
(function (App) {
    var PreferencesController = /** @class */ (function () {
        function PreferencesController($http, $location, $anchorScroll, $timeout, $translate, $mdDialog, $rootScope) {
            this.questions = [];
            this.answers = [];
            this.message = '';
            this.cms = null;
            this.showinvalid = false;
            this.disableSubmit = false;
            this.questionResponseTime = 0;
            this.scrollableFooterClass = "scrollable-footer";
            this.alert = null;
            this.$http = $http;
            this.$location = $location;
            this.$anchorScroll = $anchorScroll;
            this.$timeout = $timeout;
            this.$translate = $translate;
            this.$mdDialog = $mdDialog;
            this.$rootScope = $rootScope;
        }
        PreferencesController.prototype.activate = function ($scope) {
            var _this = this;
            if (!App.Helper.AuthenticationCheck())
                return false;
            if (App.Global.DeregisterLocationChangeStartListener == null
                && App.Global.Participant != null && (App.Global.Participant.CompleteRegistration == false || App.Global.Participant.ForceRescreen == true)) {
                //add handler only if we have not added one already. 
                App.Global.DeregisterLocationChangeStartListener = this.$rootScope.$on('$locationChangeStart', function (event, next, current) {
                    if (current.indexOf('/preferences') > 0 && next.indexOf('/preferences') < 0 && App.Global.Participant != null && (App.Global.Participant.CompleteRegistration == false || App.Global.Participant.ForceRescreen == true)) {
                        event.preventDefault();
                    }
                });
                // remove handler on destroy of the local scope.
                //$scope.$on('$destroy', function () {
                //    App.Helper.DeregisterLocationChangeStartListenerIfExists();
                //});
                // remove handler on destroy of the local scope.
                $scope.$on('$locationChangeSuccess', function () {
                    App.Helper.DeregisterLocationChangeStartListenerIfExists();
                });
            }
            this.scrollableFooterClass = (($(window).innerWidth() > $(window).innerHeight())) ? 'scrollable-footer addBrowserButtonBarPadding' : 'scrollable-footer';
            $(window).on("resize.doResize", App.Helper.Debounce(function () {
                $scope.$apply(function () {
                    //apply updates
                    $scope.radioHabits.scrollableFooterClass = (($(window).innerWidth() > $(window).innerHeight())) ? 'scrollable-footer addBrowserButtonBarPadding' : 'scrollable-footer';
                });
            }, 200, $scope));
            //Get radio habit questions
            var ps = new App.ParticipantService(this.$http);
            ps.GetPreferencesQuestions(App.Global.Participant.ID, App.Global.Client.ID).then(function (data) {
                (_this.questions = data);
                //Add child questions
                for (var i = 0; i < _this.questions.length; i++) {
                    var q = _this.questions[i];
                    if (q.ChildIndexes != null) {
                        q.Children = [];
                        for (var ci = 0; ci < q.ChildIndexes.length; ci++) {
                            q.Children.push(_this.questions[q.ChildIndexes[ci]]);
                        }
                    }
                }
                _this.$timeout(function () { App.Helper.ScrollToTop(); }, 1000);
                //return data;
            });
        };
        ;
        PreferencesController.prototype.Save = function (form) {
            var _this = this;
            //prevent double click 
            this.disableSubmit = true;
            //validate required fields
            if (form.$invalid) {
                this.showinvalid = true;
                this.savedSuccessfully = false;
                this.disableSubmit = false;
                this.showTranslatedAlert('Please fill out all of the required fields.');
                return false;
            }
            else {
                this.savedSuccessfully = true;
                this.showinvalid = false;
                this.message = "";
            }
            var ps = new App.ParticipantService(this.$http);
            ps.SavePreferences(App.Global.Participant.ID, App.Global.Client.ID, this.questions)
                .then(function (response) {
                //remove listener if successful save
                App.Helper.DeregisterLocationChangeStartListenerIfExists();
                if (App.Global.Participant.CompleteRegistration == false || App.Global.Participant.ForceRescreen == true) {
                    _this.savedSuccessfully = true;
                    App.Global.Participant.CompleteRegistration = true;
                    App.Global.Participant.ForceRescreen = false;
                    _this.showTranslatedAlert('Your preferences were saved successfully.');
                    _this.startTimer('/home');
                }
                else {
                    ps.GetThanksForSubscribingMessage(App.Global.Participant.ID, App.Global.Client.ID)
                        .then(function (cms) {
                        if (cms != null && cms.Message != null) {
                            _this.cms = cms;
                            _this.$timeout(function () { App.Helper.ScrollToTop(); }, 1000);
                        }
                    });
                    App.Global.Participant.CompleteRegistration = true;
                    App.Global.Participant.ForceRescreen = false;
                }
            }, function (err) {
                _this.savedSuccessfully = false;
                if (err != null && err.data != null && err.data.ModelState != null)
                    _this.$translate('Failed to save user preferences:').then(function (tr) {
                        _this.$translate(err.data.ModelState.error[0].trim()).then(function (trerr) {
                            _this.showAlert(tr + ": " + trerr);
                        });
                    });
                else
                    _this.showTranslatedAlert('Failed to save user preferences');
            });
            this.disableSubmit = false;
        };
        PreferencesController.prototype.goHome = function () {
            App.Helper.GoToHome();
        };
        PreferencesController.prototype.showAlert = function (message) {
            this.closeAlert();
            this.alert = this.$mdDialog.alert()
                .parent(angular.element(document.body))
                .clickOutsideToClose(true)
                .content(message)
                .ariaLabel(message)
                .ok('OK');
            this.$mdDialog.show(self.alert);
        };
        PreferencesController.prototype.showTranslatedAlert = function (message) {
            var _this = this;
            this.$translate(message).then(function (tr) {
                _this.closeAlert();
                _this.alert = _this.$mdDialog.alert()
                    .parent(angular.element(document.body))
                    .clickOutsideToClose(true)
                    .content(tr)
                    .ariaLabel(message)
                    .ok('OK');
                _this.$mdDialog.show(_this.alert);
            });
        };
        PreferencesController.prototype.closeAlert = function () {
            if (this.alert != null)
                this.$mdDialog.hide(this.alert, "finished");
            this.alert = null;
        };
        PreferencesController.prototype.startTimer = function (redirectPath) {
            var _this = this;
            var timer = this.$timeout(function () {
                _this.closeAlert();
                _this.$timeout.cancel(timer);
                _this.$location.path(redirectPath);
            }, 3000);
        };
        PreferencesController.$inject = ['$http', '$location', '$anchorScroll', '$timeout', '$translate', '$mdDialog', '$rootScope'];
        return PreferencesController;
    }());
    App.PreferencesController = PreferencesController;
    angular.module('app.preferences', [])
        .controller('PreferencesController', PreferencesController);
})(App || (App = {}));
//# sourceMappingURL=preferences.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    var RadiofaceoffController = /** @class */ (function () {
        function RadiofaceoffController($http, $anchorScroll, $location, $routeParams, $sce, $compile, $timeout, $window, $document, $rootScope, $scope, $mdDialog, $translate) {
            this.showDefaultText = false;
            this.currentFormatName = "";
            this.finishedStationsCount = 0;
            this.PlayingStation = null;
            this.$http = $http;
            this.$anchorScroll = $anchorScroll;
            this.$location = $location;
            this.$sce = $sce;
            this.$compile = $compile;
            this.$routeParams = $routeParams;
            this.$timeout = $timeout;
            this.$window = $window;
            this.$scope = $scope;
            this.$mdDialog = $mdDialog;
            this.$translate = $translate;
            this.win = angular.element($window);
            this.$document = $document;
            this.$rootScope = $rootScope;
            if (this.showHeader == undefined)
                this.showHeader = true;
            this.calls = ClientCallLetters;
            //Audio Playback Settings
            this.mediaAutoStart = false;
            this.mediaForceListen = false;
            //this.mediaPlayProgress = 0;
            //this.mediaPlayTime = 0;
            this.displayContentProgress = false;
            //
            this.allstationsfinished = false;
            this.displayartist = true;
            this.displaytitle = true;
            this.windowWidth = 0;
            this.windowHeight = 0;
            this.paddingLeft = 0;
        }
        RadiofaceoffController.prototype.$onInit = function () {
            var _this = this;
            this.$scope.$watch(function () {
                return _this.windowWidth != null && _this.win != null && _this.win.width() != _this.windowWidth;
            }, function (newVal) {
                if (newVal) {
                    _this.calculateBlockWidth();
                    _this.calculateNowPlayingAreaBottom();
                    if (!_this.$scope.$$phase) {
                        //$digest or $apply
                        _this.$scope.$apply();
                    }
                }
            });
            this.$scope.$watch(function () {
                return _this.windowHeight != null && _this.win != null && _this.win.height() != _this.windowHeight;
            }, function (newVal) {
                if (newVal) {
                    _this.calculateNowPlayingAreaBottom();
                    if (!_this.$scope.$$phase) {
                        //$digest or $apply
                        _this.$scope.$apply();
                    }
                }
            });
            if (this.data == null)
                this.data = "";
            if (this.displayartist == null)
                this.displayartist = true;
            if (this.displaytitle == null)
                this.displaytitle = true;
            this.loadStations();
        };
        RadiofaceoffController.prototype.calculateBlockWidth = function () {
            this.windowWidth = this.win.width();
            var stations = null;
            if (this.data != null && this.data.FaceOff != null)
                stations = this.data.FaceOff.Stations;
            if (stations != null && stations.length > 0) {
                var numPerRow = this.$window.Math.floor((this.windowWidth * 0.75) / 225);
                while (numPerRow > 1 && (stations.length % numPerRow) > 0) {
                    numPerRow = numPerRow - 1;
                }
                if (numPerRow == 1) {
                    this.paddingLeft = 0;
                }
                else {
                    this.paddingLeft = 1;
                }
                this.blockWidth = this.$window.Math.floor(100 / numPerRow).toString() + '%';
            }
        };
        RadiofaceoffController.prototype.calculateNowPlayingAreaBottom = function () {
            if (this.displayartist == true || this.displaytitle == true) {
                this.windowHeight = this.win.height();
                var footerHeight = 42;
                var scrollElement = angular.element(document.querySelector('#faceoffStations'));
                var scrollHeight = (scrollElement != null && scrollElement[0] != null) ? scrollElement[0].offsetHeight : 0;
                var nowPlayingElement = angular.element(document.querySelector('#foNowPlaying'));
                var nowPlayingHeight = (nowPlayingElement != null && nowPlayingElement[0] != null) ? nowPlayingElement[0].offsetHeight : 0;
                this.visibleScrollHeight = this.calculateVisibleScrollWindow();
                if (this.visibleScrollHeight > scrollHeight) {
                    //this.visibleScrollHeight = this.visibleScrollHeight + nowPlayingHeight;     
                    this.nowPlayingAreaBottom = this.visibleScrollHeight - scrollHeight + nowPlayingHeight + 29;
                }
                else {
                    this.nowPlayingAreaBottom = footerHeight + 51;
                    //this.setSurveyScrollableContentHeight();
                }
            }
        };
        RadiofaceoffController.prototype.setSurveyScrollableContentHeight = function () {
            var scrollElement = angular.element(document.querySelector('#surveyScrollableContent'));
            scrollElement.css('height', 'calc(100% - 116px)');
        };
        RadiofaceoffController.prototype.calculateVisibleScrollWindow = function () {
            var height = this.win.height();
            var footerElements = angular.element('.scrollable-footer');
            for (var i = 0; i < footerElements.length; i++) {
                height = height - footerElements[i].offsetHeight;
            }
            var hElements = angular.element('.scrollable-header');
            for (var h = 0; h < hElements.length; h++) {
                height = height - hElements[h].offsetHeight;
            }
            return height - 51; //51 is the height of the absolute header on top - it is not included in the above calculations
        };
        RadiofaceoffController.prototype.getNextPlayingMediaIndex = function (station) {
            var nextIndex;
            if (station.PlayingMediaIndex == null) {
                nextIndex = 0;
            }
            else {
                nextIndex = station.PlayingMediaIndex + 1;
            }
            return nextIndex;
        };
        //Audio
        RadiofaceoffController.prototype.loadStationMedia = function (station) {
            var nextIndex = this.getNextPlayingMediaIndex(station);
            if (nextIndex >= station.Medias.length) {
                station.NowPlayingTitleArtist = 'Failed to load station media';
                return;
            }
            //load and play the next media from the station list
            var media = station.Medias[nextIndex];
            if (media != null && media.Type == 1) {
                media.mediaPlayProgress = 0;
                media.mediaPlayTime = 0;
                //Activate audio
                var audioElement = this.getAduioElement(station.ID.toString());
                if (audioElement != null) {
                    //load audio
                    if (audioElement.src != media.Url) {
                        audioElement.src = media.Url;
                        station.PlayingMediaIndex = nextIndex;
                        station.PlayingMedia = media;
                    }
                }
            }
        };
        RadiofaceoffController.prototype.loadStations = function () {
            var _this = this;
            var msie = this.$document[0].documentMode;
            // if is IE (documentMode contains IE version)
            if (msie)
                return;
            this.$timeout(function () {
                for (var i = 0; i < _this.data.FaceOff.Stations.length; i++) {
                    //Activate the players and load the audios.
                    _this.loadStationMedia(_this.data.FaceOff.Stations[i]);
                }
                _this.calculateBlockWidth();
                _this.calculateNowPlayingAreaBottom();
            }, 0);
        };
        RadiofaceoffController.prototype.muteAllAudioButThis = function (url) {
            this.$rootScope.$broadcast('muteAllButThisMediaPlayback', { sourceurl: url });
        };
        RadiofaceoffController.prototype.playAll = function () {
            this.$rootScope.$broadcast('playMediaPlayback', {});
        };
        RadiofaceoffController.prototype.pauseAll = function () {
            this.$rootScope.$broadcast('pauseMediaPlayback', {});
        };
        RadiofaceoffController.prototype.getAduioElement = function (id) {
            return this.$document[0].getElementById(id);
        };
        RadiofaceoffController.prototype.audioOnPlay = function (answer) {
            //do nothing for now...
        };
        RadiofaceoffController.prototype.audioOnStop = function (station) {
            //time stamp changing of songs in the currently playing station!
            if (station.ID == this.PlayingStation.ID) {
                this.trackStationTimeStamp();
                this.resetStationPlayTime();
            }
            //start playing the next song from this station
            var audioElement = this.getAduioElement(station.ID.toString());
            var nextIndex = this.getNextPlayingMediaIndex(station);
            if (nextIndex >= station.Medias.length) {
                //the station had finished playing
                station.PlayingMediaIndex = -1;
                this.finishedStationsCount++;
                //check if all stations had finished playing 
                if (this.finishedStationsCount == this.data.FaceOff.Stations.length) {
                    this.allstationsfinished = true;
                }
                return;
            }
            //load and play the next media from the station list
            var media = station.Medias[nextIndex];
            media.mediaPlayProgress = 0;
            media.mediaPlayTime = 0;
            audioElement.src = media.Url;
            station.PlayingMedia = media;
            station.PlayingMediaIndex = nextIndex;
            audioElement.play();
        };
        RadiofaceoffController.prototype.switchStation = function (stationToPlay) {
            var _this = this;
            if (this.allstationsfinished == true)
                return;
            if (this.PlayingStation != null && this.PlayingStation.ID == stationToPlay.ID)
                return;
            //if (stationToPlay.PlayingMediaIndex == -1) // the station had finished playing
            //    return;
            //statrt the playback
            if (this.playbackstarted == false || this.playbackstarted == null) {
                this.$timeout(function () {
                    _this.calculateNowPlayingAreaBottom();
                }, 0);
                this.playStation(stationToPlay);
                //start playback for all stations
                this.playAll();
                this.startTimer();
                this.playbackstarted = true;
                //  
            }
            else {
                this.popQuestionsForMedia(stationToPlay);
            }
        };
        RadiofaceoffController.prototype.playStation = function (stationToPlay) {
            //mute all but the current station/audio 
            this.PlayingStation = stationToPlay;
            this.muteAllAudioButThis(this.PlayingStation.PlayingMedia.Url);
            this.playAll();
            this.resetStationPlayTime();
        };
        //popup questions
        RadiofaceoffController.prototype.removeQuestions = function (questions, forType) {
            var qidxs = [];
            var qFor;
            for (var i = 0; i < questions.length; i++) {
                qFor = questions[i].For;
                if (qFor == forType) {
                    qidxs.push(i);
                }
            }
            //remove the item
            for (var m = qidxs.length - 1; m >= 0; m--) {
                var psq = questions.splice(qidxs[m], 1);
            }
            return questions;
        };
        RadiofaceoffController.prototype.removeFinalQuestions = function (questions) {
            return this.removeQuestions(questions, 9); //9 - Final Questions
        };
        RadiofaceoffController.prototype.removePopupQuestions = function (questions) {
            return this.removeQuestions(questions, 2); //2 - Popup Questions
        };
        RadiofaceoffController.prototype.getFamiliarityQuestion = function (questions) {
            for (var i = 0; i < questions.length; i++) {
                var q = questions[i];
                if (q.For == 4) {
                    q.AllowAnswersFromUnfamilarUser = this.allowanswersfromunfamiliaruser;
                    return q;
                }
            }
        };
        RadiofaceoffController.prototype.popQuestionsForMedia = function (stationToPlay) {
            var _this = this;
            var askQuestions = true;
            var media = this.PlayingStation.PlayingMedia;
            //check if media allows questions
            if (media.IsAskQuestion == false)
                askQuestions = false;
            else if (this.data.Questions == null || this.data.Questions.length == 0)
                askQuestions = false;
            else if (media.Questions != null)
                askQuestions = false;
            if (askQuestions == false) {
                //Time Stamping
                this.trackStationTimeStamp();
                this.playStation(stationToPlay);
                return;
            }
            //clone the questions to the media
            media.Questions = JSON.parse(JSON.stringify(this.data.Questions)); //$.extend(true, {}, this.data.Questions);
            //remove final questions
            this.removeFinalQuestions(media.Questions);
            //if no questions left - return
            if (media.Questions == null || media.Questions.length == 0) {
                //Time Stamping
                this.trackStationTimeStamp();
                this.playStation(stationToPlay);
                return;
            }
            var percent = media.mediaPlayProgress;
            if (percent > this.popconfig) {
                //Remove all popup questions from the list of popQuestions
                this.removePopupQuestions(media.Questions);
                //check if any questions have left
                if (media.Questions == null || media.Questions.length == 0) {
                    //Time Stamping
                    this.trackStationTimeStamp();
                    this.playStation(stationToPlay);
                    return;
                }
            }
            //set familiarity question
            this.familiarityQuestion = this.getFamiliarityQuestion(media.Questions);
            //Set Media IDs on the Questions
            for (var q = 0; q < media.Questions.length; q++) {
                var question = media.Questions[q];
                question.MediaID = media.ID;
                question.SurveyMediaID = media.SurveyMediaID;
            }
            //Time Stamping
            this.trackStationTimeStamp();
            //set dialog start
            //var timestamp = Date.now();
            this.resetQuestionResponseTime();
            //pause all stations playback.
            this.pauseAll();
            this.$mdDialog.show({
                controller: App.PopupquestionsController,
                templateUrl: 'components/popupquestions/popupquestions.html',
                locals: {
                    name: this.data.FaceOff.Title,
                    questions: media.Questions,
                    parent: this
                }
            })
                .then(function (answer) {
                // set questions with answers
                media.Questions = answer;
                //set the timestamping data
                //var duration = Math.round((Date.now() - timestamp) / 1000);//convert to seconds...
                //start the new media playback
                _this.playStation(stationToPlay);
                //
            }, function () {
                //alert('You cancelled the dialog.');
            });
        };
        RadiofaceoffController.prototype.trackStationTimeStamp = function () {
            if (this.PlayingStation.PlayingMediaIndex == -1)
                return;
            if (this.data.FaceOff.TimeStampingData == null)
                this.data.FaceOff.TimeStampingData = '';
            else
                this.data.FaceOff.TimeStampingData += '#';
            var media = this.PlayingStation.PlayingMedia;
            this.data.FaceOff.TimeStampingData += this.PlayingStation.ID + "-" + media.SurveyMediaID + "-" + media.ID + "-" + this.stationPlayTime;
        };
        RadiofaceoffController.prototype.startTimer = function () {
            var _this = this;
            this.timer = this.$timeout(function () {
                _this.questionResponseTime += 1;
                _this.stationPlayTime += 1;
                _this.startTimer();
            }, 1000);
        };
        RadiofaceoffController.prototype.resetQuestionResponseTime = function () {
            this.questionResponseTime = 0;
        };
        RadiofaceoffController.prototype.resetStationPlayTime = function () {
            this.stationPlayTime = 0;
        };
        RadiofaceoffController.prototype.stopTimer = function () {
            if (this.timer != null) {
                this.$timeout.cancel(this.timer);
                this.timer = null;
            }
            this.questionResponseTime = 0;
            this.stationPlayTime = 0;
        };
        RadiofaceoffController.prototype.resetTimer = function () {
            this.stopTimer();
            this.startTimer();
        };
        RadiofaceoffController.$inject = ['$http', '$anchorScroll', '$location', '$routeParams', '$sce', '$compile', '$timeout', '$window', '$document', '$rootScope', '$scope', '$mdDialog', '$translate'];
        return RadiofaceoffController;
    }());
    App.RadiofaceoffController = RadiofaceoffController;
    function RadiofaceoffDirective() {
        return {
            scope: {
                data: '=',
                playbackstarted: '=',
                clientid: '=',
                allowanswersfromunfamiliaruser: '=',
                popconfig: '=',
                displayartist: '=',
                displaytitle: '=',
                allstationsfinished: '='
            },
            restrict: 'EA',
            controller: RadiofaceoffController,
            controllerAs: 'radiofaceoff',
            bindToController: true,
            templateUrl: 'components/radiofaceoff/radiofaceoff.html',
        };
    }
    ;
    angular.module('app.radiofaceoff', [])
        .controller('RadiofaceoffController', RadiofaceoffController)
        .directive('radiofaceoff', RadiofaceoffDirective);
})(App || (App = {}));
//# sourceMappingURL=radiofaceoff.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    var MontagesController = /** @class */ (function () {
        function MontagesController($http, $location, $anchorScroll, $timeout, $translate, $mdDialog, $rootScope, $document) {
            this.data = [];
            this.message = '';
            this.cms = null;
            this.showinvalid = false;
            this.disableSubmit = false;
            this.questionResponseTime = 0;
            this.scrollableFooterClass = "scrollable-footer";
            this.answertype = 1;
            //Audio Playback Settings
            this.mediaAutoStart = false;
            this.mediaForceListen = false;
            this.mediaPlayProgress = 0;
            this.mediaPlayTime = 0;
            this.forcedListenLength = 0;
            this.displayContentProgress = true;
            this.alert = null;
            this.$http = $http;
            this.$location = $location;
            this.$anchorScroll = $anchorScroll;
            this.$timeout = $timeout;
            this.$translate = $translate;
            this.$mdDialog = $mdDialog;
            this.$rootScope = $rootScope;
            this.$document = $document;
        }
        MontagesController.prototype.activate = function ($scope) {
            var _this = this;
            if (!App.Helper.AuthenticationCheck())
                return false;
            if (App.Global.DeregisterLocationChangeStartListener == null
                && App.Global.Participant != null && (App.Global.Participant.CompleteRegistration == false || App.Global.Participant.ForceRescreen == true)) {
                App.Global.DeregisterLocationChangeStartListener = this.$rootScope.$on('$locationChangeStart', function (event, next, current) {
                    if (current.indexOf('/montages') > 0 && next.indexOf('/montages') < 0 && App.Global.Participant != null && (App.Global.Participant.CompleteRegistration == false || App.Global.Participant.ForceRescreen == true)) {
                        event.preventDefault();
                    }
                });
                // remove handler on destroy of the local scope.
                //$scope.$on('$destroy', function () {
                //    App.Helper.DeregisterLocationChangeStartListenerIfExists();
                //});
                // remove handler on destroy of the local scope.
                $scope.$on('$locationChangeSuccess', function () {
                    App.Helper.DeregisterLocationChangeStartListenerIfExists();
                });
            }
            this.scrollableFooterClass = (($(window).innerWidth() > $(window).innerHeight())) ? 'scrollable-footer addBrowserButtonBarPadding' : 'scrollable-footer';
            $(window).on("resize.doResize", App.Helper.Debounce(function () {
                $scope.$apply(function () {
                    //apply updates
                    $scope.montages.scrollableFooterClass = (($(window).innerWidth() > $(window).innerHeight())) ? 'scrollable-footer addBrowserButtonBarPadding' : 'scrollable-footer';
                });
            }, 200, $scope));
            //Get montages
            var ps = new App.ParticipantService(this.$http);
            if (App.Global.Participant != null && App.Global.Participant.ID != null) {
                ps.GetMontagesForParticipant(App.Global.Client.ID, App.Global.Participant.ID).then(function (data) {
                    _this.data = data.Montages;
                    _this.conclusion = data.ConclusionQuestion;
                    _this.verbiage = data.Verbiage;
                    _this.loadAudioList();
                    _this.$timeout(function () { App.Helper.ScrollToTop(); }, 1000);
                });
            }
            else {
                ps.GetMontages(App.Global.Client.ID).then(function (data) {
                    _this.data = data.Montages;
                    _this.conclusion = data.ConclusionQuestion;
                    _this.verbiage = data.Verbiage;
                    _this.loadAudioList();
                    _this.$timeout(function () { App.Helper.ScrollToTop(); }, 1000);
                });
            }
        };
        ;
        MontagesController.prototype.Save = function (form) {
            var _this = this;
            //prevent double click 
            this.disableSubmit = true;
            //validate required fields
            if (form.$invalid) {
                this.showinvalid = true;
                this.savedSuccessfully = false;
                this.disableSubmit = false;
                this.showTranslatedAlert('Please fill out all of the required fields.');
                return false;
            }
            else {
                this.savedSuccessfully = true;
                this.showinvalid = false;
                this.message = "";
            }
            var ps = new App.ParticipantService(this.$http);
            ps.SaveMontages(App.Global.Participant.ID, this.data, this.conclusion)
                .then(function (response) {
                //remove listener if successful save
                App.Helper.DeregisterLocationChangeStartListenerIfExists();
                if (App.Global.Participant.CompleteRegistration == true && App.Global.Participant.ForceRescreen == false) {
                    _this.savedSuccessfully = true;
                    if (App.Global.Client.ShowPreferencesPage == true && App.Global.Client.LimitedParticipantProfile == false) {
                        _this.executeTranslatedPrompt("Your choices were saved successfully. Would you like to review your preferences?", function () { _this.$location.path('/preferences'); }, function () { _this.$location.path('/home'); });
                    }
                    else {
                        App.Global.Participant.CompleteRegistration = true;
                        App.Global.Participant.ForceRescreen = false;
                        _this.showTranslatedAlert('Your choices were saved successfully.');
                        _this.startTimer('/home');
                    }
                }
                else {
                    if (App.Global.Client.ShowPreferencesPage == true)
                        _this.$location.path('/preferences');
                    else {
                        ps.GetThanksForSubscribingMessage(App.Global.Participant.ID, App.Global.Client.ID)
                            .then(function (cms) {
                            if (cms != null && cms.Message != null) {
                                _this.cms = cms;
                                _this.$timeout(function () { App.Helper.ScrollToTop(); }, 1000);
                            }
                        });
                        App.Global.Participant.CompleteRegistration = true;
                        App.Global.Participant.ForceRescreen = false;
                    }
                }
            }, function (err) {
                _this.savedSuccessfully = false;
                if (err != null && err.data != null && err.data.ModelState != null)
                    _this.$translate('Failed to save montages').then(function (tr) {
                        _this.$translate(err.data.ModelState.error[0].trim()).then(function (trerr) {
                            _this.showAlert(tr + ": " + trerr);
                        });
                    });
                else
                    _this.showTranslatedAlert('Failed to save montages');
            });
            this.disableSubmit = false;
        };
        MontagesController.prototype.audioOnPlay = function (montage) {
            //do nothing for now...
            this.loadAudio(montage, true);
        };
        MontagesController.prototype.audioOnStop = function (montage) {
            //do nothing for now...
        };
        MontagesController.prototype.loadAudioList = function () {
            var _this = this;
            var msie = this.$document[0].documentMode;
            // if is IE (documentMode contains IE version)
            if (msie)
                return;
            this.$timeout(function () {
                for (var i = 0; i < _this.data.length; i++) {
                    //Activate the player and load the audio.
                    _this.loadAudio(_this.data[i], false);
                }
            }, 0);
        };
        //Audio
        MontagesController.prototype.loadAudio = function (song, play) {
            if (song.Media != null) {
                //Activate audio
                var audioElement = this.getAduioElement(song.Media.ID.toString());
                if (audioElement != null) {
                    //load audio
                    if (audioElement.src != song.Media.Url)
                        audioElement.src = song.Media.Url;
                    //play this audio
                    if (play) {
                        //audioElement.play();
                        //pause any other audio that might be playing 
                        this.pauseAllAudioButThis(song.Media.Url);
                    }
                }
            }
        };
        MontagesController.prototype.pauseAllAudioButThis = function (url) {
            this.$rootScope.$broadcast('pauseAllButThisMediaPlayback', { sourceurl: url });
        };
        MontagesController.prototype.getAduioElement = function (id) {
            return this.$document[0].getElementById(id);
        };
        MontagesController.prototype.goHome = function () {
            App.Helper.GoToHome();
        };
        MontagesController.prototype.showAlert = function (message) {
            this.closeAlert();
            this.alert = this.$mdDialog.alert()
                .parent(angular.element(document.body))
                .clickOutsideToClose(true)
                .content(message)
                .ariaLabel(message)
                .ok('OK');
            this.$mdDialog.show(self.alert);
        };
        MontagesController.prototype.showTranslatedAlert = function (message) {
            var _this = this;
            this.$translate(message).then(function (tr) {
                _this.closeAlert();
                _this.alert = _this.$mdDialog.alert()
                    .parent(angular.element(document.body))
                    .clickOutsideToClose(true)
                    .content(tr)
                    .ariaLabel(message)
                    .ok('OK');
                _this.$mdDialog.show(_this.alert);
            });
        };
        MontagesController.prototype.executeTranslatedPrompt = function (message, yes, no) {
            var _this = this;
            this.$translate(message).then(function (tr) {
                _this.closeAlert();
                _this.alert = _this.$mdDialog.confirm()
                    .parent(angular.element(document.body))
                    .clickOutsideToClose(true)
                    .content(tr)
                    .ariaLabel('prompt')
                    .ok('Yes')
                    .cancel('No');
                _this.$mdDialog.show(_this.alert).then(yes, no);
            });
        };
        MontagesController.prototype.closeAlert = function () {
            if (this.alert != null)
                this.$mdDialog.hide(this.alert, "finished");
            this.alert = null;
        };
        MontagesController.prototype.startTimer = function (redirectPath) {
            var _this = this;
            var timer = this.$timeout(function () {
                _this.closeAlert();
                _this.$timeout.cancel(timer);
                _this.$location.path(redirectPath);
            }, 3000);
        };
        //
        MontagesController.$inject = ['$http', '$location', '$anchorScroll', '$timeout', '$translate', '$mdDialog', '$rootScope', '$document'];
        return MontagesController;
    }());
    App.MontagesController = MontagesController;
    angular.module('app.montages', [])
        .controller('MontagesController', MontagesController);
})(App || (App = {}));
//# sourceMappingURL=montages.js.map;
/// <reference path="../../scripts/typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    var PersonalinfoController = /** @class */ (function () {
        function PersonalinfoController($rootScope, $http, $router, $location, $timeout, $window, authenticationService, ngAuthSettings, cfpLoadingBar, $mdDialog, $translate, $routeParams) {
            this.$self = this;
            this.loginData = {
                userName: "",
                password: "",
                useRefreshTokens: false,
                personalinfo: true,
                requestid: 0
            };
            this.isNational = IsNationalLogin;
            this.requiredClass = false;
            this.message = "";
            this.disableSubmit = false;
            this.showPassword = false;
            this.emailFormat = App.Global.EmailValidationRegEx;
            // Set the default value of inputType
            this.passwordInputType = 'password';
            this.infoloaded = false;
            this.valid = true;
            this.auth = null;
            this.forgotpass = function () {
                this.$router.parent.navigate('/forgotpassword');
            };
            this.placeholderText = "";
            this.$rootScope = $rootScope;
            this.$http = $http;
            this.$router = $router;
            this.$location = $location;
            this.$timeout = $timeout;
            this.$window = $window;
            this.authenticationService = authenticationService;
            this.ngAuthSettings = ngAuthSettings;
            this.cfpLoadingBar = cfpLoadingBar;
            this.$mdDialog = $mdDialog;
            this.$translate = $translate;
            this.requestID = $routeParams.rid;
            this.auth = $routeParams.auth;
        }
        // Hide & show password function
        PersonalinfoController.prototype.hideShowPassword = function () {
            if (this.passwordInputType == 'password')
                this.passwordInputType = 'text';
            else
                this.passwordInputType = 'password';
        };
        PersonalinfoController.prototype.gotonatnlsignup = function (form) {
            var _this = this;
            var cs = new App.ClientService(this.$http);
            cs.GetNationalClientCallLetters(ClientCallLetters).then(function (callLetters) {
                _this.$window.location.href = '/' + callLetters + '#!/signup';
            });
        };
        PersonalinfoController.prototype.processLogin = function (response) {
            App.Helper.LoadParticipantData(App.Helper.GetParticipantDataFromAuth(response));
            //authorizationdata
            var authorizationdata = response.callLetters + 'authorizationdata';
            window.localStorage.setItem(authorizationdata, JSON.stringify(App.Global.AuthorizationData));
            //participant
            var participant = response.callLetters + 'participant';
            window.localStorage.setItem(participant, JSON.stringify(App.Global.Participant));
            //authenticated
            var authenticated = response.callLetters + 'authenticated';
            window.localStorage.setItem(authenticated, App.Global.Authenticated);
            //set login source 
            App.Global.LoginRoute = '/login';
            var loginroute = response.callLetters + 'loginroute';
            window.localStorage.setItem(loginroute, JSON.stringify(App.Global.LoginRoute));
            var locationChange = response.callLetters + 'deregisterlocationchangestartlistener';
            window.localStorage.setItem(locationChange, App.Global.DeregisterLocationChangeStartListener());
            // Log out the current not existent personalinfo client!
            this.authenticationService.logOut();
            this.authenticated = false;
            App.Global.Client = null;
            //
            this.$window.location.href = SiteSubFolder + response.callLetters + '#!/personalinfo/' + this.requestID + (this.auth == null ? '' : '/' + this.auth);
        };
        PersonalinfoController.prototype.redirectDoNotSellInfo = function () {
            this.$window.open('https://rcssupport.com/en/privacy/?site=tam', '_blank');
        };
        PersonalinfoController.prototype.login = function (form) {
            var _this = this;
            this.disableSubmit = true;
            //Validate
            if (form.$invalid) {
                this.requiredClass = true;
                this.disableSubmit = false;
                if (form.emailInput.$error.pattern == true) {
                    App.Helper.ShowTranslatedAlert("Please enter a valid e-mail address.", this, this.$mdDialog, this.$translate);
                }
                else {
                    App.Helper.ShowTranslatedAlert('Please fill out all of the required fields.', this, this.$mdDialog, this.$translate);
                }
                return false;
            }
            else {
                this.message = "";
                this.requiredClass = false;
            }
            this.loginData.requestid = this.requestID;
            this.authenticationService.login(this.loginData).then(function (response) {
                _this.disableSubmit = false;
                _this.authenticated = true;
                //Load / Re-Load
                ClientCallLetters = response.data.callLetters;
                _this.processLogin(response); //.data);//adan.data);               //adam
            }, function (err) {
                console.log("personalinfo error B");
                _this.disableSubmit = false;
                if (err != null && err.data != null && err.data.error_description != null)
                    _this.message = err.data.error_description;
            });
        };
        PersonalinfoController.prototype.change = function () {
            this.message = "";
        };
        PersonalinfoController.prototype.focus = function (event) {
            this.placeholderText = event.target.placeholder;
            event.target.placeholder = "";
            return true;
        };
        PersonalinfoController.prototype.blur = function (event) {
            event.target.placeholder = this.placeholderText;
            return true;
        };
        PersonalinfoController.prototype.authExternalProvider = function (provider) {
            console.log(location);
            '/' + location.pathname.split('/')[1];
            var sitepath = '';
            var paths = location.pathname.split('/');
            for (var i = 0; i < (paths.length - 1); i++) {
                if (paths[i] != null && paths[i] != '')
                    sitepath = sitepath + '/' + paths[i];
            }
            var redirectUri = location.protocol + '//' + location.host + sitepath + '/authcomplete';
            var externalProviderUrl = this.ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
                + "&response_type=token&client_id=" + this.ngAuthSettings.appClientID
                + "&call_letters=" + this.ngAuthSettings.clientCallLetters
                + "&redirect_uri=" + redirectUri;
            window.$personalinfoWindowScope = this;
            window.localStorage.setItem('exloginlocationhref', window.location.href);
            window.location.href = externalProviderUrl;
            //var oauthWindow = window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0");
        };
        PersonalinfoController.prototype.authCompletedCB = function (fragment) {
            var _this = this;
            if (App.Global.Participant == null)
                App.Global.Participant = {};
            App.Global.Participant.ExternalAuthData = {
                Provider: fragment.provider,
                UserName: fragment.external_user_name,
                ExternalAccessToken: fragment.external_access_token
            };
            if (fragment.haslocalaccount == 'False') {
                //if no local account is found - redirect to register with external credentials.
                //authenticationService.logOut();
                if (fragment.email != null)
                    App.Global.Participant.EMail = fragment.email;
                if (fragment.first_name != null)
                    App.Global.Participant.FirstName = fragment.first_name;
                if (fragment.last_name != null)
                    App.Global.Participant.LastName = fragment.last_name;
                this.$timeout(function () { _this.$location.path('/signup'); }, 500);
            }
            else {
                //Obtain access token and redirect to home
                var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token };
                this.authenticationService.obtainAccessToken(externalData).then(function (response) {
                    var _this = this;
                    var ps = new App.ParticipantService(this.$http);
                    ps.GetBasicParticipantInfo(App.Global.Participant.ID).then(function (data) {
                        App.Helper.LoadParticipantDataAndRedirect(data, _this.$location);
                    });
                }, function (err) {
                    console.log("personalinfo error A");
                    _this.disableSubmit = false;
                    if (err != null && err.data != null && err.data.error_description != null)
                        _this.message = err.data.error_description;
                });
            }
        };
        PersonalinfoController.prototype.loadPersonalInfoData = function () {
            var _this = this;
            var service = new App.ParticipantService(this.$http);
            service.GetPersonalInfoData(this.requestID, App.Global.Participant.ID).then(function (data) {
                _this.info = data;
                _this.infoloaded = true;
            });
        };
        PersonalinfoController.prototype.convertToDate = function (stringDate) {
            var date = new Date(stringDate);
            return date;
        };
        PersonalinfoController.prototype.returnToNotClientSpecificPersonalInfoLogin = function () {
            if (ClientCallLetters.toLowerCase() != 'personalinfo') {
                this.$window.location.href = SiteSubFolder + 'personalinfo#!/personalinfo/' + this.requestID + '/notauth';
            }
        };
        PersonalinfoController.prototype.activate = function () {
            var _this = this;
            //Is request ID provided
            if (this.requestID == null || this.requestID == 0) {
                this.$translate('Invalid Privacy Info Request ID.').then(function (tr) { _this.message = tr; });
                this.valid = false;
                this.authenticated = false;
                //this.returnToNotClientSpecificPersonalInfoLogin();
                return false;
            }
            //Get request
            var service = new App.ParticipantService(this.$http);
            service.GetPersonalInfoRequest(this.requestID).then(function (data) {
                _this.request = data;
                if (_this.request.IsValid == false) {
                    _this.valid = false;
                    _this.authenticated = false;
                    _this.message = _this.request.Message;
                    //this.returnToNotClientSpecificPersonalInfoLogin();
                    return false;
                }
                _this.valid = true;
                if (!App.Global.Authenticated) {
                    _this.authenticated = false;
                    _this.returnToNotClientSpecificPersonalInfoLogin();
                }
                else {
                    if (_this.request.RequesterEmail.trim().toLowerCase() == App.Global.Participant.EMail.trim().toLowerCase()) {
                        //if (ClientCallLetters == App.Global.Client.Ca)
                        // the authenticated participant belongs to the request - load the Personal Info!
                        _this.authenticated = true;
                        _this.loadPersonalInfoData();
                    }
                    else {
                        //the authenticated participant does not belong to the request!
                        App.Helper.ShowTranslatedAlert("The singed in user is not allowed to access the requested personal information. His e-mail and/or name does not match the e-mail and/or name of the personal info requester. Please sign in with an user with e-mail and name matching the personal info requester e-mail and name ", _this, _this.$mdDialog, _this.$translate);
                        _this.authenticationService.logOut();
                        _this.authenticated = false;
                        App.Global.Client = null;
                        _this.returnToNotClientSpecificPersonalInfoLogin();
                    }
                }
            });
            //if (!App.Helper.AuthenticationCheck()) {
            //    this.authenticated = false;
            //}
            //var authFragment = window.localStorage.getItem('authfragment');
            //if (authFragment != null && authFragment != '') {
            //    window.localStorage.setItem('authfragment', '');
            //    this.authCompletedCB(JSON.parse(authFragment));
            //    return;
            //}
            ////cfpLoadingBar.latencyThreshold = 10000;
            ////Set the logo data here
            //if (App.Helper.LoadingClientPromise == null) {
            //    if (App.Global.Client != null && App.Global.Client.Theme != null)
            //        this.logo = App.Global.Client.Theme.LogoPath != null ? App.Global.Client.Theme.LogoPath : "Images/tam.png";//if there is theme load from them
            //    else
            //        this.logo = (App.Global.Client != null && App.Global.Client.LogoPath != null) ? App.Global.Client.LogoPath : "Images/tam.png";//if no theme - load the client logo
            //}
            //else {
            //    App.Helper.LoadingClientPromise.then(() => {
            //        if (App.Global.Client != null && App.Global.Client.Theme != null)
            //            this.logo = App.Global.Client.Theme.LogoPath != null ? App.Global.Client.Theme.LogoPath : "Images/tam.png";//if there is theme load from them
            //        else
            //            this.logo = (App.Global.Client != null && App.Global.Client.LogoPath != null) ? App.Global.Client.LogoPath : "Images/tam.png";//if no theme - load the client logo
            //    });
            //}
            //var rememberedUserName = this.authenticationService.getUserName();
            //if (rememberedUserName != null) {
            //    this.loginData.userName = rememberedUserName;
            //    this.loginData.useRefreshTokens = true;
            //}
            //if (App.Global.Authenticated) {
            //    if (this.loginData.useRefreshTokens) {
            //        this.authenticationService.refreshToken().then(() => {
            //            if (App.Global.Authenticated) {
            //                //authenticationService.fillAuthData();
            //                App.Helper.GoToHome();
            //            }
            //        });
            //    }
            //    else {
            //        this.authenticationService.logOut();
            //    }
            //}
            ////cfpLoadingBar.latencyThreshold = 100;
            //this.cfpLoadingBar.complete();
        };
        PersonalinfoController.$inject = ['$rootScope', '$http', '$router', '$location', '$timeout', '$window',
            'authenticationService', 'ngAuthSettings', 'cfpLoadingBar', '$mdDialog', '$translate',
            '$routeParams'];
        return PersonalinfoController;
    }());
    App.PersonalinfoController = PersonalinfoController;
    angular.module('app.personalinfo', [])
        .controller('PersonalinfoController', PersonalinfoController);
})(App || (App = {}));
//# sourceMappingURL=personalinfo.js.map;
