/// <reference path="typings/angular/index.d.ts" />
'use strict';
var App;
(function (App) {
    angular
        .module('app', [
        'pascalprecht.translate',
        'app.banner',
        'app.header',
        'app.footer',
        'app.blankfooter',
        'app.home',
        'app.homeAward',
        'app.login',
        'app.signup',
        'app.forgotpassword',
        'app.resetpassword',
        'app.about',
        'app.detail',
        'app.disclaimer',
        'app.disclaimerpopup',
        'app.popupquestions',
        'app.entitypicker',
        'app.contactus',
        'app.error',
        'app.radiohabits',
        'app.question',
        'app.mainmenu',
        'app.menubar',
        'app.usermenu',
        'app.survey',
        'app.audioplayer',
        'app.message',
        'app.playlist',
        'app.audio',
        'app.auth',
        'app.autolink',
        'app.unknown',
        'app.unsubscribe',
        'app.ratethemusic',
        'app.faqs',
        'app.topsongs',
        'app.topsongspage',
        'app.preferences',
        'app.radiofaceoff',
        'app.montages',
        'app.personalinfo',
        'ngNewRouter',
        'ui.bootstrap',
        'mobile-angular-ui',
        'angular-loading-bar',
        'angular-bind-html-compile',
        'ngSanitize',
        'pascalprecht.translate',
        'ngStorage',
        'ngAudio',
        'ngAnimate',
        'ngAria',
        'ngMaterial',
        'disableAll',
        'com.2fdevs.videogular',
        'com.2fdevs.videogular.plugins.controls',
        'com.2fdevs.videogular.plugins.overlayplay',
        'com.2fdevs.videogular.plugins.poster',
        'app.videoPlayer',
        'ngPinchZoom',
        'ui.bootstrap',
        'ui.select'
    ])
        .constant('ngAuthSettings', {
        apiServiceBaseUri: WebAPIUrl,
        clientCallLetters: ClientCallLetters,
        appClientID: 'RCS.TestAllMedia.Web.Mobile'
    })
        .run(function ($rootScope, $translate, $localStorage) {
        $rootScope.$on('$translatePartialLoaderStructureChanged', function () {
            $translate.refresh();
        });
    })
        .config(['$locationProvider', '$componentLoaderProvider', '$httpProvider', '$translateProvider', '$translatePartialLoaderProvider', 'cfpLoadingBarProvider', '$localStorageProvider', '$rootScopeProvider', '$sceDelegateProvider', /*'$compileProvider',*/ '$qProvider',
        function ($locationProvider, $componentLoaderProvider, $httpProvider, $translateProvider, $translatePartialLoaderProvider, cfpLoadingBarProvider, $localStorageProvider, $rootScopeProvider, $sceDelegateProvider /*, $compileProvider*/, $qProvider) {
            //$compileProvider.preAssignBindingsEnabled(true);
            $sceDelegateProvider.resourceUrlWhitelist([
                // Allow same origin resource loads.
                'self',
                // Allow JSONP calls that match this pattern
                'https://localhost:44372/**'
            ]); // was: 47024
            //Set the number of digest iterations
            var iterationsLimit = 100;
            $rootScopeProvider.digestTtl(iterationsLimit);
            //
            console.log('in app.ts');
            App.PreviousClientCallLetters = $localStorageProvider.get('callletters');
            if (App.PreviousClientCallLetters == null)
                App.PreviousClientCallLetters = '';
            $localStorageProvider.set('callletters', ClientCallLetters);
            $localStorageProvider.setKeyPrefix(ClientCallLetters);
            $locationProvider.html5Mode(false);
            //configure spinner
            //cfpLoadingBarProvider.latencyThreshold = 500;//10000;
            cfpLoadingBarProvider.spinnerTemplate = '<div id="loading-bar-spinner" class="loading-overlay" style="" ><div class="spinner-icon" ></div> </div>'; //'<div><span class="loading-bar-spinner">Loading...</div>';
            //configure translation
            //$translateProvider
            //    .translations('en', { /* ... */ })
            //    .translations('es', { /* ... */ })
            //    .registerAvailableLanguageKeys(['en', 'es'], {
            //    'en_*': 'en',
            //    'es_*': 'es'
            //})
            //.determinePreferredLanguage()
            //.fallbackLanguage('en');
            $translatePartialLoaderProvider.addPart('SystemText');
            $translateProvider.useLoader('$translatePartialLoader', {
                urlTemplate: WebAPIUrl + 'api/System/translation?part={part}&lang={lang}'
            });
            $translateProvider.useSanitizeValueStrategy('');
            //$translate.proposedLanguage() || $translate.use()
            $translateProvider.determinePreferredLanguage(); //.preferredLanguage('es');
            //$translateProvider.fallbackLanguage('en');
            //configure api
            $componentLoaderProvider.setTemplateMapping(function (name) {
                //name == component name
                if (name.indexOf("view") == 0)
                    return "../../Views/" + name.replace("view", "") + '.cshtml';
                return './components/' + name + '/' + name + '.html';
            });
            $httpProvider.interceptors.push('interceptorService');
            $qProvider.errorOnUnhandledRejections(false);
        }])
        .controller('AppController', ['$router', '$http', '$localStorage', '$location', '$timeout', '$rootScope', '$window', '$translate', '$translatePartialLoader', 'authenticationService', '$scope', '$document', AppController])
        .directive('ngEnter', function () {
        return function (scope, element, attrs) {
            element.bind("keydown keypress", function (event) {
                if (event.which === 13) {
                    scope.$apply(function () {
                        scope.$eval(attrs.ngEnter);
                    });
                    event.preventDefault();
                }
            });
        };
    })
        .directive('focus', function ($timeout, $parse) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                scope.$watch(attrs.focus, function (newValue, oldValue) {
                    if (newValue) {
                        element[0].focus();
                    }
                });
                element.bind("blur", function (e) {
                    $timeout(function () {
                        scope.$apply(attrs.focus + "=false");
                    }, 0);
                });
                element.bind("focus", function (e) {
                    $timeout(function () {
                        scope.$apply(attrs.focus + "=true");
                    }, 0);
                });
            }
        };
    })
        .factory('setfocus', function ($timeout, $window) {
        return function (id) {
            // timeout makes sure that it is invoked after any other event has been triggered.
            // e.g. click events that need to run before the focus or
            // inputs elements that are in a disabled state but are enabled when those events
            // are triggered.
            $timeout(function () {
                var element = $window.document.getElementById(id);
                if (element)
                    element.focus();
            });
        };
    })
        .directive("focusNextOnChange", function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.bind("blur", function () {
                    element.trigger("change");
                    element.next('select').trigger('touchstart');
                    console.log("focus next on blur");
                });
            }
        };
    })
        .directive("focusOnTouch", function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.bind("touchstart", function () {
                    element.focus();
                    console.log("focus on touch");
                });
                $(element, 'option').on("touchstart", function () {
                    element.focus();
                    console.log("focus on option touchstart");
                });
            }
        };
    })
        .directive("unselectOnFocus", function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.bind("focus", function () {
                    $(element[0].options).removeAttr('selected');
                    //$(element, "option").each(function () {
                    //        //if (this.value == $scope.registration.Ethnicity)
                    //   this.selected = "";
                    //    });
                    console.log("unselectOnFocus");
                });
                //element.bind("touchstart", function () {
                //    element.focus();
                //    console.log("focus on touch");
                //});
                //$(element, 'option').on("touchstart", function () {
                //    element.focus();
                //    console.log("focus on option touchstart");
                //});
            }
        };
    })
        .directive("changeOnTouch", function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                $(element, 'option').on("touchend", function () {
                    //element.trigger("change");
                    element.trigger("change");
                    element.next('select').trigger('touchstart');
                    element.next().find('select').trigger('touchstart');
                    console.log("option touchend");
                });
            }
        };
    })
        .directive("select", ["$timeout", "$document", function ($timeout, $document) {
            return {
                restrict: "E",
                require: "?ngModel",
                scope: false,
                link: function (scope, element, attrs, ngModel) {
                    //if (!ngModel) {
                    //    return;
                    //}
                    element.bind("blur", function () {
                        element.trigger("change");
                        if ($(element).attr("force-focus-next") == 'true') {
                            element.next('select').trigger('touchstart');
                            console.log("force focuse next on blur");
                        }
                        //var start = new Date().getTime();
                        //while (new Date().getTime() < start + 1000);
                        var timer2 = $timeout(function () {
                            $timeout.cancel(timer2);
                            element.next('select').trigger('touchstart');
                            element.next().find('select').trigger('touchstart');
                            console.log("delayed touchstart sent");
                        }, 0);
                        console.log("blur");
                    });
                    //element.bind("mouseleave", function () {
                    //    element.trigger("change");
                    //    console.log("mouseleave");
                    //});
                    $(element).on("touchstart", function () {
                        //element.trigger("change");
                        if ($(element).attr("force-focus") == 'true') {
                            //var event = new MouseEvent('mousedown', {
                            //    'view': window,
                            //    'bubbles': true,
                            //    'cancelable': true
                            //});
                            //element.size = 8;
                            //element.dispatchEvent(event);
                            element.show().focus().click();
                            //element.size = 8;
                            //element.focus();
                            //element.trigger("mousedown");
                            //var event = $document.createEvent("MouseEvents");
                            //event.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                            //element.dispatchEvent(event);
                            console.log("element touchstart");
                        }
                    });
                    $(element, 'option').on("touchstart", function () {
                        //element.trigger("change");
                        if ($(element).attr("force-focus") == 'true') {
                            //var event = new MouseEvent('mousedown', {
                            //    'view': window,
                            //    'bubbles': true,
                            //    'cancelable': true
                            //});
                            //var cb = document.getElementById(selectId);
                            //cb.size = 8;
                            //cb.dispatchEvent(event);
                            //element.size = 8;
                            this.focus();
                            //element.trigger("mousedown");
                            //var event = $document.createEvent("MouseEvents");
                            //event.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                            //element.dispatchEvent(event);
                            console.log("option touchstart");
                        }
                    });
                    $(element, 'option').on("touchend", function () {
                        //element.trigger("change");
                        element.trigger("change");
                        if ($(element).attr("force-focus-next") == 'true') {
                            element.next('select').trigger('touchstart');
                            console.log("force focuse next on touchend");
                        }
                    });
                    $(element, 'option').on("touchend", function () {
                        element.trigger("change");
                        console.log("option touchend");
                    });
                    //$(element, 'option').on("mouseenter", function () {
                    //    element.trigger("change");
                    //    console.log("option mouseenter");
                    //});
                    element.bind("change", function () {
                        console.log("change");
                    });
                    //$(element, 'option').on("hover", function () {
                    //    element.trigger("change");
                    //    console.log("option hover");
                    //});
                    //element.bind("focus", function () {
                    //    console.log("focus");
                    //});
                }
            };
        }])
        .directive('focusOnShow', function ($timeout) {
        return {
            restrict: 'A',
            link: function ($scope, $element, $attr) {
                if ($attr.ngShow) {
                    $scope.$watch($attr.ngShow, function (newValue) {
                        if (newValue) {
                            $timeout(function () {
                                $element[0].focus();
                            }, 0);
                        }
                    });
                }
                if ($attr.ngHide) {
                    $scope.$watch($attr.ngHide, function (newValue) {
                        if (!newValue) {
                            $timeout(function () {
                                $element[0].focus();
                            }, 0);
                        }
                    });
                }
            }
        };
    }).directive('focusOn', function ($timeout) {
        return {
            restrict: 'A',
            link: function ($scope, $element, $attr) {
                $scope.$watch($attr.focusOn, function (_focusVal) {
                    $timeout(function () {
                        _focusVal ? $element.focus() :
                            $element.blur();
                    });
                });
            }
        };
    })
        .directive('scrollTo', function ($location, $anchorScroll) {
        return function (scope, element, attrs) {
            element.bind('click', function (event) {
                event.stopPropagation();
                var off = scope.$on('$locationChangeStart', function (ev) {
                    off();
                    ev.preventDefault();
                });
                var location = attrs.scrollTo;
                $location.hash(location);
                $anchorScroll();
            });
        };
    })
        .directive("vgMedia", function () {
        return {
            restrict: "E",
            require: "?ngModel",
            scope: false,
            link: function (scope, element, attrs, ngModel) {
                $(element).empty();
                if ($(element).hasClass('notautoplay')) {
                    $("#videoContainer").find(".videoElementNotAuto").first().removeAttr("style").appendTo(element);
                }
                else {
                    $("#videoContainer").find(".videoElement").first().removeAttr("style").appendTo(element);
                }
                element.on('$destroy', function () {
                    //return the element to the pool
                    if ($(element).hasClass('notautoplay')) {
                        element.find(".videoElementNotAuto").height(1).width(1).appendTo("#videoContainer");
                    }
                    else {
                        element.find(".videoElement").height(1).width(1).appendTo("#videoContainer");
                    }
                });
            }
        };
    })
        .directive("ngAnchor", function anchorDirective($location, $anchorScroll) {
        // Return the directive configuration object.
        return ({
            link: link,
            restrict: "A"
        });
        // I bind the JavaScript events to the view-model.
        function link(scope, element, attributes) {
            // Whenever the attribute changes, we have to update our HREF state
            // to incorporate the new ngAnchor value as the embedded fragment.
            attributes.$observe("ngAnchor", configureHref);
            // Whenever the the location changes, we want to update the HREF value
            // of this link to incorporate the current URL plus the URL-fragment
            // that we are watching in the ngAnchor attribute.
            scope.$on("$locationChangeSuccess", configureHref);
            // I update the HREF attribute to incorporate both the current top-
            // level fragment plus our in-page URL-fragment intent.
            function configureHref() {
                var fragment = (attributes.ngAnchor || "");
                // Strip off the leading # to make the string concatenation
                // handle variable-state inputs (ie, ones that may or may not
                // include the leading pound sign).
                if (fragment.charAt(0) === "#") {
                    fragment = fragment.slice(1);
                }
                // Since the anchor is really the fragment INSIDE the fragment,
                // we have to build two levels of fragment.
                var routeValue = ("#" + $location.url().split("#").shift());
                var fragmentValue = ("#" + fragment);
                attributes.$set("href", (ClientCallLetters + routeValue + fragmentValue));
            }
        }
    });
    //.value('$anchorScroll', angular.noop);
    function AppController($router, $http, $localStorage, $location, $timeout, $rootScope, $window, $translate, $translatePartialLoader, authenticationService, $scope, $document) {
        var _this = this;
        if (ClientCallLetters.toLowerCase() == 'authcomplete')
            return;
        //load translation strings
        $rootScope.$on('$translatePartialLoaderStructureChanged', function () {
            $translate.refresh();
        });
        $translatePartialLoader.addPart('SystemText');
        $timeout(function () {
            $translate.refresh();
        }, 0);
        $scope.videoAutoplay = /Android/i.test(navigator.userAgent);
        //if (typeof (Storage) !== "undefined") {
        //    // verify the browser has localstorage
        //    window.localStorage.clear();
        //}
        //Load Global Data from the browser local storage
        App.Global = new App.GlobalData($localStorage);
        //Clean up old Client data!
        App.Global.Client = null;
        App.Global.IsPasswordReset = false;
        //Load Global Helper 
        App.Helper = new App.GlobalHelper($http, $location, $timeout, $window, $document);
        //create dummy theme holders
        $scope.themeStyle = {};
        $scope.themeHeaderStyle = {};
        $scope.theScrollableStyle = {};
        $scope.appstyles = "";
        //handler for changing the site background
        $scope.$on('setSiteBackground', function (event, data) {
            if (data.background != $scope.appstyles.background) {
            }
        });
        //Personal Info Handling
        if (ClientCallLetters.toLowerCase() == 'personalinfo') {
            if (App.PreviousClientCallLetters != '' && App.PreviousClientCallLetters.toLowerCase() != 'personalinfo'
                && $window.location.hash.includes('notauth') == false) {
                var hash = RouteParams[2] == null ? $window.location.hash : '#!/personalinfo/' + RouteParams[2];
                $window.location.href = SiteSubFolder + App.PreviousClientCallLetters + hash; //go back to the prev client to see if the logged in user qualifies the pi request
            }
        }
        else if (App.PreviousClientCallLetters.toLowerCase() == 'personalinfo' && $window.location.hash.includes('personalinfo')) {
            authenticationService.fillAuthData();
            if (!App.Global.Authenticated) {
                $window.location.href = SiteSubFolder + 'personalinfo' + $window.location.hash + '/notauth'; //reload with personalinfo
            }
        }
        //Load Client Data     
        if (ClientCallLetters.toLowerCase() != 'personalinfo') {
            var loadCDdefer = App.Helper.LoadClientData();
            if (loadCDdefer != null) {
                loadCDdefer.then(function () {
                    //Load the client theme
                    _this.loadTheme();
                    //Load Authentication
                    if (ClientCallLetters == undefined || ClientCallLetters == '' || (App.Global.Client != undefined && ClientCallLetters.toLowerCase() != App.Global.Client.CallLetters.toLowerCase())) {
                        authenticationService.logOut();
                        //App.Global.Reset(); //$sessionStorage.$reset();
                    }
                    else {
                        //Laod Authentication Data
                        authenticationService.fillAuthData();
                    }
                });
            }
        }
        //Load System Data
        App.Helper.LaodSystemData();
        //define routes
        var base = ''; //'/' + ClientCallLetters;
        var theroutes = [
            //{ path: base, redirectTo: '/' },
            { path: base + '/login', component: { header: 'header', main: 'login', footer: 'footer', menu: 'mainmenu' }, as: 'login' },
            { path: base + '/rtm', component: { header: 'header', main: 'ratethemusic', footer: 'footer', menu: 'mainmenu' }, as: 'rtm' },
            { path: base + '/rtm/:login', component: { header: 'header', main: 'ratethemusic', footer: 'footer', menu: 'mainmenu' }, as: 'rtm' },
            { path: base + '/auth', component: { header: 'header', main: 'auth', footer: 'footer', menu: 'mainmenu' }, as: 'auth' },
            { path: base + '/autolink/:guid', component: { header: 'header', main: 'autolink', footer: 'footer', menu: 'mainmenu' }, as: 'autolink' },
            { path: base + '/resetpassword/:guid', component: { header: 'header', main: 'resetpassword', footer: 'footer', menu: 'mainmenu' }, as: 'resetpassword' },
            { path: base + '/signup', component: { header: 'header', main: 'signup', footer: 'footer', menu: 'mainmenu' }, as: 'signup' },
            { path: base + '/forgotpassword', component: { header: 'header', main: 'forgotpassword', footer: 'footer', menu: 'mainmenu' }, as: 'forgotpassword' },
            { path: base + '/home', component: { header: 'header', main: 'home', footer: 'footer', menu: 'mainmenu' }, as: 'home' },
            { path: base + '/homeAward', component: { header: 'header', main: 'homeAward', footer: 'footer', menu: 'mainmenu' }, as: 'homeAward' },
            { path: base + '/about', component: { header: 'header', main: 'about', footer: 'footer', menu: 'mainmenu' }, as: 'about' },
            { path: base + '/detail/:id', component: { header: 'header', main: 'detail', footer: 'footer', menu: 'mainmenu' }, as: 'detail' },
            { path: base + '/disclaimer/:scrolltarget', component: { header: 'header', main: 'disclaimer', footer: 'footer', menu: 'mainmenu' }, as: 'disclaimer' },
            { path: base + '/disclaimer', component: { header: 'header', main: 'disclaimer', footer: 'footer', menu: 'mainmenu' }, as: 'disclaimer' },
            { path: base + '/contactus', component: { header: 'header', main: 'contactus', footer: 'footer', menu: 'mainmenu' }, as: 'contactus' },
            { path: base + '/error/:message', component: { header: 'header', main: 'error', footer: 'footer', menu: 'mainmenu' }, as: 'error' },
            { path: base + '/error', component: { header: 'header', main: 'error', footer: 'footer', menu: 'mainmenu' }, as: 'error' },
            { path: base + '/radiohabits', component: { header: 'header', main: 'radiohabits', footer: 'footer', menu: 'mainmenu' }, as: 'radiohabits' },
            { path: base + '/survey/:id', component: { header: 'header', main: 'survey', footer: 'blankfooter', menu: 'mainmenu' }, as: 'survey' },
            { path: base + '/survey/:id/:preview', component: { header: 'header', main: 'survey', footer: 'blankfooter', menu: 'mainmenu' }, as: 'survey' },
            { path: base + '/audioplayer', component: { header: 'header', main: 'audioplayer', footer: 'footer', menu: 'mainmenu' }, as: 'audioplayer' },
            { path: base + '/message', component: { header: 'header', main: 'message', footer: 'footer', menu: 'mainmenu' }, as: 'message' },
            { path: base + '/playlist', component: { header: 'header', main: 'playlist', footer: 'footer', menu: 'mainmenu' }, as: 'playlist' },
            { path: base + '/audio', component: { header: 'header', main: 'audio', footer: 'footer', menu: 'mainmenu' }, as: 'audio' },
            { path: base + '/unknown', component: { header: 'header', main: 'unknown', footer: 'footer', menu: 'mainmenu' }, as: 'unknown' },
            { path: base + '/unsubscribe', component: { header: 'header', main: 'unsubscribe', footer: 'footer', menu: 'mainmenu' }, as: 'unsubscribe' },
            { path: base + '/ratethemusic/:login', component: { header: 'header', main: 'ratethemusic', footer: 'footer', menu: 'mainmenu' }, as: 'ratethemusic' },
            { path: base + '/ratethemusic', component: { header: 'header', main: 'ratethemusic', footer: 'footer', menu: 'mainmenu' }, as: 'ratethemusic' },
            { path: base + '/faqs/:scrolltarget', component: { header: 'header', main: 'faqs', footer: 'footer', menu: 'mainmenu' }, as: 'faqs' },
            { path: base + '/faqs', component: { header: 'header', main: 'faqs', footer: 'footer', menu: 'mainmenu' }, as: 'faqs' },
            { path: base + '/topsongs', component: { header: 'header', main: 'topsongs', footer: 'footer', menu: 'mainmenu' }, as: 'topsongs' },
            { path: base + '/topsongspage', component: { header: 'header', main: 'topsongspage', footer: 'footer', menu: 'mainmenu' }, as: 'topsongspage' },
            { path: base + '/preferences', component: { header: 'header', main: 'preferences', footer: 'footer', menu: 'mainmenu' }, as: 'preferences' },
            { path: base + '/montages', component: { header: 'header', main: 'montages', footer: 'footer', menu: 'mainmenu' }, as: 'montages' },
            { path: base + '/personalinfo/:rid/:auth', component: { header: 'header', main: 'personalinfo', footer: 'footer', menu: 'mainmenu' }, as: 'personalinfo' },
            { path: base + '/personalinfo/:rid', component: { header: 'header', main: 'personalinfo', footer: 'footer', menu: 'mainmenu' }, as: 'personalinfo' },
            { path: base + '/personalinfo', component: { header: 'header', main: 'personalinfo', footer: 'footer', menu: 'mainmenu' }, as: 'personalinfo' },
            //
            { path: base + '/viewAbout', component: 'viewAbout' },
            { path: base + '/viewLogin', component: 'viewLogin' },
            { path: '/', redirectTo: base + '/login' } //should be last so we can pop it
        ];
        //set default page based on the domain - national or not
        theroutes.pop();
        if (ClientCallLetters.toLowerCase() == 'personalinfo') {
            theroutes.push({ path: '/', redirectTo: base + '/personalinfo/' + RouteParams[2] });
            IsNationalLogin = false;
        }
        else if (ClientCallLetters.toLowerCase() == NationalEntity.toLowerCase()) {
            theroutes.push({ path: '/', redirectTo: base + '/rtm' });
            IsNationalLogin = true;
        }
        else {
            theroutes.push({ path: '/', redirectTo: base + '/login' });
            IsNationalLogin = false;
        }
        $router.config(theroutes);
        //Prototype for Loading Client Theme - Invoked on successful load of client data
        this.loadTheme = function () {
            var optionBackground = "";
            if (App.Global.Client != null && App.Global.Client.Theme != null && App.Global.Client.Theme.BackgroundColor != null) {
                $scope.themeStyle.background = '#' + App.Global.Client.Theme.BackgroundColor;
                $scope.appstyles = "md-dialog {background:" + '#' + App.Global.Client.Theme.BackgroundColor + " !important;";
                optionBackground = " option:not(:checked) { background-color:" + '#' + App.Global.Client.Theme.BackgroundColor + ";}";
                optionBackground += " .ui-select-bootstrap .ui-select-choices-row span { background-color:" + '#' + App.Global.Client.Theme.BackgroundColor + ";}";
                optionBackground += " .ui-select-bootstrap .ui-select-choices-row span:hover { opacity: 0.8; background-color:" + '#' + App.Global.Client.Theme.BackgroundColor + ";}";
                optionBackground += " .input_custom_answer { background-color:" + '#' + App.Global.Client.Theme.BackgroundColor + ";}";
            }
            else {
                $scope.appstyles = "md-dialog {background:;";
                optionBackground = " option:not(:checked) { background-color: rgba(44, 140, 173, 0.8); }";
                optionBackground += " .ui-select-bootstrap .ui-select-choices-row span { background-color: rgba(44, 140, 173, 0.8); }";
                optionBackground += " .ui-select-bootstrap .ui-select-choices-row span:hover { opacity: 0.8; background-color: rgba(44, 140, 173, 0.8); }";
            }
            if (App.Global.Client != null && App.Global.Client.Theme != null && App.Global.Client.Theme.FontColor != null) {
                $scope.themeStyle.color = '#' + App.Global.Client.Theme.FontColor + ' !important';
                $scope.themeStyle['-swebkit-text-fill-color'] = '#' + App.Global.Client.Theme.FontColor; // This might be needed for mobile!!!
                $scope.themeStyle['fill'] = '#' + App.Global.Client.Theme.FontColor;
                //$scope.themeStyle['::-webkit-input-placeholder-color'] =
                //$scope.themeStyle['-moz-placeholder-color'] =
                $scope.themeStyle[':-ms-input-placeholder'] = '{ color: #' + App.Global.Client.Theme.FontColor + "; }";
                //'#' + App.Global.Client.Theme.FontColor;
                $scope.appstyles += " color: " + '#' + App.Global.Client.Theme.FontColor + " !important;";
            }
            else {
                $scope.themeStyle.color = '#FFF !important';
                $scope.themeStyle['-webkit-text-fill-color'] = '#FFF';
                $scope.themeStyle['fill'] = '#FFF';
                $scope.themeStyle['-ms-input-placeholder-color'] = '#FFF';
                $scope.appstyles += " color: #FFF; !important";
            }
            $scope.appstyles += "}";
            if (App.Global.Client != null && App.Global.Client.Theme != null && App.Global.Client.Theme.FontColor != null) {
                $scope.appstyles += " .alink{ color: " + '#' + App.Global.Client.Theme.FontColor + "; } ";
                $scope.appstyles += " input{ color: " + '#' + App.Global.Client.Theme.ControlFontColor + " !important; } ";
                $scope.appstyles += " md-checkbox{color: " + '#' + App.Global.Client.Theme.ControlFontColor + " !important; }";
                $scope.appstyles += " input.ng-empty {color: " + '#' + App.Global.Client.Theme.ControlFontColor + " !important; }";
                $scope.appstyles += " input.ng-untouched {color: " + '#' + App.Global.Client.Theme.ControlFontColor + " !important; }";
                $scope.appstyles += " input.ng-untouched::-webkit-input-placeholder {color: " + '#' + App.Global.Client.Theme.ControlFontColor + " !important; }";
                $scope.appstyles += " button{ color: " + '#' + App.Global.Client.Theme.FontColor + " !important; } ";
                $scope.appstyles += " h3{ color: " + '#' + App.Global.Client.Theme.FontColor + " !important; } ";
                $scope.appstyles += " h4{ color: " + '#' + App.Global.Client.Theme.FontColor + " !important; } ";
                $scope.appstyles += " h5{ color: " + '#' + App.Global.Client.Theme.FontColor + " !important; } ";
            }
            else {
                $scope.appstyles += " .alink{ color: #FFF; } ";
                $scope.appstyles += " input{ color: #FFF !important; } ";
            }
            if (App.Global.Client != null && App.Global.Client.Theme != null && App.Global.Client.Theme.ControlFontColor != null) {
                $scope.appstyles += " select option {color:#" + App.Global.Client.Theme.ControlFontColor + " !important;}";
                $scope.appstyles += " select {color:#" + App.Global.Client.Theme.ControlFontColor + " !important;}";
                $scope.themeStyle['-moz-placeholder-color'] = "#" + App.Global.Client.Theme.ControlFontColor + "!important;";
                $scope.themeStyle['::-webkit-input-placeholder-color'] = "#" + App.Global.Client.Theme.ControlFontColor + "!important;";
                $scope.themeStyle['.ng-touched::-moz-placeholder-color'] = "#" + App.Global.Client.Theme.ControlFontColor + "!important;";
                $scope.themeStyle['.ng-touched::-webkit-input-placeholder-color'] = "#" + App.Global.Client.Theme.ControlFontColor + "!important;";
                $scope.themeStyle['.ng-untouched::-moz-placeholder-color'] = "#" + App.Global.Client.Theme.ControlFontColor + "!important;";
                $scope.themeStyle['.ng-untouched::-webkit-input-placeholder-color'] = "#" + App.Global.Client.Theme.ControlFontColor + "!important;";
            }
            else {
                $scope.appstyles += " ";
            }
            if (App.Global.Client != null && App.Global.Client.Theme != null && App.Global.Client.Theme.HeaderBackgroundColor != null) {
                if (ClientCallLetters.toLowerCase() == NationalEntity.toLowerCase()) {
                    $scope.themeHeaderStyle.background = 'rgba(0, 0, 0, 0.8)';
                    $scope.appstyles += " .header {background: rgba(0, 0, 0, 0.8);";
                }
                else {
                    $scope.themeHeaderStyle.background = '#' + App.Global.Client.Theme.HeaderBackgroundColor;
                    $scope.appstyles += " .header {background:" + '#' + App.Global.Client.Theme.HeaderBackgroundColor + ";";
                }
            }
            else {
                $scope.appstyles += " .header {background: rgba(0, 0, 0, 0.25);";
            }
            if (App.Global.Client != null && App.Global.Client.Theme != null && App.Global.Client.Theme.HeaderFontColor != null) {
                $scope.themeHeaderStyle.color = '#' + App.Global.Client.Theme.HeaderFontColor;
                $scope.appstyles += " color: " + '#' + App.Global.Client.Theme.HeaderFontColor + ";";
            }
            else {
                $scope.themeHeaderStyle.color = '#FFF';
                $scope.appstyles += " color: #FFF;";
            }
            if (App.Global.Client != null && App.Global.Client.Theme != null && App.Global.Client.Theme.HeaderFont != null) {
                $scope.themeHeaderStyle["font-family"] = App.Global.Client.Theme.HeaderFont;
                $scope.appstyles += " font-family: " + App.Global.Client.Theme.HeaderFont + ";";
            }
            if (App.Global.Client != null && App.Global.Client.Theme != null && App.Global.Client.Theme.HeaderFontSize != null) {
                $scope.themeHeaderStyle["font-size"] = App.Global.Client.Theme.HeaderFontSize + 'px';
                $scope.appstyles += "font-size: " + App.Global.Client.Theme.HeaderFontSize + ";";
            }
            $scope.appstyles += "}";
            $scope.appstyles += optionBackground;
            if (App.Global.Client != null && App.Global.Client.Theme != null && App.Global.Client.Theme.HighlightsColor != null) {
                $scope.appstyles += " option:checked {background-color: " + '#' + App.Global.Client.Theme.HighlightsColor + ";}";
                $scope.appstyles += " .ui-select-bootstrap .ui-select-choices-row.active span {background-color: " + '#' + App.Global.Client.Theme.HighlightsColor + ";}";
                //$scope.appstyles += " md-checkbox.md-checked .md-icon {background-color: " + '#' + App.Global.Client.Theme.HighlightsColor + ";}";
                $scope.appstyles += " md-radio-button.md-checked .md-on {background-color: " + '#' + App.Global.Client.Theme.HighlightsColor + ";}";
                $scope.appstyles += " md-radio-button.md-checked .md-off { border-color: " + '#' + App.Global.Client.Theme.HighlightsColor + ";}"; //background-color: " + '#' + App.Global.Client.Theme.HighlightsColor + ";
                $scope.appstyles += " .progress-bar { background: " + '#' + App.Global.Client.Theme.HighlightsColor + ";}";
                $scope.appstyles += " input[type='range'].player::-webkit-slider-thumb { background: " + '#' + App.Global.Client.Theme.HighlightsColor + "; opacity: 0.8; border: 1px solid " + '#' + App.Global.Client.Theme.HighlightsColor + ";}";
                $scope.appstyles += " .invalid-input { color: " + '#' + App.Global.Client.Theme.HighlightsColor + "; -webkit-text-fill-color: " + '#' + App.Global.Client.Theme.HighlightsColor + ";}";
                $scope.appstyles += " .md-button.md-accent { color: #" + App.Global.Client.Theme.HighlightsColor + ";}";
            }
            else {
                $scope.appstyles += " option:checked {background-color: rgba(44, 140, 173, 1);}";
                $scope.appstyles += " .ui-select-bootstrap .ui-select-choices-row.active span {background-color: rgba(44, 140, 173, 1);}";
            }
            if (App.Global.Client != null && App.Global.Client.Theme != null && App.Global.Client.Theme.HeaderFontColor != null) {
                $scope.appstyles += " md-nav-bar.md-default-theme .md-button._md-nav-button.md-unselected, md-nav-bar .md-button._md-nav-button.md-unselected { color: #" + App.Global.Client.Theme.HeaderFontColor + ";}";
                $scope.appstyles += " .md-menu .md-button { color: #" + App.Global.Client.Theme.HeaderFontColor + " !important;}";
                $scope.appstyles += " a.md-button { color: #" + App.Global.Client.Theme.HeaderFontColor + " !important;}";
                $scope.appstyles += " md-menu-item > .md-button { color: #" + App.Global.Client.Theme.HeaderFontColor + " !important;}";
                $scope.appstyles += " md-menu-content.md-default-theme md-menu-item, md-menu-content md-menu-item { color: #" + App.Global.Client.Theme.HeaderFontColor + " !important;}";
            }
            else {
                $scope.appstyles += " md-nav-bar.md-default-theme .md-button._md-nav-button.md-unselected, md-nav-bar .md-button._md-nav-button.md-unselected { color: #fff;}";
                ;
                $scope.appstyles += " .md-menu .md-button { color: #fff;}";
                $scope.appstyles += " md-menu-item > .md-button { color: #fff;}";
            }
            $timeout(function () {
                $scope.theScrollableStyle = { 'top': '50px', 'position': 'fixed', 'height': '100%' };
            }, 500);
        };
    }
})(App || (App = {}));
//# sourceMappingURL=app.js.map;
/// <reference path="typings/angularjs/angular.d.ts" />
var App;
(function (App) {
    var Module = (function () {
        function Module(name, modules) {
            this.mod = angular.module(name, modules);
        }
        Module.prototype.addController = function (name, controller) {
            this.mod.controller(name, controller);
        };
        Module.prototype.addService = function (name, service) {
            this.mod.service(name, service);
        };
        return Module;
    }());
    App.Module = Module; // Module class
})(App || (App = {}));
//# sourceMappingURL=module.js.map;
/// <reference path="typings/angular/index.d.ts" />
/// <reference path="services/service.ts"/>
var App;
(function (App) {
    var GlobalData = /** @class */ (function () {
        function GlobalData($storage) {
            this.storage = $storage;
            this.storage.deregisterlocationchangestartlistener = null;
        }
        Object.defineProperty(GlobalData.prototype, "Client", {
            get: function () {
                return this.storage.client;
                //public class ClientInfo {
                //    public int ID;
                //    public string Name;
                //    public string CallLetters;
                //    public string LogoPath;
                //    public string Slogan;
                //}
            },
            set: function (value) {
                this.storage.client = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GlobalData.prototype, "Participant", {
            get: function () {
                return this.storage.participant;
            },
            set: function (value) {
                this.storage.participant = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GlobalData.prototype, "System", {
            get: function () {
                return this.storage.system;
            },
            set: function (value) {
                this.storage.system = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GlobalData.prototype, "IsPasswordReset", {
            get: function () {
                return this.storage.ispasswordreset;
            },
            set: function (value) {
                this.storage.ispasswordreset = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GlobalData.prototype, "Authenticated", {
            get: function () {
                return this.storage.authenticated;
            },
            set: function (value) {
                this.storage.authenticated = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GlobalData.prototype, "LoginRoute", {
            get: function () {
                return this.storage.loginroute;
            },
            set: function (value) {
                this.storage.loginroute = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GlobalData.prototype, "AuthorizationData", {
            get: function () {
                return this.storage.authorizationdata;
            },
            set: function (value) {
                this.storage.authorizationdata = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GlobalData.prototype, "PrevAuthorizationData", {
            get: function () {
                return this.storage.prevauthorizationdata;
            },
            set: function (value) {
                this.storage.prevauthorizationdata = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GlobalData.prototype, "AuthFragment", {
            get: function () {
                return this.storage.authfragment;
            },
            set: function (value) {
                this.storage.authfragment = value;
            },
            enumerable: true,
            configurable: true
        });
        GlobalData.prototype.Reset = function () {
            this.storage.$reset();
        };
        Object.defineProperty(GlobalData.prototype, "EmailValidationRegEx", {
            get: function () {
                return /\w+([-+.'']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/; // /^[a-z]+[a-z0-9._]+@[a-z]+\.[a-z.]{2,5}$/ ;//   ;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GlobalData.prototype, "DeregisterLocationChangeStartListener", {
            get: function () {
                return this.storage.deregisterlocationchangestartlistener;
            },
            set: function (value) {
                this.storage.deregisterlocationchangestartlistener = value;
            },
            enumerable: true,
            configurable: true
        });
        return GlobalData;
    }());
    App.GlobalData = GlobalData;
    var GlobalHelper = /** @class */ (function () {
        function GlobalHelper($http, $location, $timeout, $window, $document) {
            this.LoadingClientPromise = null;
            //SUPPORT FOR ALERTS
            this.CloseAlert = function (component, $mdDialog) {
                if (component.alert != null)
                    $mdDialog.hide(component.alert, "finished");
                component.alert = null;
            };
            this.ShowTranslatedAlert = function (message, component, $mdDialog, $translate) {
                var _this = this;
                $translate(message).then(function (tr) {
                    _this.CloseAlert(_this, $mdDialog);
                    component.alert = $mdDialog.alert()
                        .parent(angular.element(document.body))
                        .clickOutsideToClose(true)
                        .content(tr)
                        .ariaLabel(message)
                        .ok('OK');
                    $mdDialog.show(component.alert);
                });
            };
            this.$location = $location;
            this.$http = $http;
            this.$timeout = $timeout;
            this.$window = $window;
            this.$document = $document;
            App.Global.DeregisterLocationChangeStartListener = null;
        }
        GlobalHelper.prototype.DeregisterLocationChangeStartListenerIfExists = function () {
            if (App.Global.DeregisterLocationChangeStartListener != null) {
                App.Global.DeregisterLocationChangeStartListener();
                App.Global.DeregisterLocationChangeStartListener = null;
            }
        };
        GlobalHelper.prototype.ScrollToTop = function () {
            var elem = angular.element(document.getElementById('maincontent'));
            var scrollableContentController = elem.controller('scrollableContent');
            var containedElement = document.getElementById('top');
            scrollableContentController.scrollTo(containedElement, 100);
        };
        GlobalHelper.prototype.GoToAnchor = function (anchor) {
            var _this = this;
            var timer1 = this.$timeout(function () {
                _this.$timeout.cancel(timer1);
                _this.$location.hash(anchor); // go to anchor
                //this.$window.innerHeight = this.$document.innerHeight();
                _this.$document[0].getElementById('main-scrollable-div').style['top'] = '0';
            }, 0);
            var timer2 = this.$timeout(function () {
                _this.$timeout.cancel(timer2);
                _this.$location.hash(''); //clear the anchor
                //this.$window.innerHeight = this.$document.innerHeight();
                //angular.element(this.$document[0].getElementById('main-scrollable-div')).css('top', '50px');
                _this.$document[0].getElementById('main-scrollable-div').style['top'] = '50px';
            }, 10);
        };
        GlobalHelper.prototype.GoToLogin = function (login) {
            var logstr = login != null && App.Global.LoginRoute == '/rtm' ? '/' + login.toString() : '';
            if (IsNationalLogin == true && (ClientCallLetters.toLowerCase() == NationalEntity.toLowerCase() || App.Global.LoginRoute == '/rtm')) {
                document.location.href = SiteSubFolder + NationalEntity + '#!' + App.Global.LoginRoute + logstr;
            }
            else {
                if (App.Global.LoginRoute == null) {
                    this.redirect('/login');
                }
                else {
                    this.redirect(App.Global.LoginRoute + logstr);
                }
            }
        };
        GlobalHelper.prototype.GoToHome = function () {
            //this.location.path('/home');
            this.redirect('/home');
        };
        GlobalHelper.prototype.GoToSignup = function () {
            //this.location.path('/home');
            this.redirect('/home');
        };
        GlobalHelper.prototype.GoToUnknown = function () {
            this.redirect('/unknown');
        };
        GlobalHelper.prototype.GoToMaint = function () {
            window.location.href = 'https://www.testallmedia.com/Maintenance.aspx';
        };
        GlobalHelper.prototype.GoToError = function (error) {
            var errorPath = '/error';
            if (error != null || undefined)
                errorPath = errorPath + '/' + error;
            this.redirect(errorPath);
            //this.location.path(errorPath);
        };
        GlobalHelper.prototype.GetRandomInt = function (max) {
            return Math.floor(Math.random() * Math.floor(max));
        };
        GlobalHelper.prototype.AuthenticationCheck = function (preview) {
            if (!App.Global.Authenticated) {
                if (preview == null || preview == false)
                    this.redirect('/login');
                return false;
            }
            return true;
        };
        GlobalHelper.prototype.ForceRescreenCheck = function () {
            if (App.Global.Participant != null && App.Global.Participant.ForceRescreen == true)
                return true;
            return false;
        };
        GlobalHelper.prototype.CompleteRegistrationCheck = function () {
            if (App.Global.Participant != null && App.Global.Participant.CompleteRegistration == true)
                return true;
            return false;
        };
        GlobalHelper.prototype.IsAuthenticated = function () {
            return App.Global.Authenticated;
        };
        GlobalHelper.prototype.redirect = function (redirectPath) {
            var _this = this;
            var timer = this.$timeout(function () {
                _this.$timeout.cancel(timer);
                _this.$location.path(redirectPath);
            }, 0);
        };
        GlobalHelper.prototype.LaodSystemData = function () {
            if (App.Global.System == undefined)
                App.Global.System = {};
            //var clientService = new ClientService(this.$http);
            //clientService.GetClientInfo(ClientCallLetters).then((data) => (App.Global.Client = data));
            //var systemService = new SystemService($http);
            //systemService.GetEthnicities().then((data) => (App.Global.System.Ethnicities = data));
            //systemService.GetCountries().then((data) => (App.Global.System.Countries = data));
            //systemService.GetCountries().then((data) => (App.Global.System.States = data));
        };
        GlobalHelper.prototype.LoadClientData = function () {
            var _this = this;
            if (ClientCallLetters == null || ClientCallLetters == undefined || ClientCallLetters == '') {
                App.Helper.GoToUnknown();
                return null;
            }
            var clientService = new App.ClientService(this.$http);
            this.LoadingClientPromise = clientService.GetClientInfo(ClientCallLetters).then(function (data) {
                if (data == null) {
                    //Client does not exist
                    App.Helper.GoToUnknown();
                }
                else {
                    App.Global.Client = data;
                    if (data.Maint == true) {
                        console.log("maint mode!");
                        App.Helper.GoToMaint();
                    }
                    //load cliend settings
                    clientService.GetSignupSettings(App.Global.Client.ID).then(function (s) {
                        App.Global.Client.SignupSettings = s;
                    });
                }
                _this.LoadingClientPromise = null;
            }, function (err) {
                console.log("main error A");
                //Client does not exit
                App.Helper.GoToUnknown();
                _this.LoadingClientPromise = null;
            });
            return this.LoadingClientPromise;
        };
        GlobalHelper.prototype.LoadParticipantDataAndRedirect = function (data, $location) {
            var participant = App.Helper.LoadParticipantData(data);
            if ((participant.CompleteRegistration == true && participant.ForceRescreen == false)
                || App.Global.Client.DisplayRadioHabits == false
                || App.Global.Client.LimitedParticipantProfile == true) {
                //                if (participant.HasAward == true)
                //                {
                //                    this.redirect('/homeAward');
                //                }
                //                else
                //                {
                this.redirect('/home');
                //                }
            }
            else {
                if (participant.CompleteRegistration == false)
                    this.redirect('/radiohabits');
                else
                    this.redirect('/signup');
            }
        };
        GlobalHelper.prototype.LoadParticipantData = function (data) {
            if (data.Name == null || data.Name == '')
                data.Name = data.FirstName + ' ' + data.LastName;
            //App.Global.Participant = data;
            App.Global.Participant.Name = data.Name;
            App.Global.Participant.EMail = data.EMail;
            App.Global.Participant.CompleteRegistration = data.CompleteRegistration;
            App.Global.Participant.ForceRescreen = data.ForceRescreen;
            App.Global.Participant.HasAward = data.HasAward;
            return App.Global.Participant;
        };
        GlobalHelper.prototype.GetParticipantDataFromAuth = function (authResponse) {
            return {
                "ID": authResponse.data.participantID,
                "Name": authResponse.data.participantName,
                "EMail": authResponse.data.userName,
                "CompleteRegistration": App.Helper.StringToBoolean(authResponse.data.completeRegistration),
                "ForceRescreen": App.Helper.StringToBoolean(authResponse.data.forceRescreen),
                "HasAward": authResponse.data.HasAward
            };
        };
        GlobalHelper.prototype.StringToBoolean = function (string) {
            switch (string.toLowerCase().trim()) {
                case "true":
                case "yes":
                case "1": return true;
                case "false":
                case "no":
                case "0":
                case null: return false;
                default: return Boolean(string);
            }
        };
        /**
         * debouncing, executes the function if there was no new event in $wait milliseconds
         * @param func
         * @param wait
         * @param scope
         * @returns {Function}
         */
        GlobalHelper.prototype.Debounce = function (func, wait, scope) {
            var timeout;
            return function () {
                var context = scope || this, args = arguments;
                var later = function () {
                    timeout = null;
                    func.apply(context, args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        };
        /**
         * in case of a "storm of events", this executes once every $threshold
         * @param fn
         * @param threshhold
         * @param scope
         * @returns {Function}
         */
        GlobalHelper.prototype.Throttle = function (fn, threshhold, scope) {
            threshhold || (threshhold = 250);
            var last, deferTimer;
            return function () {
                var context = scope || this;
                var now = +new Date, args = arguments;
                if (last && now < last + threshhold) {
                    // hold on to it
                    clearTimeout(deferTimer);
                    deferTimer = setTimeout(function () {
                        last = now;
                        fn.apply(context, args);
                    }, threshhold);
                }
                else {
                    last = now;
                    fn.apply(context, args);
                }
            };
        };
        return GlobalHelper;
    }());
    App.GlobalHelper = GlobalHelper;
})(App || (App = {}));
//# sourceMappingURL=main.js.map;
