/* Minification failed. Returning unminified contents.
(4198,37-38): run-time error JS1195: Expected expression: )
(4198,40-41): run-time error JS1195: Expected expression: >
(4199,75-76): run-time error JS1004: Expected ';': )
(4201,21-25): run-time error JS1034: Unmatched 'else'; no 'if' defined: else
(4203,21-22): run-time error JS1002: Syntax error: }
(4205,32-33): run-time error JS1195: Expected expression: )
(4205,34-35): run-time error JS1004: Expected ';': {
(4207,18-19): run-time error JS1195: Expected expression: )
(4210,40-41): run-time error JS1004: Expected ';': {
(4324,5-6): run-time error JS1002: Syntax error: }
(4328,33-34): run-time error JS1004: Expected ';': :
(4332,31-32): run-time error JS1004: Expected ';': {
(4735,2-3): run-time error JS1195: Expected expression: )
(4736,31-32): run-time error JS1004: Expected ';': {
(5013,2-3): run-time error JS1195: Expected expression: )
(5014,1-2): run-time error JS1197: Too many errors. The file might not be a JavaScript file: (
 */
/* Minification failed. Returning unminified contents.
(4180,37-38): run-time error JS1195: Expected expression: )
(4180,40-41): run-time error JS1195: Expected expression: >
(4181,75-76): run-time error JS1004: Expected ';': )
(4183,21-25): run-time error JS1034: Unmatched 'else'; no 'if' defined: else
(4185,21-22): run-time error JS1002: Syntax error: }
(4187,32-33): run-time error JS1195: Expected expression: )
(4187,34-35): run-time error JS1004: Expected ';': {
(4189,18-19): run-time error JS1195: Expected expression: )
(4192,40-41): run-time error JS1004: Expected ';': {
(4306,5-6): run-time error JS1002: Syntax error: }
(4310,33-34): run-time error JS1004: Expected ';': :
(4314,31-32): run-time error JS1004: Expected ';': {
(4717,2-3): run-time error JS1195: Expected expression: )
(4718,31-32): run-time error JS1004: Expected ';': {
(4995,2-3): run-time error JS1195: Expected expression: )
(4996,1-2): run-time error JS1197: Too many errors. The file might not be a JavaScript file: (
 */
(function (window, undefined) {
    'use strict';

    OnlineApp.Namespace.extend('OnlineApp.Events.CommonEventsNames', {
        EditableItemBeginEdit: 'editableItemBeginEdit',
        EditItemComplete: 'editItemComplete',
        EditableCollectionItemDiscarded: 'editableCollectionItemDiscarded',
        TryRemoveItem: 'tryRemoveItem',
        RemoveItemComplete: 'removeItemComplete',
        ItemRemoved: 'itemRemoved',
        ResumeImportComplete: 'resumeImportComplete',
        PreSaveValidationFailed: 'preSaveValidationFailed',
        ApplicationSubmit: 'applicationSubmit',
        Login: 'loginEvent',
        Register: 'registerEvent',
        QuestionsSaved: 'questionsSaved',
        DocumentAttached: 'documentAttached',
        PasswordReset: 'passwordReset',
        ResetPasswordClicked: 'resetPasswordClicked',
        ContactInfomationAvailable: 'contactInformationAvailable',
        RegisterAccountLinkClicked: 'registerAccountLinkClicked',
        RegisterAccountFormOpened: 'registerAccountFormOpened',
        LoginFormOpened: 'loginFormOpened',
        ApplicationRendered: 'applicationRendered',
        TabActivated: 'tabActivated',
        ApplicationClosed: 'applicationClosed',
        ApplyTabOpened: 'applyTabOpened',
        ResourcesLinkClicked: 'resourcesLinkClicked',
        CertifySubmitTabOpened: 'certifySubmitTabOpened',
        EmailVerified: "emailVerified",
        EmailWasChanged: "emailWasChanged",
        ContactInfoEmailVerificationFormClosed: "contactInfoEmailVerificationFormClosed",
        ShowCancelVerificationRequestDialog: 'ShowCancelVerificationRequestDialog',
        InitSearchFieldsWithAutocomplete: "initSearchFieldsWithAutocomplete",
        AutocompleteMenuItemSelect: "menuselect",
        ConfirmEditEmailAddress: "confirmEditEmailAddress",
        CancelEditEmailAddress: "cancelEditEmailAddress",
        OjrMasterJicSubscribe: "ojrMasterJicSubscribe"
    });

})(window);;
(function(window, undefined) {
    'use strict';

    function NotificationController() {
        var self = this;

        self.showNotification = function(settings) {
            $(document).trigger(
                Events.CommonEventsNames.ShowConfirmDialog,
                settings
            );
        };

        self.showAppIncompleteNotification = function (confirmCallback) {
            self.showNotification({
                additionalCssClassName: "leave-incomplete-app-popup",
                header: "You are leaving the application process.",
                subHeader: "Do you want to proceed?",
                cancelButtonText: "Don't leave",
                confirmButtonText: "Leave Application",
                confirmClick: confirmCallback
            });
        };

        self.showDeleteItemNotification = function(confirmCallback, cancelCallback) {
            self.showNotification({
                header: "You are about to delete an item",
                subHeader: "Are you sure you would like to delete the item?\nRemember, this cannot be undone.",
                cancelButtonText: "No",
                confirmButtonText: "Yes",
                confirmClick: confirmCallback,
                cancelClick: cancelCallback
            });
        };

        self.showConfirmNavigationNotification = function (confirmCallback, cancelCallback, subheaderText, headerText) {
            subheaderText = subheaderText || "You have unsaved changes.";
            self.showNotification({
                header: headerText || "Confirm Navigation",
                subHeader: subheaderText + " Are you sure you want to leave this page?",
                cancelButtonText: "Stay on this Page",
                confirmButtonText: "Leave this Page",
                confirmClick: confirmCallback,
                cancelClick: cancelCallback
            });
        };

        self.showCreateNewAccountNotification = function(confirmCallback, cancelCallback) {
            self.showNotification({
                additionalCssClassName: "create-account-popup",
                header: "Create Account",
                subHeader: "Your username and password is confidential. Sharing your account with others is not permitted under any circumstances. If you are not the original owner of this account, you must stop using this account and create an account of your own. Violations may result in account suspension or removal.",
                confirmButtonText: "Create Account",
                cancelButtonText: "Cancel button",
                confirmClick: confirmCallback,
                cancelClick: cancelCallback
            });
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Controllers', {
        NotificationController: NotificationController,
        notificationController: new NotificationController()
    });
})(window);;
(function (window, undefined) {
    'use strict';

    /* base class for online app controllers */
    function MenuController() {
        var self = this;

        self.activateFirstTab = function () { };

        self.activateTabById = function (id) { };

        self.updateMenuState = function (selectedTabLink) { };

        return self;
    }


    var containerSelector = '.onlineapp-app-container',
        aria = gJobs.ariaAttributes;

    function SideBarMenuController() {
        var self = MenuController.apply(this, arguments) || this;

        var menuSelector = 'ul.left-menu-nav';

        var activate = function (tabSelector) {
            var $container = $(containerSelector);
            var $menu = $container.find(menuSelector);

            if (gJobs.browserDetector.isIE()) {
                gJobs.pageTabNavigationService.adjustNavigationForFixedHeader($menu);
            }

            // if menu is visible - set first tab as active tab
            if ($menu.is(':visible')) {
                var tabLink = $menu.find(tabSelector);
                tabLink.tab('show');

                // activate tab pane
                $(tabLink.attr('href')).addClass('active');
            }
        };

        self.activateFirstTab = function () {
            activate('a:first');
        };

        self.activateTabById = function (id) {
            activate('a[href="#' + id + '"]');
        };

        self.updateMenuState = function (selectedTabLink) {
            var $container = $(containerSelector);
            var $menu = $container.find(menuSelector);

            if (!$menu.is(':visible')) {
                $menu.find('li.active').removeClass('active');
                $menu.find('a[href="' + selectedTabLink + '"]').closest('li').addClass('active').click();
            }
        };

        return self;
    }

    function DropDownMenuController() {
        var self = MenuController.apply(this, arguments) || this;

        var menuSelector = '.dropdown-nav';
        var menuListSelector = '.dropdown-menu';

        var fixDropDown = function ($item) {
            var $dropdown = $item.parents().find('li.dropdown');

            $dropdown.find('.dropdown-toggle span').html($item.find('a').html());

            $dropdown.find('> .dropdown-menu > li').not($item).removeClass('active');
            $item.addClass('active');
        };

        var activate = function (tabSelector) {
            var $container = $(containerSelector);
            var $menu = $container.find(menuSelector);

            // if menu is visible - set tab as active
            var tabLink = $menu.find(menuListSelector).find(tabSelector);
            if ($menu.is(':visible')) {
                tabLink.tab('show');
            }
        };

        self.activateFirstTab = function () {
            activate('a:first');
        };

        self.activateTabById = function (id) {
            activate('a[href="#' + id + '"]');
        };

        self.updateMenuState = function (selectedTabLink) {
            var $container = $(containerSelector);
            var $menu = $container.find(menuSelector);

            var tabLink = $menu.find('a[href="' + selectedTabLink + '"]');
            fixDropDown(tabLink.closest('li').click());
        };

        return self;
    }

    function NavigationMenuController() {
        var self = this;

        var notificationController = OnlineApp.Controllers.notificationController;

        self.leftMenuController = new SideBarMenuController();
        self.topMenuController = new DropDownMenuController();

        self.tabIds = {
            generalInfo: '#general-info-tab',
            work: '#work-tab',
            education: '#education-tab',
            questions: '#questions-tab',
            additionalInfo: '#additional-info-tab',
            referencesInfo: '#references-tab',
            attachmentsInfo: '#attachments-tab',
            reviewInfo: '#review-tab',
            submitInfo: '#submit-tab',
            payment: '#payment-tab'
        };

        self.initialize = function () {

            var isTabShowingFirstTime = true;

            self.onTab('shown', function (e, data) {
                var $targetLink = $(e.target);
                var tabLink = $targetLink.attr('href');
                var tabHeader = $(tabLink).find('.page-header');
                var tabCode = $targetLink.data('code');
                var tabName = $targetLink.find('.tab-name').text();
                var activeTab = self.getActiveTab().tab;
                var hasNotification = tabLink === self.tabIds.reviewInfo;
                var notificationContainer = activeTab.find('.description.notification');
                var hasInstruction = !!notificationContainer.length;
                if (!hasInstruction || hasNotification) {
                    notificationContainer = $('#screen-reader-message');
                }

                self.leftMenuController.updateMenuState(tabLink);

                self.topMenuController.updateMenuState(tabLink);

                var notificationText = tabHeader.length
                    ? 'You are now on ' + tabName + ' section. ' + tabHeader.filter(':visible').get(0).outerText + ' block'
                    : tabName + ' section';

                notificationText += ' is opened. ';

                var $additionalInfoElements = $targetLink.find('.additional-information');
                
                if ($additionalInfoElements.length) {
                    notificationText += $additionalInfoElements.text();
                }
                $targetLink.closest('ul').find('a').each(function () {
                    // Set aria-expanded and aria-selected to false for all links except targetLink
                    if ($(this)[0] !== $targetLink[0]) {
                        $(this).attr('aria-expanded', 'false').attr('aria-selected', 'false');
                    }
                });
                $targetLink.closest('ul').find('a').removeAttr(aria.describedBy);

                if (hasInstruction && !hasNotification) {
                    $targetLink.setAttributes([
                        [ aria.describedBy, notificationContainer.attr('id') ]
                    ]);
                }

                notificationText = notificationText.replace(/\s{2,}/g, ' ');

                gJobs.screenReadersService.silenceScreenreader();

                gJobs.screenReadersService.setNotificationOnElement({
                    text: notificationText,
                    $element: $targetLink
                });

                if (isTabShowingFirstTime) {
                    gJobs.screenReadersService.setAriaLiveNotification(notificationText);
                   
                    isTabShowingFirstTime = false;
                }

                $(document).trigger('layoutUpdated');

                var event = jQuery.Event(OnlineApp.Events.CommonEventsNames.TabActivated);
                event.tabCode = tabCode;
                $(document).trigger(event);

                $('.application-container').scrollTop(0);
                $('#jobDetailsButton').attr('tabindex', '-1');
            });
        };

        self.attachHandlersToNextBtns = function (canNavigateAway) {

            $(containerSelector).find('.tab-content .btn-next')
                // clear previous events if they exist
                .off('click')
                // navigate next btns functionality (submit tab has its own implementation)
                .on('click', function (e) {
                    var menuLis = $(containerSelector).find('ul.nav-tabs li');
                    var active = menuLis.filter('.active');
                    var currentIndex = menuLis.index(active);
                    var nextMenuItem = menuLis.get(currentIndex + 1);
                    var newTabName = $(nextMenuItem).find('a').attr('href');
                    var tabName = active.find('.tab-name').text();

                    var showNextTab = function () {
                        var event = jQuery.Event('showNextTab');

                        event.callback = function () {
                            $(nextMenuItem).find('a').tab('show');
                        };
                        event.viewModel = ko.contextFor($(menuLis.get(currentIndex)).find('a').get(0)).$data;
                        $(nextMenuItem).find('a').trigger(event);
                    }

                    if (nextMenuItem) {
                        var previousViewModel = self.getActiveViewModel();
                        var isViewModelEditable = $.isFunction(previousViewModel.isInEditMode);

                        var isCanNavigateAwayFunc = canNavigateAway && $.isFunction(canNavigateAway);
                        if (isCanNavigateAwayFunc && isViewModelEditable) {
                            var canNavigate = canNavigateAway(previousViewModel);

                            if (!canNavigate) {
                                var confirmCallback = function() {
                                    if ($.isFunction(previousViewModel.discardChanges)) {
                                        e.dontScrollAfterEditing = true;
                                        previousViewModel.discardChanges(null, e);
                                    }

                                    previousViewModel.isVisited(true);

                                    showNextTab(newTabName);
                                };
                                
                                var cancelCallback = function () {
                                    gJobs.screenReadersService.setAriaLiveNotification(
                                        'The modal has been closed.'
                                    );
                                    OnlineApp.Helpers.layoutHelper.tabbing.activateFirstElement();
                                }


                                notificationController.showConfirmNavigationNotification(
                                    confirmCallback,
                                    cancelCallback
                                );

                                return false;
                            }
                        }

                        previousViewModel.isVisited(true);
                        if (previousViewModel.showCheckValidationIcon &&
                            previousViewModel.showCheckValidationIcon()) {

                            gJobs.screenReadersService.setAriaLiveNotification(
                                tabName + ' section has been successfully completed.'
                            );
                        }

                        // timeout is neccessary as otherwise setAriaLiveNotification from self.onTab() would override this one
                        showNextTab(nextMenuItem);
                    }
                });
        };

        self.attachHandlersToNavigationMenu = function (
                canNavigateAway,
                canNavigateAwayCallback,
                canNavigateToTab,
                canNotNavigateToTabCallback) {

            self.onTab('click', function (e) {
                if (e.target) {
                    var activeTabData = self.getActiveTab();
                    var $activeMenuItem = $('[href="#' + activeTabData.tabId + '"]', containerSelector);
                    var tabName = $($activeMenuItem[0]).find('.tab-name').text();

                    var previousViewModel = ko.contextFor($activeMenuItem[0]).$data;

                    var isViewModelEditable = $.isFunction(previousViewModel.isInEditMode);
                    
                    var $target = $(e.target);
                    var newTabName = $target.attr('href');

                    if (!newTabName) {
                        newTabName = $target.closest('[data-toggle="tab"]').attr('href');
                    }

                    if (newTabName === '#' + activeTabData.tabId) {
                        e.stopPropagation();
                        e.preventDefault();
                        return false;
                    }

                    if (isViewModelEditable) {

                        var canNavigate = canNavigateAway(previousViewModel);

                        if ($.isFunction(canNavigateToTab) && !canNavigateToTab(newTabName)) {
                            if ($.isFunction(canNotNavigateToTabCallback)) {
                                canNotNavigateToTabCallback(newTabName);
                            }
                            e.stopPropagation();
                            e.preventDefault();

                            if (!canNavigate) {
                                OnlineApp.Helpers.layoutHelper.tabbing.activateFirstElement();
                            }

                            return false;
                        }

                        if (!canNavigate) {

                            var confirmCallback = function() {
                                if ($.isFunction(previousViewModel.discardChanges)) {
                                    e.dontScrollAfterEditing = true;
                                    previousViewModel.discardChanges(null, e);
                                }

                                previousViewModel.isVisited(true);

                                newTabName = newTabName.substr(1, newTabName.length - 1);
                                self.activateTabById(newTabName);
                            }

                            var cancelCallback = function() {
                                OnlineApp.Helpers.layoutHelper.tabbing.activateFirstElement();
                            }

                            var isQuestionsOrAttachmentsTab =
                                '#' + activeTabData.tabId === self.tabIds.questions ||
                                '#' + activeTabData.tabId === self.tabIds.attachmentsInfo;

                            if (!isQuestionsOrAttachmentsTab && !previousViewModel.isDataChanged()) {
                                confirmCallback();
                            } else {
                                var subHeaderText, headerText;

                                if (isQuestionsOrAttachmentsTab) {
                                    subHeaderText = 'You have mandatory information missing. ';
                                    headerText = 'Mandatory information missing';
                                }

                                notificationController.showConfirmNavigationNotification(
                                    confirmCallback,
                                    cancelCallback,
                                    subHeaderText,
                                    headerText
                                );

                                return false;
                            }
                        }
 
                        if ($.isFunction(canNavigateAwayCallback)) {
                            canNavigateAwayCallback(previousViewModel);
                        }

                        previousViewModel.validate();
                    }

                    if (previousViewModel.updateStatus) {
                        previousViewModel.updateStatus();
                    }

                    previousViewModel.isVisited(true);

                    if (previousViewModel.showCheckValidationIcon &&
                        previousViewModel.showCheckValidationIcon()) {
                        gJobs.screenReadersService.setAriaLiveNotification(tabName + ' section has been successfully completed.');
                    }
                }
            });
        };

        self.activateFirstTab = function () {
            self.leftMenuController.activateFirstTab();
            self.topMenuController.activateFirstTab();
        };

        self.activateTabById = function (id) {
            self.leftMenuController.activateTabById(id);
            self.topMenuController.activateTabById(id);
        };

        self.getNavigationInfo = function() {
            var allTabs = $(containerSelector)
                .find('a[data-toggle="tab"]:visible');

            var activeTab = $(containerSelector).find('.tab-pane.active');
            var tabId = activeTab.length > 0 ? activeTab.attr('id') : undefined;

            var tabIndex = 0,
                tabName = '',
                tabElement = undefined;

            if (tabId) {
                for (var i = 0; i < allTabs.length; i++) {
                    var tab = $(allTabs[i]);
                    if (tab.attr('href') === '#' + tabId) {
                        tabElement = tab;
                        tabName = tab.find('.tab-name').text();
                        tabIndex = i + 1;
                        break;
                    }
                }
            }

            return {
                activeTabElement: tabElement,
                activeTabName: tabName,
                activeTabIndex: tabIndex,
                totalTabCount: allTabs.length
            };
        };

        self.disableMenuTabs = function () {
            $(containerSelector)
                .find('a[data-toggle="tab"]')
                .on('click.disableMenuTabs', function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                });
        };

        self.enableMenuTabs = function () {
            $(containerSelector)
                .find('a[data-toggle="tab"]')
                .off('click.disableMenuTabs');
        };

        self.getActiveTab = function () {
            var activeTab = $(containerSelector).find('.tab-pane.active');

            var tabId = activeTab.length > 0 ? activeTab.attr('id') : undefined,
                tabName = tabId != null ? tabId.split('-')[0] : undefined;
            $('#jobDetailsButton').attr('tabindex', '-1');
            return {
                tab: activeTab,
                tabId: tabId,
                tabName: tabName
            };
        };

        self.getActiveViewModel = function () {
            var activeTabData = self.getActiveTab();
            var $activeMenuItem = $('[href="#' + activeTabData.tabId + '"]', containerSelector);

            return ko.contextFor($activeMenuItem[0]).$data;
        };

        self.getTabIdByName = function (id) {
            var tab = $(containerSelector).find('.tab-pane[id^="' + id + '"]');
            return tab.attr('id');
        };

        self.onTab = function (eventName, callback) {
            $(containerSelector + ' a[data-toggle="tab"]').on(eventName, callback);
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Controllers', {
        NavigationMenuController: NavigationMenuController,
        navigationMenuController: new NavigationMenuController()
    });

})(window);;
(function(window, undefined) {
    'use strict';

    function findEditedItemContainer(eventTargetElement) {
        var $editedItemContainer = $(eventTargetElement);

        var prev = $editedItemContainer.prev();
        if (prev.length > 0) {
            $editedItemContainer = prev;
        }

        if ($editedItemContainer.prev().is('h3'))
            return $editedItemContainer.prev();

        return $editedItemContainer;
    }

    function NavigationController() {
        var self = this;
        var navigationMenuController = OnlineApp.Controllers.navigationMenuController;
        var pageScrollService = gJobs.pageScrollService;

        self.initialized = false;

        self.initialize = function() {
            // TODO: check what happens when session dies and user re-logs in
            if (self.initialized) return;

            navigationMenuController.initialize();

            navigationMenuController.onTab('shown', function (e) {
                //search for current active tab
                updateActiveTabId();

                self.scrollTabTopToView(e);
            });

            self.initialized = true;
        };

        self.deinitialize = function() {
            self.initialized = false;
        };


        var navigationState = {
            initialUrl: undefined,
            onlineAppUrl: undefined,
            forceLoad: false,
            enableMenuTabs: false,
            activateFirstTab: false,
            activateTabById: false,
            attachNextButtonHandlers: false,
            scrollToEditDialog: false,
            tabId: undefined,
            tabName: undefined
        };

        var jobDetailsFlyoutUrlSuffix = '/jobdetails';

        self.activateFirstTab = function() {
            navigationState.activateFirstTab = true;
            navigationState.activateTabById = false;
        };

        self.activateTabById = function(id) {
            navigationState.activateFirstTab = false;
            navigationState.activateTabById = true;
            navigationState.tabId = id;
        };

        self.disableMenuTabs = function() {
            navigationState.enableMenuTabs = false;
        };

        self.enableMenuTabs = function() {
            navigationState.enableMenuTabs = true;
        };

        self.attachHandlersToNextBtns = function() {
            navigationState.attachNextButtonHandlers = true;
        };

        self.editDialogScrolling = function() {
            navigationState.scrollToEditDialog = true;
        };

        function updateActiveTabId() {
            var $dropdown = $('.onlineapp-app-container .dropdown-nav')
                .filter(function() {
                    return $(this).css('display') != 'none';
                });
            var activeTabMenuItem;

            if ($dropdown !== undefined && $dropdown.length != 0) {
                activeTabMenuItem = $dropdown.find('.dropdown-menu li.active a');
            } else {
                activeTabMenuItem = $('.onlineapp-app-container .left-menu-nav li.active a');
            }
            if (activeTabMenuItem) {
                var tabName = activeTabMenuItem.attr('href');
                if (tabName) {
                    navigationState.tabId = tabName.substring(1, tabName.length);
                }
                activeTabMenuItem.focus();
            }
        }

        function findFirstValidationError(element) {
            /*              5 types of validatable controls:                */
            return element
                .find(
                    'input.validation-error,'                /*   input         */
                    + ' textarea.validation-error,'          /*   text-area     */
                    + ' div.select-validation-error,'        /*   select        */
                    + ' .validation-error .checkbox-set,'    /*   checkbox      */
                    + ' .validation-error.checkbox-set,'     /*   checkbox      */
                    + ' .validation-error .radio-set,'       /*   radio-group   */
                    + '.validation-error.radio-set')         /*   radio-group   */
                .filter(':not(.inline-message)')
                .first();
        }

        self.navigate = function() {
            self.initialize();

            if (navigationState.scrollToEditDialog) {
                var currentTab = $('#' + navigationState.tabId);
                if (currentTab) {
                    // find first item with error
                    var errorItem = findFirstValidationError(currentTab);

                    if (errorItem.length !== 0) {
                        self.scrollToTopValidationError(errorItem);
                    } else {
                        var firstEditDialog = currentTab
                            .find('.edit-dialog:not([style*="display: none"])').first();
                        self.scrollElementToView(firstEditDialog);
                    }
                }

                navigationState.scrollToEditDialog = false;
                return;
            }

            if (navigationState.enableMenuTabs) {
                navigationMenuController.enableMenuTabs();
            } else {
                navigationMenuController.disableMenuTabs();
            }

            if (navigationState.activateFirstTab) {
                navigationMenuController.activateFirstTab();
            }

            if (navigationState.activateTabById) {
                var tabId = navigationState.tabId;

                if (tabId) {
                    navigationMenuController.activateTabById(tabId);
                } else {
                    navigationMenuController.activateFirstTab();
                }
            }

            if (navigationState.attachNextButtonHandlers) {
                navigationMenuController.attachHandlersToNextBtns(function (previousViewModel) {
                    return previousViewModel.validateChanges();
                });
            }
        };

        self.scrollToAndFocusFirstTabWithValidationError = function () {
            /* TODO: think about less markup dependent solution both for first invalid tab and for first focusable element with error */
            var activeTab = $('.onlineapp-tabs .tab-pane.active:visible');

            var validationError = activeTab.find('.validation-error');
            var validationSectionError = activeTab.find('.section-validation-message');

            var tabWithValidationError = undefined;
            if (validationError.length !== 0) {
                tabWithValidationError = $(validationError[0]).closest('.onlineapp-section');
            }
            if (validationSectionError.length !== 0) {
                tabWithValidationError = $(validationSectionError[0]).closest('.onlineapp-section');
            }

            if (tabWithValidationError && tabWithValidationError.length !== 0) {

                var $elementToFocus;
                if ($(tabWithValidationError).find('.edit-dialog:visible').length !== 0) {
                    $elementToFocus = $(tabWithValidationError).find('.validation-error:first');
                } else {
                    var $sectionEditButton = $(tabWithValidationError).find('.validation-error .item-edit-button:visible').filter(function() {
                        return !($(this).css('visibility') === 'hidden');
                    });
                    var $sectionUploadButton = $(tabWithValidationError).find('.attachment-upload-button').filter(function() {
                        return !($(this).css('visibility') === 'hidden');
                    });
                    var $sectionAddButton = $(tabWithValidationError).find('.btn-app-add:visible').filter(function() {
                        return !($(this).css('visibility') === 'hidden');
                    });

                    if ($sectionEditButton.length !== 0) {
                        $elementToFocus = $sectionEditButton;
                    } else if ($sectionUploadButton.length !== 0) {
                        $elementToFocus = $sectionUploadButton;
                    } else {
                        $elementToFocus = $sectionAddButton;
                    }
                }

                if ($elementToFocus && $elementToFocus.length !== 0) {
                    $elementToFocus[0].focus();

                    var $elementToFocusBox = $($elementToFocus).closest('.box-container');
                    if ($elementToFocusBox.length !== 0) {
                        $elementToFocusBox[0].scrollIntoView();
                        return;
                    }
                }

                tabWithValidationError[0].scrollIntoView();
            }
        }

        self.scrollToTopValidationError = function(element) {
            /* TODO: think about less markup dependent solution */
            if (!element || $(element).is(document)) {
                element = $('.validation-error').filter(':visible').first();
            }

            if (element.length === 0) {
                return;
            }

            var error = findFirstValidationError($(element)
                .closest('.edit-dialog'));

            /* select a valid container based on markup templates */
            if (!error.hasClass('select-validation-error')) {
                error = error.parent();
            }

            if (!$(error).is(':visible')) {
                error = error.closest('legend');
            }

            // for questions tab try to find closest question-item container
            var errorElementContainer = error.parents('.question-item');
            if (errorElementContainer.length !== 0) {
                error = errorElementContainer.first();
            }

            self.scrollElementToView(error);
        };

        // TODO: review the code below (remained unchanged from initial state while refactoring)

        self.scrollClosestBoxToView = function(element, findAbove) {
            var box = $(element).closest('.box-container');
            if (findAbove) {
                box = $('.box-container').filter(':visible').last();
            }
            self.scrollElementToView(box);
        };

        self.scrollTabTopToView = function (e) {
            if (e) {
                var viewModel = ko.contextFor(e.target).$data;
                if (viewModel.hasError && viewModel.hasError()) {
                    var activeTab = navigationMenuController.getActiveTab(),
                        firstError = activeTab != null ? findFirstValidationError(activeTab.tab) : null;

                    //do not scroll to the top validation error on Questions tab (IS-16910)
                    if (firstError != null && firstError.length > 0 && activeTab.tabId != 'questions-tab') {
                        self.scrollToTopValidationError(firstError);

                        return;
                    }
                }
            }

            self.scrollElementToView($('.onlineapp-tabs'));
        };

        self.scrollElementContainerToView = function(element) {
            self.scrollElementToView(findEditedItemContainer(element));
        };

        self.scrollElementToView = function ($targetToScroll) {
            var $flyoutScrollContainer = pageScrollService.getFlyoutScrollContainer();

            var metrics = {
                offset: $targetToScroll.offset(),
                position: $targetToScroll.position(),
                padding: parseInt($targetToScroll.css('padding-top') || 0),
                containerScroll: $flyoutScrollContainer.scrollTop()
            };

            return self.scrollToView(metrics);
        };

        self.scrollToView = function(metrics) {

            if (!metrics) {
                return;
            }

            if (metrics.padding < 40) {
                metrics.padding = 40 - metrics.padding;
            }

            pageScrollService.scrollToView(metrics);
        };


        self.setRoutingBehavior = function() {

            //todo: move gJobs.router into more common namespace
            if (!gJobs || !gJobs.router || !History) {
                return;
            }

            var initialState = History.getState();
            navigationState.initialUrl = initialState.url;

            //do not append /apply to the Job Search page
            var tempElement = document.createElement('a');
            tempElement.href = initialState.url;
            var initialPathname = tempElement.pathname.toLowerCase();
            if (initialPathname == '/jobs' || initialPathname == '/applications/incomplete') {
                return;
            }
            initialState.cleanUrl = gJobs.router.cutQueryString(initialState.url);
            navigationState.onlineAppUrl = !!initialState.cleanUrl.match(/\/apply\/?/) ?
                initialState.cleanUrl :
                initialState.cleanUrl +
                    (initialState.cleanUrl.match(/\/$/) ? '' : '/' /* check for slash at the end */)
                    + 'apply';

            if (utils.stringEndsWith(navigationState.onlineAppUrl, '/')) {
                navigationState.onlineAppUrl = utils.removeFromStringEnd(navigationState.onlineAppUrl, 1);
            }

            gJobs.router.navigate(navigationState.onlineAppUrl, null, null, null, {}, true);

            History.Adapter.bind(window, 'statechange', function() {
                var historyState = History.getState();

                if (historyState.data && historyState.data.innerData) {
                    var historyTab = historyState.data.innerData,
                        activeTab = navigationMenuController.getActiveTab();

                    if (activeTab && activeTab.tabName !== historyTab.tabName) {
                        navigationMenuController.activateTabById(historyTab.tabId);
                    }
                }
            });
        };

        self.goToInitialUrl = function () {
            if (navigationState.onlineAppUrl) {
                window.location = navigationState.onlineAppUrl;
                return true;
            }
            if (navigationState.initialUrl) {
                window.location = navigationState.initialUrl;
                return true;
            }
            return false;
        };

        self.updateUrl = function() {
            //todo: move gJobs.router into more common namespace
            if (!gJobs || !gJobs.router || !History) {
                return;
            }

            var historyState = History.getState();
            var innerData = historyState.data.innerData;
            
            var activeTab = navigationMenuController.getActiveTab();
            
            if (!innerData ||
                !innerData.tab ||
                (activeTab != null && innerData.tab.tabName !== activeTab.tabName)) {

                var url = navigationState.onlineAppUrl.replace(/\/apply.*/, '/apply/' + activeTab.tabName);

                gJobs.router.navigate(url,
                    null, null, null,
                    {
                        tabId: activeTab.tabId,
                        tabName: activeTab.tabName
                    }, true);
            }
        };

        self.navigateToFirstInvalidTab = function() {
            var firstAlertMenuItem = $('.tabs-left .ss-alert').filter('[data-invalid="true"]:first');
            if (firstAlertMenuItem.get(0)) { //invalid tab has been visited and is highlighted in the menu
                firstAlertMenuItem.closest('a').tab('show');
                return true;
            } else { //invalid tab is not being highlighted in the menu
                $('.tabs-left .nav-tabs li a').each(function (index, element) {
                    var viewModel = ko.dataFor(element);
                    if (viewModel.hasError && viewModel.hasError()) {
                        $(element).tab('show');
                        return false; //break from 'each' loop
                    }
                });
            }

            return false;
        };

        self.navigateToApplicationsPage = function() {
            var applicationsHref =
                $('#header .application-menu .application-menu-items .job-applications-link')
                    .attr('href');

            if (applicationsHref &&
                applicationsHref !== window.location.pathname) /* no need to navigate */ {
                window.location = applicationsHref;
            }
        };

        self.navigateToJobDetailsFlyout = function () {
            AgencyPages &&
                AgencyPages.router &&
                AgencyPages.router.navigate(navigationState.onlineAppUrl + jobDetailsFlyoutUrlSuffix, null, null, null, null, true);
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Controllers', {
        NavigationController: NavigationController,
        navigationController: new NavigationController()
    });

})(window);;
(function (window, undefined) {
    'use strict';

    function TabsNavigationController() {
        var self = this;
        var $window = $(window);
        var navigationMenuController = OnlineApp.Controllers.navigationMenuController;

        self.enableHashChangeTracking = function () {
            $window.off('hashchange', self.syncCurrentTab);
            $window.on('hashchange', self.syncCurrentTab);
        };

        self.syncHash = function () {
            var tab = navigationMenuController.getActiveTab();
            location.hash = tab.tabName;
        };

        self.syncCurrentTab = function () {
            var hash = location.hash.substring(1);

            if (!hash) {
                navigationMenuController.activateFirstTab();
                return;
            }

            var tabId = navigationMenuController.getTabIdByName(hash);
            navigationMenuController.activateTabById(tabId);
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.Controllers', {
        TabsNavigationController: TabsNavigationController,
        tabsNavigationController: new TabsNavigationController()
    });

})(window);
;
(function (window, undefined) {
    'use strict';

    function TalentSearchPreferencesViewModel() {
        var config = {
            endpoint: "talentSearchPreferences"
        };

        var self = OnlineApp.ViewModels.Base.EditableViewModel.call(this, config) || this;

        self.isAccessMembershipEnabled = ko.observable(false);

        self.isAccessMembershipEnabled.subscribe(function(value) {
            var accessMembershipNotification = "Access membership is " +
                (value ? "active" : "inactive");

            gJobs.screenReadersService.setAriaLiveNotification(accessMembershipNotification);
        });

        self.toggleButtonText = function (toggleValue) {
            return toggleValue ? 'ON' : 'OFF';
        };

        self.fromDataModel = function (data) {
            if (!data) {
                return;
            }

            self.isAccessMembershipEnabled(data.isAccessMembershipEnabled);
        };

        self.trackClickOnAccessMembershipLogo = function() {
            gJobs.common.analytics.trackEvent(
                'Access Membership Account Preferences Section',
                'Followed'
            );

            return true;
        };

        self.isInEditMode.subscribe(function(value) {
            var $accessMembershipPreferencesTab = $('.access-membership-preferences-tab');
            var nonEditModeClassName = 'non-edit-mode';

            if (value) {
                $accessMembershipPreferencesTab.removeClass(nonEditModeClassName);
            } else {
                $accessMembershipPreferencesTab.addClass(nonEditModeClassName);
            }
        });

        self.saveChanges = (function(base) {
            var pageInfoService = gJobs.pageInfoService ? gJobs.pageInfoService : AgencyPages.pageInfoService;

            return function(item, e) {
                return base(item, e).always(function() {
                    if (pageInfoService.isOnPreferencesSectionPage()) {
                        if (!self.isAccessMembershipEnabled()) {
                            var configSettingForStickyHeader = $('#sticky-header').data('config-setting-for-sticky-header');

                            if (configSettingForStickyHeader) {
                                $('#content').addClass('respect-sticky-header');
                                window.enableStickyHeader = true;
                            }
                            $(document).trigger(Events.CommonEventsNames.AccessMembershipDisabled);

                        } else if (window.enableStickyHeader && self.isAccessMembershipEnabled()) {
                            $(document).trigger(Events.CommonEventsNames.AccessMembershipEnabled);
                        }
                    }
                });
            };
        })(self.saveChanges);
    }


    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        TalentSearchPreferencesViewModel: TalentSearchPreferencesViewModel
    });

})(window);


;
(function (window, undefined) {
    'use strict';

    var captchaHelper = new OnlineApp.Helpers.CaptchaHelper('#contact-info-tab');
    var layoutHelper = OnlineApp.Helpers.layoutHelper;

    function ContactInfoViewModel(config) {
        var config = $.extend({}, {
            endpoint: "contactInfo",
            get: false // data is loaded in parent View-Model
        }, config);

        var contactInfoSaveButtonSelector = '#contact-info-tab .form-actions .btn-app-primary-save';

        var pageInfoService = gJobs.pageInfoService ? gJobs.pageInfoService : AgencyPages.pageInfoService;
        var currentPage = pageInfoService.getCurrentPageType();
        var currentPageType;
        var pageTypes = pageInfoService.getPageTypes();

        if (currentPage) {
            currentPageType = currentPage.type;
        }

        var self = OnlineApp.ViewModels.Base.EditableViewModel.call(this, config) || this;

        self.isDiscardChange = ko.observable(false);

        self.radioButtonOptions = ko.observable({
            notificationPreference: [
                {
                    value: '1',
                    id: 'contact-info-notification-preference-email',
                    name: 'ci-radioSet-notify',
                    label: 'Email'
                },
                {
                    value: '2',
                    id: 'contact-info-notification-preference-paper',
                    name: 'ci-radioSet-notify',
                    label: 'Paper'
                }
            ]
        }).extend({ ignoreOnSerialization: true });

        self.enableEmailVerification = ko.observable(window.enableEmailVerification);
        self.fromAppProcess = ko.observable(window.utils.getUrlParameter("fromAppProcess").trim() === 'true'  ? true : false);
        self.isEmailVerified = ko.observable();
        self.isAccountSettingsPage  = ko.observable(currentPageType === pageTypes.accountSettings.type);

        var initialFullName;
        self.name = new OnlineApp.ViewModels.Common.NameViewModel();
        self.address = new OnlineApp.ViewModels.Common.AddressViewModel();
        self.phone = new OnlineApp.ViewModels.Common.PhoneViewModel();
        self.textCaptchaViewModel = new OnlineApp.ViewModels.TextCaptchaViewModel();


        self.initContactInfoEmailVerificationViewModel = function (options) {
            if (!self.contactInfoEmailVerificationViewModel) {
                self.contactInfoEmailVerificationViewModel = new OnlineApp.ViewModels.ContactInfoEmailVerificationViewModel();
            }

            if (options) {
                self.contactInfoEmailVerificationViewModel
                    .emailVerificationViewModel
                    .changedEmailAddressWasAdded = ko.observable(options.changedEmailAddressWasAdded);
            }

            self.contactInfoEmailVerificationViewModel.emailVerificationViewModel.initUserData();

            OnlineApp.Services.emailVerificationService.isEmailVerified().then(function(response) {
                var data = response.data;

                self.isEmailVerified(data.isEmailVerified);
            });
        };
        
        if (self.enableEmailVerification() && self.isAccountSettingsPage() && !self.fromAppProcess()) {
            OnlineApp.Services.authenticationService.isLoggedIn()
            .done(function (isLoggedIn) {
                if (isLoggedIn) {
                   self.initContactInfoEmailVerificationViewModel();
                }
            });
        }


        // todo: implement EmailAvailabilityValidator (promise-based)
        // todo: combine all email-related funtionality into one place
        self.initialEmail = ko.observable(null);
        self.emailAddress = ko.observable('').extend({ required: {}, email: {} });
        self.isEmailNotAvailable = ko.observable(false).extend({ ignoreOnSerialization: true });
        self.isEmailEditable = ko.observable(config.isEmailEditable || false).extend({ ignoreOnSerialization: true });
        self.isPasswordSet = true;
        self.textCaptchaEnabled = window.textCaptcha;

        self.isEmailVerificationNotificationEnabled = ko.observable(config.isEmailVerificationNotificationEnabled);
        self.isEmailVerificationMode = ko.observable(false);
        self.isEmailChanged = ko.observable(false).extend({ ignoreOnSerialization: true });
        self.showCaptchaValidationMessage = ko.observable(false);

        self.currentPassword = ko.observable().extend({ required: {} });
        self.isEmailAddressAvailable = ko.observable(true);
        self.isGoogleSignIn = ko.observable(false);

        self.emailAddress.subscribe(function (value) {
            //we assume that user changed email correctly
            self.isEmailNotAvailable(false);
            if (!value) {
                self.isEmailAddressAvailable(false);
            }
            else {
                self.isEmailAddressAvailable(true);
            }
            if (value !== self.initialEmail()) {
                self.isEmailChanged(true);
                
                if (!self.enableEmailVerification()) {
                    if (self.textCaptchaEnabled) {
                        self.textCaptchaViewModel.resetCaptcha(
                            self.textCaptchaViewModel.hasError(),
                            self.textCaptchaViewModel.userAnswer.validationMessage()
                        );
                    } else {
                        captchaHelper.renderCaptcha();
                    }
                }
            }
        });

        self.goToAccountSettingsPage = function () {
            var accountSettingsPagePath = gJobs.accountSettingsHelper.getLinkForAccountSettings();
            accountSettingsPagePath += '?changeEmail=true';

            var pageInfoService = gJobs.pageInfoService ? gJobs.pageInfoService : AgencyPages.pageInfoService;

            if (self.enableEmailVerification() && pageInfoService.isOnApplyPage()) {
                accountSettingsPagePath += '&redirectToVerifyAccountPage=true';
                sessionStorage.setItem(OnlineApp.SessionKeys.ApplicationProcessUrl, window.location.href);
            }

            window.location = accountSettingsPagePath;
        };

        self.changeEmailNotification = ko.computed({
            read: function () {
                return 'Your current email address is ' + self.initialEmail() +
                '. To change the email address, please visit account settings page.';
            },
            deferEvaluation: true
        })

        self.notificationPreference = ko.observable();
        self.jobId = ko.observable();

        self.notificationPreferenceText = ko.computed({
            read: function () {
                // todo: use same approach for every enum
                /* This approach for setting Enum values 
                uses client side enum-like dictionaries
                (see definitionsViewModel) */
                // $root.definitionsViewModel.notificationType.items()[1].id - might be input values

                var prefValue = self.notificationPreference();
                if (!prefValue) {
                    return "";
                }

                var notificationTypes = OnlineApp.ViewModels.applicationViewModel.definitionsViewModel.notificationType.items();
                var pref = notificationTypes[prefValue];

                if (!pref) {
                    return "";
                }

                return pref.text;
            },
            write: function (value) {
                var definition = ko.utils.arrayFirst(
                    OnlineApp.ViewModels.applicationViewModel.definitionsViewModel.notificationType.items(),
                    function(item) {
                        return item.text == value;
                    });

                self.notificationPreference(definition.id);
            }
        }).extend({ ignoreOnSerialization: true });

        self.getValidationConfig = function () {

            var fieldSettings = OnlineApp.FieldSettings;

            var getPrimaryPhone = function () {
                return {
                    subjectField: self.phone.primaryPhone,
                    objectField: self.phone.primaryPhoneExt,
                };
            };

            var getAlternatePhone = function () {
                return {
                    subjectField: self.phone.alternatePhone,
                    objectField: self.phone.alternatePhoneExt,
                };
            };

            var config = {
                'all': {
                    'name.firstName': {
                        required: {},
                        length: {
                            max: 50
                        },
                        regexp: {
                            pattern: /^[a-zA-Z\-\'~\u00C0-\u017F ]*$/,
                            validationMessage: "Invalid first name",
                            isValidationMessageVisible: true
                        }
                    },
                    'name.lastName': {
                        required: {},
                        length: {
                            max: 50
                        },
                        regexp: {
                            pattern: /^[a-zA-Z\-\'~\u00C0-\u017F ]*$/,
                            validationMessage: "Invalid last name",
                            isValidationMessageVisible: true
                        }
                    },
                    'name.middleName': {
                        required: {
                            enabled: !!fieldSettings ? fieldSettings.middleName.required : false
                        },
                        length: {
                            max: 50,
                            enabled: !!fieldSettings ? fieldSettings.middleName.visible : true
                        },
                        disallowHtml: {}
                    },
                    'name.formerName': {
                        required: {
                            enabled: !!fieldSettings ? fieldSettings.formerLastName.required : false
                        },
                        length: {
                            max: 50,
                            enabled: !!fieldSettings ? fieldSettings.formerLastName.visible : true
                        },
                        regexp: {
                            pattern: /^[a-zA-Z\-\'~\u00C0-\u017F ]*$/,
                            validationMessage: "Invalid former last name",
                            isValidationMessageVisible: true,
                            enabled: !!fieldSettings ? fieldSettings.formerLastName.visible : true
                        }
                    },
                    'address.address1': {
                        required: {},
                        length: {
                            max: 100
                        },
                        disallowHtml: {}
                    },
                    'address.address2': {
                        required: {
                            enabled: !!fieldSettings ? fieldSettings.address2.required : false
                        },
                        length: {
                            max: 50,
                            enabled: !!fieldSettings ? fieldSettings.address2.visible : true
                        },
                        disallowHtml: {}
                    },
                    'address.city': {
                        required: {},
                        length: {
                            max: 50
                        },
                        disallowHtml: {}
                    },
                    'address.state.id': {
                        required: {
                            validationMessage: "Please select a state",
                            isValidationMessageVisible: true
                        },
                        regexp: {
                            pattern: /^[1-9]\d*$/,
                            validationMessage: "Please select a state",
                            isValidationMessageVisible: true
                        },
                        deferredDefinitionAwareValue: {
                            deferredDefinitionViewModel: OnlineApp.ViewModels.applicationViewModel.definitionsViewModel.states
                        },
                        state: {
                            onlyIf: function () {
                                return self.address.country.id() && self.address.state.id();
                            },
                            states: OnlineApp.ViewModels.applicationViewModel.definitionsViewModel.states.items(),
                            countryId: self.address.country.id
                        }
                    },
                    'address.country.id': {
                        required: {
                            enabled: !!fieldSettings ? fieldSettings.countryID.required : false,
                            validationMessage: "Please select a country",
                            isValidationMessageVisible: true
                        },
                        regexp: {
                            pattern: !!fieldSettings && fieldSettings.countryID.required ? /^[1-9]\d*$/ : null,
                            validationMessage: "Please select a country",
                            isValidationMessageVisible: true,
                            enabled: !!fieldSettings ? fieldSettings.countryID.visible : true
                        },
                        deferredDefinitionAwareValue: {
                            deferredDefinitionViewModel: OnlineApp.ViewModels.applicationViewModel.definitionsViewModel.countries
                        }
                    },
                    'address.zipCode': {
                        required: {},
                        length: {
                            max: 20
                        },
                        zip: {
                            onlyIf: function () {
                                return self.address.country.id();
                            },
                            countryId: self.address.country.id
                        }
                    },
                    'phone.primaryPhoneExt': {
                        requiredField: $.extend({}, getPrimaryPhone(), {
                            enabled: !!fieldSettings ? fieldSettings.homePhone.visible : true
                        }),
                        length: {
                            max: 10,
                            enabled: !!fieldSettings ? fieldSettings.homePhone.visible : true
                        },
                        disallowHtml: {}
                    },
                    'phone.primaryPhone': {
                        required: {
                            enabled: !!fieldSettings ? fieldSettings.homePhone.required : false
                        },
                        requiredField: $.extend({}, getPrimaryPhone(), {
                            enabled: !!fieldSettings ? fieldSettings.homePhone.visible : true
                        }),
                        phone: {
                            countryID: function () {
                                var phoneNumberAllowed = !!fieldSettings ? fieldSettings.homePhone.visible : true;
                                if (phoneNumberAllowed) {
                                    if (self.editableItem() != undefined) {
                                        if (self.editableItem().address && self.editableItem().address.country)
                                            return self.editableItem().address.country.id();
                                    } else {
                                        if (self.address && self.address.country)
                                            return self.address.country.id();
                                    }
                                }
                            },
                        },
                        length: {
                            //phone number and extension are concatenated into a single field which is maximum 50 chars long.
                            //10 chars are reserved for the extension and 6 for the ' ext. ' text
                            max: 34,
                            enabled: !!fieldSettings ? fieldSettings.homePhone.visible : true
                        },
                        disallowHtml: {}
                    },
                    'phone.alternatePhoneExt': {
                        requiredField: $.extend({}, getAlternatePhone(), {
                            enabled: !!fieldSettings ? fieldSettings.alternatePhone.visible : true
                        }),
                        length: {
                            max: 10,
                            enabled: !!fieldSettings ? fieldSettings.alternatePhone.visible : true
                        },
                        disallowHtml: {}
                    },
                    'phone.alternatePhone': {
                        required: {
                            enabled: !!fieldSettings ? fieldSettings.alternatePhone.required : false
                        },
                        requiredField: $.extend({}, getAlternatePhone(), {
                            enabled: !!fieldSettings ? fieldSettings.alternatePhone.visible : true
                        }),
                        phone: {
                            countryID: function () {
                                var phoneNumberAllowed = !!fieldSettings ? fieldSettings.alternatePhone.visible : true;
                                if (phoneNumberAllowed) {
                                    if (self.editableItem() != undefined) {
                                        if (self.editableItem().address && self.editableItem().address.country)
                                            return self.editableItem().address.country.id();
                                    } else {
                                        if (self.address && self.address.country)
                                            return self.address.country.id();
                                    }
                                }
                            },
                        },
                        length: {
                            max: 34,
                            enabled: !!fieldSettings ? fieldSettings.alternatePhone.visible : true
                        },
                        disallowHtml: {}
                    },
                    'notificationPreference': {
                        required: {
                            enabled: !!fieldSettings ? fieldSettings.notificationType_cd.required : false
                        },
                        definitionAwareValue: {
                            definitionItems: OnlineApp.ViewModels.applicationViewModel.definitionsViewModel.notificationType.items
                        }
                    },
                    'emailAddress': {
                        required: {},
                        email: {}
                    }
                }
            };

            return config;
        };


        self.beginEmailVerificationMode = function () {
            self.contactInfoEmailVerificationViewModel.emailAddress(self.emailAddress());
            self.contactInfoEmailVerificationViewModel.initEmailVerification();
            self.isEmailVerificationMode(true);
        } 

        self.cancelEmailVerificationMode = function () {
            self.isEmailVerificationMode(false);
            $('#verify-email-contact-info-link').focus();
            layoutHelper.tabbing.updateIndices();
        }

        self.resetEmailAddress = function(newEmailAddress) {
            self.emailAddress(newEmailAddress);

            if (self.editableItem()) {
                self.editableItem().emailAddress(newEmailAddress);
            }
        };

        self.updateContactInfoAfterEmailChange = function (options) {

            self.isEmailVerified(false);
            if (options && options.isEmailChanged) self.resetEmailAddress(self.initialEmail());

            if (window.utils.getUrlParameter("redirectToVerifyAccountPage")) {
                window.location = options.forceRedirectUrl;
            } else {
                self.beginEmailVerificationMode();
            }

        };

        self.goToApplicationProcess = function() {
            var applicationProcessUrl = sessionStorage.getItem(OnlineApp.SessionKeys.ApplicationProcessUrl);

            if (applicationProcessUrl) {
                sessionStorage.removeItem(OnlineApp.SessionKeys.ApplicationProcessUrl);

                window.location = applicationProcessUrl;
            }
        };

        self.updateAccessToContactInfoSaveButton = function(isSaveButtonDisabled) {
            if ($(contactInfoSaveButtonSelector).length) $(contactInfoSaveButtonSelector).prop('disabled', isSaveButtonDisabled);
        };

        self.fromDataModel = function (data) {
            if (!data) {
                return;
            }

            self.name.fromDataModel(data.name);
            initialFullName = self.name.fullName();
            self.address.fromDataModel(data.address);
            self.phone.fromDataModel(data.phone);
            self.notificationPreference(data.notificationPreference ? data.notificationPreference.toString():"1"); // Email is default

            self.initialEmail(data.initialEmail || data.emailAddress);
            self.emailAddress(data.emailAddress);
            self.isGoogleSignIn(data.isGoogleSignIn);

            self.isEmailEditable(self.isEmailEditable() || data.isEmailEditable || !data.emailAddress || false);

            if (data.isPasswordSet != undefined)
            {
                self.isPasswordSet = data.isPasswordSet;
            }

            if (OnlineApp.ViewModels != null
                && OnlineApp.ViewModels.applicationViewModel != null
                && OnlineApp.ViewModels.applicationViewModel.jobId != null
                && OnlineApp.ViewModels.applicationViewModel.jobId() > 0) {
                self.jobId(OnlineApp.ViewModels.applicationViewModel.jobId());
            }

            self.registerValidation(self.getValidationConfig());

            $(document).trigger(OnlineApp.Events.CommonEventsNames.ContactInfomationAvailable, {
                firstName: self.name.firstName(),
                lastName: self.name.lastName(),
                email: self.emailAddress()
            });
        };

        var baseDiscardChanges = self.discardChanges;
        self.discardChanges = function (item, e) {            
            self.isDiscardChange(true);
            baseDiscardChanges.call(self, item, e);
            self.goToApplicationProcess();
        };

        self.saveChanges = (function(base) {
            return function(item) {
                var editableItem = self.editableItem(),
                    that = this,
                    saveChangesArguments = arguments,
                    promise;

                item.isBusy(true);
                self.updateAccessToContactInfoSaveButton(true);


                /*
                   Switch for email verification. The logic is similar the default but conditions related to the captcha were deleted 
                   and the final promise on getting saving result changed

                */
                if (self.enableEmailVerification()) {

                    if (editableItem.isEmailChanged() && self.isEmailEditable()) {


                        var isPasswordValid = (OnlineApp.ViewModels.accountSettingsViewModel 
                                && OnlineApp.ViewModels.accountSettingsViewModel.isImpersonatedJobSeeker) ||
                            !self.isPasswordSet ||
                            editableItem.currentPassword.validate();

                        if (!self.hasErrorPureComputed() && !isPasswordValid) {
                            self.isBusy(false);
                            self.updateAccessToContactInfoSaveButton(false);
                            triggerValidationFailedEvent(saveChangesArguments);
                            return false;
                        }
                    }

                    promise = $.when(function() { return true; });

                    //send request to email check service
                    if (editableItem && editableItem.emailAddress() !== self.initialEmail() && self.isEmailEditable()) {
                        editableItem.emailAddress.validate();

                        var isEmailAllowedRequestData = {
                            email: editableItem.emailAddress(),
                            captchaAnswer: editableItem.textCaptchaViewModel.userAnswer(),
                            password: editableItem.currentPassword()
                        }

                        if (!editableItem.emailAddress.hasError()) {
                            promise = promise.then(function() {
                                return OnlineApp.Services.authenticationService
                                    .isEmailAllowed(isEmailAllowedRequestData)
                                    .then(
                                        function(data) {
                            
                                            if (data.success) {
                                                editableItem.emailAddress.hasError(!data.isEmailAllowed);
                                                editableItem.isEmailNotAvailable(!data.isEmailAllowed);

                                                return data.isEmailAllowed;
                                            } else {

                                                var innerPromise;

                                                innerPromise = $.when(function() { return true; });

                                                innerPromise = innerPromise.then(function() {
                                                    if (data.errorPropertyName == 'Password') {
                                                        editableItem.currentPassword.validationMessage(data.errorMessage);
                                                        editableItem.currentPassword.hasError(true);
                                                        editableItem.currentPassword.isValidationMessageVisible(true);
                                                    }

                                                    return false;
                                                });
                                                
                                                return innerPromise;
                                            }


                                        },
                                        //fail callback
                                        function() {
                                            toastr.warning(Resources.NotificationMessages.ServiceUnavailable);

                                            return window.undefined;
                                        }
                                    );
                            });
                        }
                    }

                    editableItem.name.normalize();

                    var isResumeLoadedInCurrentSession = OnlineApp.ViewModels.applicationViewModel.importResumeViewModel &&
                        OnlineApp.ViewModels.applicationViewModel.importResumeViewModel.resumeUploadComplete();
                    if (!isResumeLoadedInCurrentSession && initialFullName && editableItem && editableItem.name.fullName() !== initialFullName) {
                        var deferred = $.Deferred();
                        OnlineApp.Controllers.notificationController.showCreateNewAccountNotification(function () {
                            deferred.then(function () {
                                return OnlineApp.Services.authenticationService.logout().done(
                                    function() {
                                        sessionStorage.setItem('shouldCreateNewAccount', "true");
                                        $(window).on('beforeunload', function () {
                                            $(window).scrollTop(0);
                                        });
                                        location.reload();
                                    });
                            });

                            deferred.resolve(false);
                        }, function () {
                            deferred.resolve(true);
                        });
                        promise = promise.then(function(isValid) {
                            if (isValid) {
                                return deferred; 
                            }
                            return false;
                        });
                    }

                    promise = promise.then(function (saveAllowed) {
                        if (saveAllowed) {
                            if (editableItem.isEmailChanged() && self.isEmailEditable()) {
                                gJobs.crossWindowCommunicationService.sendMessage(
                                    gJobs.subjects.EmailUpdated,
                                    editableItem.emailAddress()
                                );
                            }

                            var queryStringData = { 
                            fromAppProcess: self.fromAppProcess(),
                            returnUrl: encodeURIComponent(window.location.href)
                        };

                            if (self.enableEmailVerification()) {
                                if (window.utils.getUrlParameter("redirectToVerifyAccountPage")) {
                                    queryStringData.sendAccountVerifEmail = true;
                                }

                                var applicationProcessUrl = sessionStorage.getItem(OnlineApp.SessionKeys.ApplicationProcessUrl);

                                if (applicationProcessUrl) {
                                    queryStringData.redirectionUrl = applicationProcessUrl;
                                    //sessionStorage.removeItem(OnlineApp.SessionKeys.ApplicationProcessUrl);
                                }
                                 
                            }

                        var agencyFolderName = AgencyPages.pageInfoService ?
                            AgencyPages.pageInfoService.getCurrentAgencyFolderName() :
                            gJobs.pageInfoService.getCurrentAgencyPageFolderName();
                        
                        if (agencyFolderName) {
                            queryStringData.agencyFolderName = agencyFolderName;
                        }

                        var args = Array.prototype.slice.call(saveChangesArguments);
                        args.push(queryStringData);
                        
                        return base.apply(that, args);
                        } else {
                            triggerValidationFailedEvent(saveChangesArguments);
                        }

                        return window.undefined;
                    });

                    promise = promise
                        .done(function (data) {
                            if (self.isAccountSettingsPage()) {
                                if (data && data.isSuccess && data.payload && !data.payload.isImpersonatedJobSeeker) {
                                    if (data.payload.forceRedirectUrl) {
                                        window.location = data.payload.forceRedirectUrl;
                                        return;
                                    }

                                    var options = null;

                                    if (data.payload.isEmailChanged) {
                                        options = { changedEmailAddressWasAdded: true, isEmailChanged: data.payload.isEmailChanged, forceRedirectUrl: data.payload.forceRedirectUrl };
                                        gJobs.localStorageHelper.updateItemForMultipleTabs(OnlineApp.LocalStorageKeys.EmailWasChanged, "true");
                                        localStorage.setItem('updatedEmail', data.payload.updatedEmail);
                                    }

                                    if (self.fromAppProcess() || window.utils.getUrlParameter("changeEmail")) {
                                        if (data.payload.isEmailChanged) {
                                            gJobs.localStorageHelper.updateItemForMultipleTabs(
                                                OnlineApp.LocalStorageKeys.EmailWasChangedAndNewVerificationCodeSent,
                                                "true"
                                            );

                                            self.updateContactInfoAfterEmailChange(options);
                                        } else {
                                            self.goToApplicationProcess();
                                        }
                                    } else if (data.payload.isEmailChanged) {
                                        self.updateContactInfoAfterEmailChange(options);
                                    }

                                    if (window.enableTwoFactorAuthentication && data.payload.isEmailChanged) {
                                        $(document).trigger(OnlineApp.Events.CommonEventsNames.EmailWasChanged, options);
                                    }
                                }
                            }
                        })
                    .always(function() {
                        item.isBusy(false);
                        self.updateAccessToContactInfoSaveButton(false);
                        self.validate();
                    });

                    return promise;
            } else {
                if (editableItem.isEmailChanged() && self.isEmailEditable()) {

                    var isCaptchaSubmitted = captchaHelper.isCaptchaSubmitted;
                    editableItem.showCaptchaValidationMessage(!isCaptchaSubmitted);

                    var isPasswordValid = (OnlineApp.ViewModels.accountSettingsViewModel 
                            && OnlineApp.ViewModels.accountSettingsViewModel.isImpersonatedJobSeeker) ||
                        !self.isPasswordSet ||
                        editableItem.currentPassword.validate();

                    if (!self.hasErrorPureComputed() && 
                        !(isPasswordValid && ((isCaptchaSubmitted && !window.textCaptcha) || 
                            (window.textCaptcha && editableItem.textCaptchaViewModel.validate())))) {
                        self.isBusy(false);
                        self.updateAccessToContactInfoSaveButton(false);
                        triggerValidationFailedEvent(saveChangesArguments);
                        return false;
                    }
                }

                promise = $.when(function() { return true; });

                //send request to email check service
                if (editableItem && editableItem.emailAddress() !== self.initialEmail() && self.isEmailEditable()) {
                    editableItem.emailAddress.validate();

                    var isEmailAllowedRequestData = {
                        email: editableItem.emailAddress(),
                        captchaAnswer: editableItem.textCaptchaViewModel.userAnswer(),
                        password: editableItem.currentPassword()
                    }

                    if (!editableItem.emailAddress.hasError()) {
                        promise = promise.then(function() {
                            return OnlineApp.Services.authenticationService
                                .isEmailAllowed(isEmailAllowedRequestData)
                                .then(
                                    function(data) {
                                        if (editableItem.isEmailChanged() && !self.textCaptchaEnabled) {
                                            captchaHelper.resetCaptcha();
                                        }

                                        if (data.success) {
                                            editableItem.emailAddress.hasError(!data.isEmailAllowed);
                                            editableItem.isEmailNotAvailable(!data.isEmailAllowed);

                                            return data.isEmailAllowed;
                                        } else {
                                            var resetTextCaptcha = editableItem.textCaptchaViewModel.validate();

                                            var innerPromise;

                                            if (resetTextCaptcha) {
                                                innerPromise = editableItem.textCaptchaViewModel.resetCaptcha();
                                            } else {
                                                innerPromise = $.when(function() { return true; });
                                            }

                                            innerPromise = innerPromise.then(function() {
                                                if (data.errorPropertyName == 'Password') {
                                                    editableItem.currentPassword.validationMessage(data.errorMessage);
                                                    editableItem.currentPassword.hasError(true);
                                                    editableItem.currentPassword.isValidationMessageVisible(true);
                                                } else if (data.errorPropertyName == 'Captcha') {
                                                    editableItem.textCaptchaViewModel.userAnswer.hasError(true);
                                                    if (resetTextCaptcha) {
                                                        editableItem.textCaptchaViewModel.userAnswer.validationMessage('Captcha is invalid');
                                                    } else {
                                                        editableItem.textCaptchaViewModel.userAnswer.validationMessage('This field is required');
                                                    }
                                                    editableItem.textCaptchaViewModel.userAnswer.isValidationMessageVisible(true);
                                                }

                                                return false;
                                            });
                                            
                                            return innerPromise;
                                        }


                                    },
                                    //fail callback
                                    function() {
                                        toastr.warning(Resources.NotificationMessages.ServiceUnavailable);

                                        return window.undefined;
                                    }
                                );
                        });
                    }
                }

                editableItem.name.normalize();

                var isResumeLoadedInCurrentSession = OnlineApp.ViewModels.applicationViewModel.importResumeViewModel &&
                    OnlineApp.ViewModels.applicationViewModel.importResumeViewModel.resumeUploadComplete();
                if (!isResumeLoadedInCurrentSession && initialFullName && editableItem && editableItem.name.fullName() !== initialFullName) {
                    var deferred = $.Deferred();
                    OnlineApp.Controllers.notificationController.showCreateNewAccountNotification(function () {
                        deferred.then(function () {
                            return OnlineApp.Services.authenticationService.logout().done(
                                function() {
                                    sessionStorage.setItem('shouldCreateNewAccount', "true");
                                    $(window).on('beforeunload', function () {
                                        $(window).scrollTop(0);
                                    });
                                    location.reload();
                                });
                        });

                        deferred.resolve(false);
                    }, function () {
                        deferred.resolve(true);
                    });
                    promise = promise.then(function(isValid) {
                        if (isValid) {
                            return deferred; 
                        }
                        return false;
                    });
                }

                promise = promise.then(function (saveAllowed) {
                    if (saveAllowed) {
                        if (editableItem.isEmailChanged() && self.isEmailEditable()) {
                            gJobs.crossWindowCommunicationService.sendMessage(
                                gJobs.subjects.EmailUpdated,
                                editableItem.emailAddress()
                            );
                        }

                        var queryStringData = { fromAppProcess: self.fromAppProcess(), fromAccountSettings: self.isAccountSettingsPage() };

                        if (self.fromAppProcess()) {

                            var agencyFolderName = AgencyPages.pageInfoService ?
                                AgencyPages.pageInfoService.getCurrentAgencyFolderName() :
                                gJobs.pageInfoService.getCurrentAgencyPageFolderName();

                            if (agencyFolderName) {
                                queryStringData.agencyFolderName = agencyFolderName;
                            }
                        }

                            var args = Array.prototype.slice.call(saveChangesArguments);
                            args.push(queryStringData);

                            return base.apply(that, args);
                        } else {
                            triggerValidationFailedEvent(saveChangesArguments);
                        }

                        return window.undefined;
                    
                });

                promise = promise
                    .done(function (data) {
                        if (data && data.payload && data.payload.isEmailChanged) {
                            if (self.fromAppProcess()) {
                                localStorage.setItem('updatedEmail', data.payload.updatedEmail);
                                sessionStorage.setItem('emailWasChangedAndNewVerificationCodeSent', 'true');
                            }
                        }
                    })
                .always(function() {
                    item.isBusy(false);
                    self.updateAccessToContactInfoSaveButton(false);
                    self.validate();
                });

                return promise;
            }
        }
        })(self.saveChanges);

        function triggerValidationFailedEvent(event) {
            if (OnlineApp.Events) {
                var validationFailedEvent =
                    jQuery.Event(OnlineApp.Events.CommonEventsNames.PreSaveValidationFailed);
                validationFailedEvent.target = event.target;
                $(document).trigger(validationFailedEvent);
            }
        }

        gJobs.crossWindowCommunicationService.setListener(
            gJobs.subjects.EmailUpdated,
            function (newEmail) {
                self.emailAddress(newEmail);
                if (self.editableItem()) {
                    self.editableItem().emailAddress(newEmail);
                }
            }
        );

        self.emailFieldLoaded = function (elements) { 
            var emailInputField = $(elements).find('input');
            emailInputField.keydown(function(e) {
                var keyCode = e.keyCode || e.which;
                var isShiftPressed = e.shiftKey;
                setTimeout(function() {
                    if (!isShiftPressed && keyCode === $.ui.keyCode.TAB && self.isEmailEditable() && self.isEmailChanged()) {
                        $('#currentPassword').focus();
                    }
                });
            });
        }
        
        self.showHideAriaLabel = function () {
            if ($("fieldset.radio-set.css3-radio").length > 0) {
                $("fieldset.radio-set.css3-radio").each(function (i) {
                    $("fieldset.radio-set.css3-radio")[i].removeAttribute("aria-required");
                });
            }
        }

        if (self.enableEmailVerification()) {
            OnlineApp.Services.authenticationService.isLoggedIn()
            .done(function(isLoggedIn) {
                if (isLoggedIn) {
                    OnlineApp.Services.emailVerificationService.isEmailVerified()
                        .then(function(response) {
                        var data = response.data;
        
                        self.isEmailVerified(data.isEmailVerified);
                        });
                }
            });

            $(document).on(OnlineApp.Events.CommonEventsNames.EmailVerified, function (event, data) {
                self.isEmailVerificationMode(false);
                self.isEmailVerified(true);

                if (self.contactInfoEmailVerificationViewModel) {
                    self.contactInfoEmailVerificationViewModel
                        .emailVerificationViewModel
                        .changedEmailAddressWasAdded = ko.observable(false);
                }

                if (data && data.changedEmailAddress) {
                    self.initialEmail(data.changedEmailAddress);
                    self.resetEmailAddress(data.changedEmailAddress);
                }

                var applicationProcessUrl = sessionStorage.getItem(OnlineApp.SessionKeys.ApplicationProcessUrl);

                if (applicationProcessUrl) {
                    sessionStorage.removeItem(OnlineApp.SessionKeys.ApplicationProcessUrl);

                    window.location = applicationProcessUrl;
                }
            });

            $(document).on(OnlineApp.Events.CommonEventsNames.ContactInfoEmailVerificationFormClosed, self.cancelEmailVerificationMode);

            var loginEvents = Events.CommonEventsNames.Login + ' ' + Events.CommonEventsNames.Register;

            $(document).on(loginEvents, function () {
                self.initContactInfoEmailVerificationViewModel();
            });
        }
    };


    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        ContactInfoViewModel: ContactInfoViewModel
    });

})(window);;
(function (window, undefined) {
    'use strict';

    function ChangePasswordViewModel() {
        var config = {
            endpoint: "changePassword",
            get: false
        };

        var self = OnlineApp.ViewModels.Base.EditableViewModel.call(this, config) || this;
        var changePasswordFormSelector = '#change-password form';

        self.currentPassword = ko.observable().extend({ required: {} });
        self.currentPassword.wrapValidationMessage = ko.observable(true);
        self.newPassword = OnlineApp.ViewModels.Common.PasswordExtender({ required: {}, password: {} });

        self.popoverContent = ko.observable(Resources.AdditionalInfoMessages.ThingsToConsider);
        self.passwordRequirements = Resources.AdditionalInfoMessages.passwordRequirements;

        self.isCurrentPasswordSelected = ko.observable(false);
        self.isNewPasswordSelected = ko.observable(false);
        self.hasCurrentPasswordChangedAfterError = ko.observable(true);
        self.hasNewPasswordChangedAfterError = ko.observable(true);        

        self.currentPassword.subscribe(function (value) {
            self.hasCurrentPasswordChangedAfterError(true);
        });

        self.newPassword.subscribe(function (value) {
            self.hasNewPasswordChangedAfterError(true);
        });        

        self.isCurrentPasswordSelected.subscribe(function (value) {
            if (!value && self.hasCurrentPasswordChangedAfterError()) {
                self.currentPassword.validate();
            }
        })

        self.isNewPasswordSelected.subscribe(function (value) {
            if (!value && self.hasNewPasswordChangedAfterError()) {
                self.newPassword.validate();
            }
        })
        

        self.isIE = ko.observable(gJobs.browserDetector.isIE());
        self.isInPasswordBlock = ko.observable(false);
        self.inPasswordBlock = function () {
            self.isInPasswordBlock(true);
        };
        self.outOfPasswordBlock = function () {
            // set handling to the end of event queue
            setTimeout(function () {
                if (self.isInPasswordBlock() && !self.isNewPasswordSelected() && !self.newPassword.isConfirmPasswordSelected()) {
                    self.isInPasswordBlock(false);
                }
            }, 0);
        };

        self.newPasswordSameAsOld = ko.computed(function () {
            if (self.currentPassword() === '')
                return false;

            if (self.newPassword.hasError())
                return false;

            return self.newPassword() == self.currentPassword();
        }).extend({ throttle: 1 });

        self.changePassword = function () {
            var vmData = {
                currentPassword: self.currentPassword(),
                newPassword: self.newPassword(),
                confirmNewPassword: self.newPassword.confirmPassword()
            };

            $.post("/user/changePassword", vmData, function (data) {
                if (data.shouldLogout) {
                    OnlineApp.Services.authenticationService.logout().done(function () {
                        location.reload();
                    });
                }

                if (data.isSuccess) {
                    var passwordChangedSuccessMessage = "Password changed!";
                    toastr.success(passwordChangedSuccessMessage);                    

                    // clear fields
                    self.currentPassword("");
                    self.currentPassword.isValidationMessageVisible(false);
                    self.currentPassword.hasError(false);

                    self.newPassword("");
                    self.newPassword.isValidationMessageVisible(false);
                    self.newPassword.hasError(false);

                    self.newPassword.confirmPassword("");
                    OnlineApp.Helpers.layoutHelper.tabbing.getFirstElement($(changePasswordFormSelector)).focus();

                    setTimeout(function () {
                        gJobs.screenReadersService.setAriaLiveNotification(passwordChangedSuccessMessage);
                    },300);
                }
                else {
                    switch (data.errorPropertyName) {
                        case 'Current Password':
                            self.currentPassword.hasError(true);
                            self.currentPassword.isValidationMessageVisible(true);
                            self.currentPassword.validationMessage(data.errorMessage);
                            self.hasCurrentPasswordChangedAfterError(false);
                            if (self.newPasswordSameAsOld()) {
                                self.newPassword.validationMessage("You can't pick the old password");
                            }                            
                            $('#ci-currentPassword').focus();
                            break;
                        case 'New Password':
                            self.newPassword.hasError(true);
                            self.newPassword.isValidationMessageVisible(true);

                            if (self.newPasswordSameAsOld()) {
                                self.newPassword.validationMessage("You can't pick the old password");
                            }
                            else {
                                self.newPassword.validationMessage(data.errorMessage);
                            }
                            self.hasNewPasswordChangedAfterError(false);
                            $('#ci-newPassword').focus();
                            break;
                        case 'Confirm New Password':
                            self.newPassword.confirmPassword.hasError(true);
                            self.newPassword.confirmPassword.isValidationMessageVisible(true);                            
                            self.newPassword.confirmPassword.validationMessage(data.errorMessage);                            
                            $('#ci-newConfirmPassword').focus();
                            break;
                        default:
                            OnlineApp.Helpers.layoutHelper.tabbing.getFirstElement($(changePasswordFormSelector)).focus();
                            break;
                    }
                }

               
            });

        };

        self.validate = function () {
            self.currentPassword.validate();
            if (self.currentPassword.hasError() || !self.hasCurrentPasswordChangedAfterError()) {
                return false;
            }

            self.newPassword.validate();
            if (self.newPassword.hasError() || !self.hasNewPasswordChangedAfterError()) {
                return false;
            }

            self.newPassword.confirmNewPassword.validate()
            if (self.newPassword.confirmNewPassword.hasError()) {
                return false;
            }

            if (self.newPasswordSameAsOld()) {
                return false;
            }

            return true;
        };
    }

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        ChangePasswordViewModel: ChangePasswordViewModel
    });
})(window);;
(function (window, undefined) {
    'use strict';

    function EmailPreferencesViewModel(hidePromotionalEmailsOption) {
        var config = {
            endpoint: "emailPreferences",
            passAgencyFolderName: true,
            passJobId: true
        };
        var self = OnlineApp.ViewModels.Base.DataViewModel.call(this, config) || this;

        self.promotionalEmails = ko.observable(true);
        self.jobApplicationEmails = ko.observable(true);
        self.agencyName = ko.observable('');

        self.hidePromotionalEmailsOption = hidePromotionalEmailsOption;
        self.showOnSubmitTab = ko.observable(false);

        self.jobApplicationEmailsInfoShown = ko.observable(false);

        self.toggleJobApplicationEmailsInfo = function() {
            self.jobApplicationEmailsInfoShown(!self.jobApplicationEmailsInfoShown());
            if (self.jobApplicationEmailsInfoShown()) {
                var message = $('#job-application-option-details').text();
                gJobs.screenReadersService.setAriaLiveNotification(message);
            }
        }

        self.fromDataModel = function(data) {
            if (!data) {
                return;
            }

            self.promotionalEmails(data.promotionalEmails);
            self.jobApplicationEmails(data.jobApplicationEmails);
            self.agencyName(data.agencyName);

            if (!data.jobApplicationEmails) {
                self.showOnSubmitTab(true);
            }
        }

        self.updatePromotionalEmailsPreference = function() {
            self.save(self.toDataModel())
                .done(function() {
                    var message = 'You have been successfully ' + (self.promotionalEmails() ? 'subscribed to' : 'unsubscribed from') + " job opportunity emails.";
                    gJobs.screenReadersService.setAriaLiveNotification(message);
                })
                .fail(function() {
                    self.promotionalEmails(!self.promotionalEmails());
                });
            return true;
        }

        self.updateJobApplicationEmailsPreference = function () {
            self.save(self.toDataModel())
                .done(function () {
                    var message = 'You have been successfully ' + (self.jobApplicationEmails() ? 'subscribed to' : 'unsubscribed from') + " job application emails.";
                    gJobs.screenReadersService.setAriaLiveNotification(message);
                })
                .fail(function () {
                    self.jobApplicationEmails(!self.jobApplicationEmails());
                });
            return true;
        }

        self.onToggleFocused = function (vm, e) {
            var message = $(e.target).closest(".option-container").find(".option-description").text();
            gJobs.screenReadersService.setAriaLiveNotification(message);
        }

        self.getInboxUrl = function () {
            var redirectUrl = '/inbox';
            var currentArea = gJobs.areaInfoService.getCurrentArea();
            if (currentArea === gJobs.areaInfoService.areaNames.Career) {
                redirectUrl = AgencyPages.pageInfoService.getCurrentAgencyHomePageUrl() + redirectUrl;
            } else if (currentArea === gJobs.areaInfoService.areaNames.Agency) {
                var employerFolderName = AgencyPages.pageInfoService ?
                    AgencyPages.pageInfoService.getCurrentAgencyFolderName() :
                    gJobs.pageInfoService.getCurrentAgencyPageFolderName();
                if (employerFolderName) {
                    redirectUrl = '/AgencyInbox/' + employerFolderName;
                }
            }
            return redirectUrl;
        }

    }

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        EmailPreferencesViewModel: EmailPreferencesViewModel
    });
})(window);;
(function (window, undefined) {
    'use strict';

    function EmailVerificationViewModel(options) {
        var options = options ? options : {};
        
        var RESEND_VERIFICATION_CODE_ATTEMPTS_COUNT_WITHOUT_CAPTCHA = window.emailVerificationResendAttempts;
        var VERIFICATION_CODE_VERIFY_ATTEMPTS_COUNT_WITHOUT_CAPTCHA = window.emailVerificationVerifyAttempts;
        var CAPTCHA_LABEL_HTML_CONTENT_FOR_RESEND_CODE = "<span>Please answer the question to <b>resend</b> a code again</span>";
        var CAPTCHA_LABEL_HTML_CONTENT_FOR_VERIFICATION_CODE = "<span>Please answer the question to <b>verify</b> a code again</span>";
        var CAPTCHA_INVALID_MESSAGE = "Captcha is invalid";
        var CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFY_CODE = "captcha-user-answer-for-verify-code";
        var CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE = "captcha-user-answer-for-resend-code";
        var INSTRUCTIONS_MESSAGE_FOR_SENT_CODE = "We've sent a " + window.emailVerificationCodeLength +
            " digit code to your email address and the code is only valid for " + window.emailVerificationCodeDurationInMins +
            " minutes. Please enter the code below. ";

        var verificationCodeInput;
        var lastFocusableElement;

        var isUserDataInitiated = false;
        var emailWasChangedAndNewVerificationCodeSent = false;

        var self = OnlineApp.ViewModels.Base.ValidatableViewModel.apply(this, arguments) || this;

        self.enableEmailVerification = ko.observable(window.enableEmailVerification);

        self.isNeedToHideHeader = ko.observable(options.isNeedToHideHeader);
        self.isNeedToHideInstructions = ko.observable(options.isNeedToHideInstructions);
        self.verificationCodeLabelText = ko.observable(options.verificationCodeLabelText ? options.verificationCodeLabelText : "Verification code");
        self.verificationCodeAriaLabelText = ko.observable(
            options.isNeedToHideInstructions
            ? INSTRUCTIONS_MESSAGE_FOR_SENT_CODE + self.verificationCodeLabelText()
            : self.verificationCodeLabelText());
        self.useCustomVerifyButton = ko.observable(options.useCustomVerifyButton);
        
        var abstractAreaInfoService = new gJobs.AbstractAreaInfoService();

        self.textCaptchaViewModelForResendCode = new OnlineApp.ViewModels.TextCaptchaViewModel("ResendEmailVerificationCodeAnswer");
        self.textCaptchaViewModelForVerificationCode = new OnlineApp.ViewModels.TextCaptchaViewModel("VerifyEmailVerificationCodeAnswer");

        self.textCaptchaEnabled = window.textCaptcha;
        self.isNeedToShowEmailVerificationForm = ko.observable(false);
        self.isEmailVerified = ko.observable();
        self.userEmail = ko.observable();
        self.verificationAttemptsCount = ko.observable(0);
        self.resendEmailVerificationCount = ko.observable(0);
        self.isEmailVerificationSubmitButtonEnabled = ko.observable(false);
        self.emailVerificationCode = ko.observable("").extend({
            required: {},
            verificationCode: {
                regExpForValueTransform: /_/g,
                validationMessage: OnlineApp.Validation.validationMessages.invalidEmailVerificationCode
            }
        });

        self.emailVerificationCode.subscribe(function(newValue) {
            if (newValue !== "" && self.emailVerificationCode.validate(newValue)) {
                self.isEmailVerificationSubmitButtonEnabled(true);
            } else {
                self.isEmailVerificationSubmitButtonEnabled(false);
            }
            
            OnlineApp.Helpers.layoutHelper.tabbing.updateIndices();
        });

        self.changedEmailAddressWasAdded = ko.observable(false);

        function updateFieldErrorState (field, hasError, errorMessage) {
            field.hasError(hasError);
            field.isValidationMessageVisible(hasError);

            if (hasError && errorMessage) {
                field.validationMessage(errorMessage);
            }
        };

        function resetCaptcha (textCaptchaViewModel, htmlContentForLabel, captchaUserAnswerId) {
            textCaptchaViewModel.setCustomLabelHtmlContent(htmlContentForLabel);
            textCaptchaViewModel.setCustomUserAnswerInputId(captchaUserAnswerId);

            return textCaptchaViewModel.resetCaptcha(
                textCaptchaViewModel.userAnswer.hasError(),
                CAPTCHA_INVALID_MESSAGE
            );
        };

        function removeItemFromLocalStorage(key, delay) {
            setTimeout(function () {
                localStorage.removeItem(key);
            }, delay);
        }

        function checkEmailForUpdate() {
            setInterval(function() {
                if (localStorage.getItem('updatedEmail')  && localStorage.getItem('updatedEmail') !== self.userEmail()) {
                    self.userEmail(localStorage.getItem('updatedEmail'));
                    removeItemFromLocalStorage('updatedEmail', 5000);
                }
            }, 5000)
        }

        function tryFocusOnErrorCaptcha (isEmailVerificationContainerVisible, captchaUserAnswerInputId) {
            if (isEmailVerificationContainerVisible
                && lastFocusableElement.length
                && lastFocusableElement.attr('id') === captchaUserAnswerInputId
            ) {
                $("#" + captchaUserAnswerInputId).focus();
            }
        }

        self.initUserData = function (options) {
            self.emailVerificationCode('');
            updateFieldErrorState( self.emailVerificationCode, false);
            updateFieldErrorState(self.textCaptchaViewModelForResendCode.userAnswer, false);
            updateFieldErrorState(self.textCaptchaViewModelForVerificationCode.userAnswer, false);

            OnlineApp.Services.emailVerificationService
            .getUserData()
            .then(function (response) {
                var data = response.data;

                self.isEmailVerified(data.isEmailVerified);
                self.userEmail(data.userEmail);
                self.verificationAttemptsCount(data.verificaitonAttempts)
                self.resendEmailVerificationCount(data.resendEmailVerificationCount);

                if (self.isNeedToShowResendVerificationCodeCaptcha()) {
                    resetCaptcha(
                        self.textCaptchaViewModelForResendCode, 
                        CAPTCHA_LABEL_HTML_CONTENT_FOR_RESEND_CODE,
                        CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE
                    );
                }

                if (self.isNeedToShowVerificationCodeCaptcha()) {
                    resetCaptcha(
                        self.textCaptchaViewModelForVerificationCode, 
                        CAPTCHA_LABEL_HTML_CONTENT_FOR_VERIFICATION_CODE,
                        CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFY_CODE
                    );
                }

                if (!self.isEmailVerified()) {
                    checkEmailForUpdate();
                    self.isNeedToShowEmailVerificationForm(true);
                }

                isUserDataInitiated = true;

                if (options && options.changedEmailAddressWasAdded) {
                    self.isEmailVerified(false);
                    updateFieldErrorState(self.emailVerificationCode, false);
                    self.emailVerificationCode('');
                }

                self.onReady();
            });
        }

        self.onReady = function () {
            verificationCodeInput = $('#verification-code');
            verificationCodeInput.inputmask({'mask': '999999'});

            if (verificationCodeInput.length) verificationCodeInput.focus();
        }

        self.init = function () {
            if (self.enableEmailVerification()) {
                if (!isUserDataInitiated) {
                    self.initUserData();
                }

                OnlineApp.Services.emailVerificationService.trySendEmailVerificationCode();
            }
        }

        self.resetForm = function () {
            if (self.isNeedToShowVerificationCodeCaptcha()) {
                updateFieldErrorState(self.textCaptchaViewModelForVerificationCode.userAnswer, false);

                resetCaptcha(
                    self.textCaptchaViewModelForVerificationCode,
                    CAPTCHA_LABEL_HTML_CONTENT_FOR_VERIFICATION_CODE,
                    CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFY_CODE
                );
            }

            if (self.isNeedToShowResendVerificationCodeCaptcha()) {
                updateFieldErrorState(self.textCaptchaViewModelForResendCode.userAnswer, false);

                resetCaptcha(
                    self.textCaptchaViewModelForResendCode,
                    CAPTCHA_LABEL_HTML_CONTENT_FOR_RESEND_CODE,
                    CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE
                );
            }

            self.emailVerificationCode("");
            updateFieldErrorState(self.emailVerificationCode, false);
        }

        self.goToAccountSettingsPage = function() {
            var QUERY_PARAMETERS = '?fromAppProcess=true#contact';

            var linkForAccountSettings = gJobs.accountSettingsHelper.getLinkForAccountSettings();
            linkForAccountSettings += QUERY_PARAMETERS;

            sessionStorage.setItem(OnlineApp.SessionKeys.ApplicationProcessUrl, window.location.href);

            window.location = linkForAccountSettings;
        };

        self.showSuccessNotification = function (htmlContent) {
            var successEmailNotificationEventName = "successEmailNotification";
            var successEmailNotificationSelector = "success-email-notification";
            var successEmailNotification = $('#' + successEmailNotificationSelector);

            if (successEmailNotification.length !== 0) {
                successEmailNotification.html(htmlContent);
                successEmailNotification.css("display", "flex");
            } else {
                $('body').append(
                    "<div class='uses-gjobs-styles'><div id='" + successEmailNotificationSelector + "'>" + htmlContent + "</div></div>"
                );

                successEmailNotification = $('#' + successEmailNotificationSelector);
            }

            gJobs.screenReadersService.setAriaLiveNotification(successEmailNotification.text());

            $(document).on('click.' + successEmailNotificationEventName, function () {
                if (successEmailNotification.is(":visible")) {
                    successEmailNotification.css("display", "none");
                }
            });

            setTimeout(function () {
                if (successEmailNotification.is(":visible")) {
                    successEmailNotification.css("display", "none");
                }

                $(document).off('click.' + successEmailNotificationEventName);
            }, 10000)
        }

        self.showResendCodeSuccessNotification = function () {
            var htmlContent = "<div class='success-email-notification-holder'><span>A new verification code has been sent to your email address</span></div>";

            self.showSuccessNotification(htmlContent);
        }

        self.showResendCodeOnNewEmailNotification = function () {
            var htmlContent = "<div class='success-email-notification-holder'><span>A new verification code has been sent to your new email address</span></div>";
        
            self.showSuccessNotification(htmlContent);
        }

        self.showSuccessEmailVerifcationNotification = function () {
            var htmlContent = "<div class='success-email-notification-holder'><img class='email-verification-success-icon' src='/Content/Images/email-verification-success-notification-icon-white.svg' /><span>Your account (" + self.userEmail() + ") is verified</span></div>";
        
            self.showSuccessNotification(htmlContent);
        }

        self.isNeedToShowResendVerificationCodeCaptcha = function () {
            return !self.isEmailVerified() && self.textCaptchaEnabled && (self.resendEmailVerificationCount() > RESEND_VERIFICATION_CODE_ATTEMPTS_COUNT_WITHOUT_CAPTCHA);
        }

        self.isNeedToShowVerificationCodeCaptcha = function () {
            return !self.isEmailVerified() && self.textCaptchaEnabled && (self.verificationAttemptsCount() > VERIFICATION_CODE_VERIFY_ATTEMPTS_COUNT_WITHOUT_CAPTCHA);
        }

        self.resendEmailVerificationCode = function () {
            if (self.isEmailVerified()) {
                return;
            }

            if (self.isNeedToShowResendVerificationCodeCaptcha()) {
                if (!self.textCaptchaViewModelForResendCode.validate()) {
                    $('#' + CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE).focus();
                    return;
                };
            }

            OnlineApp.Services.emailVerificationService
            .resendEmailVerificationCode(self.textCaptchaViewModelForResendCode.userAnswer(), self.changedEmailAddressWasAdded())
            .then(function (response) {
                var isCaptchaInvalid = false;
                var data = response.data;
                var newResendEmailVerificationCount = data.resendEmailVerificationCount;
                self.resendEmailVerificationCount(newResendEmailVerificationCount);

                if (data.isResendEmailSucceeded === false) {
                    if (data.isCaptchaInvalid === true) {
                        isCaptchaInvalid = true;
                        updateFieldErrorState(self.textCaptchaViewModelForResendCode.userAnswer, true, CAPTCHA_INVALID_MESSAGE);
                    }
                } else {
                    self.showResendCodeSuccessNotification();
                }

                if (self.isNeedToShowResendVerificationCodeCaptcha()) {
                    resetCaptcha(
                        self.textCaptchaViewModelForResendCode, 
                        CAPTCHA_LABEL_HTML_CONTENT_FOR_RESEND_CODE,
                        CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE
                    ).always(function () {
                        if (isCaptchaInvalid) {
                            $('#' + CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE).focus();
                        }
                    });
                }
            });
        }


        self.getRedirectLinkForSuccessfullEmailVerification = function() {
                OnlineApp.Services
                .emailVerificationService
                .getRedirectLinkForSuccessfullEmailVerification()
                .done(function (response) {
                    var data = response.data;

                    if (data.redirectedLink !== "") {
                        window.location = data.redirectedLink;
                    }
                });
        }
        
        self.submitVerifyEmail = function () {
            self.isEmailVerificationSubmitButtonEnabled(false);

            if (self.isNeedToShowVerificationCodeCaptcha()) {
                if (!self.textCaptchaViewModelForVerificationCode.validate()) {
                    $("#" + CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFY_CODE).focus();
                    self.isEmailVerificationSubmitButtonEnabled(true);
                    return;
                };
            }            

            /*
                The default behavior assumes that the verify email button is not available until 
                a 6-digit code is entered, when the custom verify email button is used we cannot
                guarantee the same behavior, in this case we need to validate the email verification code

            */
            if (self.useCustomVerifyButton() && !self.emailVerificationCode.validate()) {
                updateFieldErrorState(self.emailVerificationCode, true);
                verificationCodeInput.focus();
                self.isEmailVerificationSubmitButtonEnabled(true);
                return;
            }

            var dataResponse = OnlineApp.Services
            .emailVerificationService
            .verifyEmail(self.emailVerificationCode(), self.textCaptchaViewModelForVerificationCode.userAnswer(), self.changedEmailAddressWasAdded())
            .done(function (response) {
                var isCaptchaInvalid = false;
                var data = response.data;
            
                if (data.isVerificationSucceeded === true) {   
                    self.isEmailVerified(true);

                    if (self.changedEmailAddressWasAdded()) {
                        self.userEmail(data.changedEmailAddress);
                    }

                    self.showSuccessEmailVerifcationNotification();
                    $(document).trigger(OnlineApp.Events.CommonEventsNames.EmailVerified, { changedEmailAddress: data.changedEmailAddress });
                    gJobs.localStorageHelper.updateItemForMultipleTabs(OnlineApp.LocalStorageKeys.EmailWasVerified, "true");
                } else {
                    var newVerificationAttemptsCount = self.verificationAttemptsCount() + 1;
                    self.verificationAttemptsCount(newVerificationAttemptsCount);

                    if (data.errorFieldName === "captcha") {
                        isCaptchaInvalid = true;
                        self.isEmailVerificationSubmitButtonEnabled(true);
                        updateFieldErrorState(self.textCaptchaViewModelForVerificationCode.userAnswer, true, CAPTCHA_INVALID_MESSAGE);
                    } else {
                        var errorMessage;

                        if (data.errorMessage === "error") {
                            errorMessage = "Invalid verification code";
                        } else if (data.errorMessage === "expired") {
                            errorMessage = "Code is expired. Please resend an email to get a new code";
                        }

                        updateFieldErrorState(self.emailVerificationCode, true, errorMessage);

                        verificationCodeInput.focus();
                    }

                    if (self.isNeedToShowVerificationCodeCaptcha()) {
                        resetCaptcha(
                            self.textCaptchaViewModelForVerificationCode, 
                            CAPTCHA_LABEL_HTML_CONTENT_FOR_VERIFICATION_CODE,
                            CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFY_CODE
                        ).always(function() {
                            if (isCaptchaInvalid) {
                                $("#" + CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFY_CODE).focus();
                            }
                        });
                    }
                }
            });
        }

        self.updateVerificationCodeFormAfterEmailChange = function() {
            self.isEmailVerified(false);
            self.emailVerificationCode('');
        };

        window.onstorage = function (e) {
            if (e.key === OnlineApp.LocalStorageKeys.EmailWasChanged && e.newValue === "true") {
                self.initUserData();
            } else if (e.key === OnlineApp.LocalStorageKeys.EmailWasChangedAndNewVerificationCodeSent && e.newValue === "true") {
                emailWasChangedAndNewVerificationCodeSent = true;
            } else if (e.key === OnlineApp.LocalStorageKeys.EmailWasVerified && e.newValue === "true") {
                self.isEmailVerified(true);
                self.isNeedToShowEmailVerificationForm(false);
            }
        };

        $(window).focus(function () {
            var isEmailVerificationContainerVisible = $("#verify-email-container").is(":visible");
            
            if (emailWasChangedAndNewVerificationCodeSent) {
                if (isEmailVerificationContainerVisible) {
                    OnlineApp.Services.emailVerificationService.trySendEmailVerificationCode();
                }

                self.updateVerificationCodeFormAfterEmailChange();
                emailWasChangedAndNewVerificationCodeSent = false;
            }

            if (self.isNeedToShowVerificationCodeCaptcha()) {
                resetCaptcha(
                    self.textCaptchaViewModelForVerificationCode, 
                    CAPTCHA_LABEL_HTML_CONTENT_FOR_VERIFICATION_CODE,
                    CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFY_CODE
                ).always(function () {
                    tryFocusOnErrorCaptcha(isEmailVerificationContainerVisible, CAPTCHA_USER_ANSWER_INPUT_ID_FOR_VERIFY_CODE);
                });
            }

            if (self.isNeedToShowResendVerificationCodeCaptcha()) {
                resetCaptcha(
                    self.textCaptchaViewModelForResendCode, 
                    CAPTCHA_LABEL_HTML_CONTENT_FOR_RESEND_CODE,
                    CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE
                ).always(function () {
                    tryFocusOnErrorCaptcha(isEmailVerificationContainerVisible, CAPTCHA_USER_ANSWER_INPUT_ID_FOR_RESEND_CODE);
                });
            }
        });

        $(window).blur(function () {
            lastFocusableElement = $(document.activeElement);
        });
        
        $(document).on(OnlineApp.Events.CommonEventsNames.CertifySubmitTabOpened, function () {
            self.init();
        });

        $(document).on(OnlineApp.Events.CommonEventsNames.EmailWasChanged, function (event, data) {
            self.initUserData(data);
        });
    }

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        EmailVerificationViewModel: EmailVerificationViewModel
    });

})(window);
;
var editJobAlertIndex;
(function (window, undefined) {
    'use strict';

    var ARIA_LIVE_NOTIFICATION_CONTAINER = $("#aria-live-message-container");

    var $jobAlertPopup = $('#job-alert-out-container');
    var $deleteJobAlertPopup = $('#job-alert-preference-dialog')
    var $jobAlertAuthorizationPopup = $('#job-alert-authorization-popup');
    var $jobAlertAccessMembershipPopup = $('#job-alert-access-membership-popup');
    var $jobAlertShadow = $('#job-alert-shadow');
    var $headerShadow = $('#header-shadow');
    var $jobAlertPreferences = $('#job-alert-preferences-container');
    var $jobAlertEditView = $('#job-alert-sidebar-container');
    var $searchFormView = $('#search-form');
    var $stickyHeader = $('#sticky-header');
    var $setJobAlertBtn = $('#set-job-alert');    
    var isExistingJobAlert = false;

    var jobAlertIndex;
    var jobAlertLocationAutocompleteMenuClassName = 'job-alert-location-autocomplete-menu';
    var jobAlertKeywordAutocompleteMenuClassName = 'job-alert-keyword-autocomplete-menu';
    var jobAlertSearchFieldSelector = '#job-alert-location-search-input';
    var jobAlertKeywordSearchFieldSelector = '#job-alert-keyword-search-input';
    var displayJobAlertsLoginPopupQueryParameter = "displayJobAlertsLoginPopup";
    var facetGroupNameDataAttribute = "facet-group-name";
    var facetFilterNameDataAttribute = "facet-filter-name";
    var facetGroupNames = {
        datePosted: "Date Posted",
        remote: "Remote",
        jobType: "Job Type",
        organizations: "Top Organizations",
        categories: "Top Categories",
        salary: "Salary Estimate"
    };

    var initialLocation;
    var selectedOrganization;
    var selectedCategory;
    var selectedSalary;
    var selectedRemoteWorkOptionId;
    var selectedJobType;

    const gJobsSite = 0;
    const sJobsSite = 1;
    
    function JobAlertsViewModel() {
        //var self = this;
        var config = {
            endpoint: "jobAlertsPreferences"
        };
        var self = OnlineApp.ViewModels.Base.EditableViewModel.call(this, config) || this;

        self.jobAlerts = ko.observableArray([]);
        self.jobAlertsGJobs = ko.observableArray([]);
        self.jobAlertsSJobs = ko.observableArray([]);
        self.jobAlertPreference = ko.observable();
        self.isInEditMode = ko.observable(false);
        self.jobAlertsIsEmpty = ko.observable(false);
        self.jobAlertsGJobsIsEmpty = ko.observable(false);
        self.jobAlertsSJobsIsEmpty = ko.observable(false);
        self.frequencyPreference = ko.observable();
        self.selectedJobAlert = ko.observable();
        self.selectedFrequency = ko.observable();
        self.isInDeleteMode = ko.observable(false);
        self.isAccessMembershipEnabled = ko.observable(false);
        self.isJobAlertsEnabled = ko.observable(false);
        self.isLoggedIn = ko.observable(false);
        self.jobSeekerId = ko.observable(0);

        self.initialToggleValue = ko.observable();
        self.initialFrequencyValue = ko.observable();

        self.isJobAlertsEnabled.subscribe(function (value) {

            if (self.initialToggleValue() == null && value !== null) {
                self.initialToggleValue(value);
            }

            self.isJobAlertsEnabled(value);
            var jobAlertNotification = "Job Alert is " +
                (value ? "active" : "inactive");

            gJobs.screenReadersService.setAriaLiveNotification(jobAlertNotification);
        });

        self.showHideAriaLabel = function () {
            if ($("fieldset.radio-set.css3-radio").length > 0) {
                $("fieldset.radio-set.css3-radio").each(function (i) {
                    $("fieldset.radio-set.css3-radio")[i].removeAttribute("aria-required");
                });
            }
        }

        OnlineApp.Services.authenticationService.isLoggedIn()
            .done(function (isLoggedIn) {
                self.isLoggedIn(isLoggedIn);

                if (self.isLoggedIn()) {
                    OnlineApp.Services.jobAlertService.getAll().then(function (data) {
                        data.jobAlerts.sort(function (a, b) {
                            return a.SiteSource - b.SiteSource;
                        });
                        data.jobAlerts.forEach(function (value, i) {
                            value.Index = i;
                        })
                        self.jobAlerts(data.jobAlerts);
                        self.jobAlertsGJobs(data.jobAlerts.filter(function (jobAlertElement) {
                            return jobAlertElement.SiteSource == gJobsSite;
                        }));
                        self.jobAlertsSJobs(data.jobAlerts.filter(function (jobAlertElement) {
                            return jobAlertElement.SiteSource == sJobsSite;
                        }));

                        self.jobAlertsGJobsIsEmpty(data.jobAlerts.filter(function (g) { var countGJobs = 0; if (g.SiteSource == gJobsSite) { countGJobs++; } return countGJobs; }).length == 0);
                        self.jobAlertsSJobsIsEmpty(data.jobAlerts.filter(function (s) { var countSJobs = 0; if (s.SiteSource == sJobsSite) { countSJobs++; } return countSJobs; }).length == 0);
                        
                        self.jobAlertsIsEmpty(data.jobAlerts.length == 0);
                        
                        self.jobAlertPreference(data.jobAlertPreference);
                        self.jobSeekerId(data.jobAlertPreference.JobSeekerId);
                        self.isJobAlertsEnabled(data.jobAlertPreference.IsJobAlertEnabled);
                        self.frequencyPreference(data.jobAlertPreference.SentJobAlertsFrequency.toString());
                        self.isAccessMembershipEnabled(data.isAccessMembershipEnabled);
                    })
                }
            });



        self.isInEditMode.subscribe(function (value) {
            var $jobAlertsPreferencesTab = $('.job-alerts-preferences-tab');
            var nonEditModeClassName = 'non-edit-mode';

            if (value) {
                $jobAlertsPreferencesTab.removeClass(nonEditModeClassName);
            } else {
                $jobAlertsPreferencesTab.addClass(nonEditModeClassName);
            }
        });

        self.radioButtonOptions = ko.observable({
            frequencyPreference: [
                {
                    value: '0',
                    id: 'job-alert-frequency-preference-weekly',
                    name: 'ci-radioSet-notify',
                    label: 'Weekly'
                },
                {
                    value: '1',
                    id: 'job-alert-frequency-preference-daily',
                    name: 'ci-radioSet-notify',
                    label: 'Daily'
                }
            ]
        }).extend({ ignoreOnSerialization: true });

        self.frequencyPreference.subscribe(function (value) {
            if (!self.initialFrequencyValue()) {
                self.initialFrequencyValue(self.frequencyPreference())
            }
            self.frequencyPreference(value.toString());
        });

        self.saveChanges = function (item) {
            var frequency = self.frequencyPreference();
            var isJobAlertsEnabled = self.isJobAlertsEnabled();
            OnlineApp.Services.jobAlertService.updateJobAlertPreferences(frequency, isJobAlertsEnabled)
                .then(function (data) {
                    self.jobAlertPreference(data.jobAlertPreference);
                    self.initialToggleValue(isJobAlertsEnabled);
                    self.initialFrequencyValue(frequency);
                    self.endEdit(item);
                    self.focusEditButton(true);

                    OnlineApp.Helpers.layoutHelper.tabbing.updateIndices('.job-alerts-list');
                })
        }

        self.discardChanges = function (item) {
            self.frequencyPreference(self.initialFrequencyValue().toString());
            self.isJobAlertsEnabled(self.initialToggleValue());

            gJobs.screenReadersService.setAriaLiveNotification("Job Alert is " + (self.initialToggleValue() ? "active" : "inactive"));

            self.endEdit(item);
            self.focusEditButton();
        }

        self.focusEditButton = function (saved) {
            var $editableItemContainer = $('#job-alerts-preferences');
            var $editButton = $editableItemContainer.find('.item-edit-button');

            if (saved) {
                gJobs.screenReadersService.setAriaLiveNotification("Job Alert Preferences has been saved.");
                ARIA_LIVE_NOTIFICATION_CONTAINER.focus();
            }

            $editButton.focus();
        }

        self.beginEdit = function (item) {
            var editableItem = item.clone();

            item.isInEditMode(true);
            editableItem.isInEditMode(true);

            self.editableItem(editableItem);
            OnlineApp.Helpers.layoutHelper.tabbing.updateIndices('.job-alerts-list');
            $('#job-alerts-preferences').find(':focusable').first().focus();
        }

        self.fromDataModel = function (data) {
            if (!data) {
                return;
            }

            self.isJobAlertsEnabled(data.isJobAlertsEnabled);
        };

        self.openDeleteJobAlertDialog = function (jobAlert) {
            jobAlert.JobSeekerId = self.jobSeekerId();
            self.selectedJobAlert(jobAlert);
            showHideElementsOnDialog(false);
            gJobs.dialogHelper.disableTabIndexOnParentView();
            self.isInDeleteMode(true);
            showHideDeleteJobAlertPopup(true);
            hideScrollBar('html');

            jobAlertIndex = jobAlert.Index;
            gJobs.dialogHelper.setTabIndexOnJobAlertsPopup("#job-alert-preference-dialog");
            focusOnFistTabbableDialogElement($('.job-alert-preference-dialog'));
        };

        self.closeDeleteJobAlertDialog = function () {
            gJobs.screenReadersService.setAriaLiveNotification("Delete Job Alert modal is closed.");
            ARIA_LIVE_NOTIFICATION_CONTAINER.focus();

            self.isInDeleteMode(false);
            $jobAlertPreferences.addClass("hidden");
            showScrollBar('html');
            showHideDeleteJobAlertPopup(false);
            showHideElementsOnDialog(false);
            focusOnDeleteButton(jobAlertIndex);
        };

        self.deleteJobAlert = function () {
            var jobAlert = self.selectedJobAlert();
            jobAlert.JobSeekerId = self.jobSeekerId();
            var disableJobAlert = self.jobAlerts().length === 1;
            OnlineApp.Services.jobAlertService.deleteJobAlert(jobAlert.JobAlertId, disableJobAlert, jobAlert.JobSeekerId)
                .done(function (response) {
                    showHideElementsOnDialog(false);
                    gJobs.screenReadersService.setAriaLiveNotification("Job Alert was deleted.");
                    ARIA_LIVE_NOTIFICATION_CONTAINER.focus();

                    self.isInDeleteMode(false);
                    self.jobAlerts.remove(jobAlert);
                    if (jobAlert.SiteSource == gJobsSite) {
                        self.jobAlertsGJobs.remove(jobAlert);
                    }
                    if (jobAlert.SiteSource == sJobsSite) {
                        self.jobAlertsSJobs.remove(jobAlert);
                    }
                    showScrollBar('html');

                    if (disableJobAlert) {
                        self.isInEditMode(false);
                        self.jobAlertsIsEmpty(true);
                        self.jobAlertsGJobsIsEmpty(true);
                        self.jobAlertsSJobsIsEmpty(true);
                        self.isJobAlertsEnabled(false);
                    }
                    gJobs.dialogHelper.setTabIndexOnJobAlertsPopup("#setJobAlertDialog");
                    focusOnFistTabbableDialogElement($('.job-alerts-list'));
                    $headerShadow.addClass('hidden');
                })
        };

        self.editJobAlert = function (jobAlert) {
            jobAlertIndex = jobAlert.Index;
            editJobAlertIndex = jobAlert.Index;
            OnlineApp.Services.jobAlertService.getJobAlertEditModel(jobAlert)
                .done(function (response) {
                    $jobAlertEditView.html(response.data);
                    $searchFormView.html(response.searchForm);
                    window.isJobAlertEdit = true;
                    gJobs.screenReadersService.setAriaLiveNotification("Edit Job Alert flyout is openned.");
                    ARIA_LIVE_NOTIFICATION_CONTAINER.focus();
                    $jobAlertEditView.removeClass("hidden");
                    $jobAlertEditView.css({ height: window.innerHeight-95 });
                    hideScrollBar('html');
                    $('#skip-to-content-button').focus();
                    $("#account-settings").attr('aria-hidden', true);
                    $("#account-settings").attr('visible', false);
                    var $tabbableElements;
                    $tabbableElements = $('#account-settings')
                        .find(':tabbable');
                    $tabbableElements.attr('tabindex', -1);
                    $("#footer-new").hide();
                    $("#sjobs-footer-new").hide();
                })
        };

        $(document)
            .on(Events.CommonEventsNames.JobAlertUpdated, function () {
                OnlineApp.Services.jobAlertService.getAll().then(function (data) {
                    data.jobAlerts.sort(function (a, b) {
                        return a.SiteSource - b.SiteSource;
                    });
                    data.jobAlerts.forEach(function (value, i) {
                        value.Index = i;
                    })
                    self.jobAlerts(data.jobAlerts);
                    self.jobAlertsGJobs(data.jobAlerts.filter(function (jobAlertElement) {
                        return jobAlertElement.SiteSource == 0;
                    }));
                    self.jobAlertsSJobs(data.jobAlerts.filter(function (jobAlertElement) {
                        return jobAlertElement.SiteSource == 1;
                    }));
                    OnlineApp.Helpers.layoutHelper.tabbing.updateIndices('.job-alerts-list');
                })
            })
            .on(Events.CommonEventsNames.AccessMembershipDisabled, function (event, data) {
                self.isAccessMembershipEnabled(false);
                self.isJobAlertsEnabled(false);
                self.initialToggleValue(false);
                self.isInEditMode(false);
            })
            .on(Events.CommonEventsNames.AccessMembershipEnabled, function (event, data) {
                self.isAccessMembershipEnabled(true);
                self.isInEditMode(false);
            })
            .on(Events.CommonEventsNames.Login + " " + Events.CommonEventsNames.Register, function (event, data) {
                OnlineApp.Services.jobAlertService.getAll().then(function (data) {
                    data.jobAlerts.sort(function (a, b) {
                        return a.SiteSource - b.SiteSource;
                    });
                    data.jobAlerts.forEach(function (value, i) {
                        value.Index = i;
                    })
                    self.jobAlerts(data.jobAlerts);
                    self.jobAlertsGJobs(data.jobAlerts.filter(function (jobAlertElement) {
                        return jobAlertElement.SiteSource == gJobsSite;
                    }));
                    self.jobAlertsSJobs(data.jobAlerts.filter(function (jobAlertElement) {
                        return jobAlertElement.SiteSource == sJobsSite;
                    }));

                    self.jobAlertsGJobsIsEmpty(data.jobAlerts.filter(function (g) { var countGJobs = 0; if (g.SiteSource == gJobsSite) { countGJobs++; } return countGJobs; }).length == 0);
                    self.jobAlertsSJobsIsEmpty(data.jobAlerts.filter(function (s) { var countSJobs = 0; if (s.SiteSource == sJobsSite) { countSJobs++; } return countSJobs; }).length == 0);
                    
                    self.jobAlertsIsEmpty(data.jobAlerts.length == 0);
                    
                    self.jobAlertPreference(data.jobAlertPreference);
                    self.isJobAlertsEnabled(data.jobAlertPreference.IsJobAlertEnabled);
                    self.frequencyPreference(data.jobAlertPreference.SentJobAlertsFrequency.toString());
                    self.isAccessMembershipEnabled(data.isAccessMembershipEnabled);
                    $stickyHeader.hide();
                })
            })
    }

    $(document).ready(function () {
        var showJobAlertPopup = sessionStorage.getItem(OnlineApp.LocalStorageKeys.ShowJobAlertPopup);        
        if (showJobAlertPopup === 'true') {
            sessionStorage.setItem(OnlineApp.LocalStorageKeys.ShowJobAlertPopup, "false");
            sessionStorage.setItem(OnlineApp.LocalStorageKeys.RedirectToShowJobAlertPopup, "false");

            OnlineApp.Services.jobAlertService.isJobAlertCanBeCreated(OnlineApp.Helpers.Url.getJsonFromUrl(location.search))
                .done(function () {
                    showHideJobAlertPopup(true);
                });

        }
    })    

    $(document).keydown(function (e) {
        if (e.keyCode == $.ui.keyCode.ESCAPE) {
            var elementsToExclude = getListOfElmentsToBeExcluded();
            if (elementsToExclude.includes(e.target.id)) {
                return;
            }

            if (e.target.id != 'gmapLink' && $(e.target).attr('data-toggle') != 'popover') {
                if ($(e.target).hasClass('things-to-consider-popover-trigger')
                    || $(e.target).hasClass('st-custom-button')
                    || $(e.target).hasClass('job-details-location-icon')
                    || $(e.target).hasClass('job-details-salary-icon')
                    || $(e.target).hasClass('inbox-header-id')
                    || $(e.target).hasClass('flag-left')
                    || $(e.target).hasClass('doNotSellMyPersonalInformationDialogCloseButton')) return;
                if ($('.job-alert-preferences').length && !$('.job-alert-preferences').is(':visible') && $jobAlertEditView.length && $jobAlertEditView.hasClass('hidden') && !isExistingJobAlert) return;
                var deleteModeWasActive = $('.job-alert-preferences').length && $('.job-alert-preferences').is(':visible');
                $jobAlertAuthorizationPopup.addClass('hidden');
                var closeJobAlertButton = document.getElementById("close-job-alert");
                var closeJobAlertOkButton = document.getElementById("close-job-alert-ok-button");
                var closeJobAlertDeleteButton = document.getElementById("close-job-alert-delete");

                var closeAccessMembershipAlert = document.getElementById("close-access-membership-alert");
                if (typeof (closeAccessMembershipAlert) != 'undefined' && closeAccessMembershipAlert != null) {
                    closeAccessMembershipAlert.click();
                }

                if (typeof (closeJobAlertButton) != 'undefined' && closeJobAlertButton != null) {
                    closeJobAlertButton.click();
                }
                if (typeof (closeJobAlertOkButton) != 'undefined' && closeJobAlertOkButton != null) {
                    closeJobAlertOkButton.click();
                }
                if (typeof (closeJobAlertDeleteButton) != 'undefined' && closeJobAlertDeleteButton != null) {
                    closeJobAlertDeleteButton.click();
                }
                self.closeJobAlert();
                self.closeEditMode();
                if (isExistingJobAlert) { self.showJobAlertEditView(); isExistingJobAlert = false; } else { $setJobAlertBtn.focus(); }
                if (deleteModeWasActive) {
                    var setJobAlertIndex = jobAlertIndex ? jobAlertIndex : 0;
                    focusOnDeleteButton(setJobAlertIndex);
                }
            }
            if ($(e.target).attr('data-toggle') == 'popover') {
                $(e.target).popover('hide');
            }
        } else if (e.keyCode == $.ui.keyCode.ENTER) {
            if (e.target.className === "btn-show-results" || e.target.className === "hidden-facet clearAllFilter") {
                self.showResults();
            }
            else if (e.target.className === "btn-gjobs-secondary") {
                if (e.target.id != "set-job-alert") {
                    self.showResults(e.target.className);
                }
            }
            else if (e.target.className === "facet-link") {
                $(e.target).click();
            }
        }        
    });   

    self.setJobAlert = function () {
        $stickyHeader.hide();
        $('#content').removeClass('respect-sticky-header');
        gJobs.dialogHelper.setTabIndexOnJobAlertsPopup("#setJobAlertDialog");

        if ($('#job-alert-access-membership-popup')[0]) {
            var isAccessMemberShipEnabled = false;
            $(document).on(Events.CommonEventsNames.AccessMembershipEnabled, function () {
                isAccessMemberShipEnabled = true;
            });
            $(document).on(Events.CommonEventsNames.CloseAccessMembershipDialog, function (event) {
                if (isAccessMemberShipEnabled) {
                    $jobAlertAccessMembershipPopup.remove();
                    $('#job-alert-out-container').removeClass('hidden');
                    gJobs.dialogHelper.setTabIndexOnJobAlertsPopup("#setJobAlertDialog");
                }
                else {
                    self.showHideJobAlertAcessMembershipPopup(true, false);
                }
            });
            //Event handler added to prevent displaying both landing accesmembership dialog and job alert accessmembership  popup if page refreshed post set jobalert sign in
            $(document).on(Events.CommonEventsNames.OpenAccessMembershipDialog, function () {
                self.showHideJobAlertAcessMembershipPopup(false, false);
            });
        }

        OnlineApp.Services.authenticationService.isLoggedIn()
            .done(function (isLoggedIn) {
                showHideElementsOnDialog(false);
                gJobs.dialogHelper.disableTabIndexOnParentView();
                hideScrollBar('body');
                hideScrollBar('html');
                if (isLoggedIn) {
                    gJobs.dialogHelper.setTabIndexOnJobAlertsPopup("#setJobAlertDialog");
                    if ($('#job-alert-access-membership-popup')[0]) {
                        self.showHideJobAlertAcessMembershipPopup(true, true);
                        return;
                    }
                    else
                        showHideJobAlertPopup(true);
                }
                else {
                    showHideJobAlertAuthPopup(true);
                    OnlineApp.ViewModels.applicationViewModel.loginViewModel.signInViewModel.showJobAlert(true);
                    OnlineApp.ViewModels.applicationViewModel.loginViewModel.registerViewModel.showJobAlert(true);

                    if (window.enableEmailVerificationRefinements) {
                        if (!window.utils.getUrlParameter(displayJobAlertsLoginPopupQueryParameter)) {
                            var currentUrl = addEmailVerificationParametersToUrl();
                            history.pushState(null, "", currentUrl);
                        }
                    }
                }
                gJobs.screenReadersService.setAriaLiveNotification("Set Job Alert modal is openned.");
                ARIA_LIVE_NOTIFICATION_CONTAINER.focus();
                gJobs.dialogHelper.setTabIndexOnJobAlertsPopup("#jobAlertAuthorizationPopup");
                focusOnFistTabbableDialogElement(isLoggedIn ? $jobAlertPopup : $jobAlertAuthorizationPopup);
                
            });
    }
    self.addJobAlert = function (searchCriteria) {
        $("#add-job-alert").attr("disabled", true);
        OnlineApp.Services.jobAlertService.addJobAlert(searchCriteria)
            .done(function (response) {
                showHideElementsOnDialog(false);
                gJobs.dialogHelper.disableTabIndexOnParentView();
                $('#job-alert-out-container').html(response);
                $(document).trigger(Events.CommonEventsNames.JobAlertCreated);
                gJobs.dialogHelper.setTabIndexOnJobAlertsPopup("#setJobAlertDialog");
            })
    }

    self.updateJobAlert = function (jobAlert) {

        jobAlert.Location = document.getElementById('job-alert-location-search-input').value;
        jobAlert.Keyword = document.getElementById('job-alert-keyword-search-input').value;

        OnlineApp.Services.jobAlertService.updateJobAlert(jobAlert)
            .done(function (response) {
                showHideElementsOnDialog(false);
                gJobs.dialogHelper.disableTabIndexOnParentView();
                var updateResultMessage = "Job Alert is saved. ";
                ARIA_LIVE_NOTIFICATION_CONTAINER.focus();

                if (!response.isSuccessfull) {
                    hideScrollBar('body');
                    $jobAlertPopup.html(response.responseView);
                    gJobs.dialogHelper.disableTabIndexOnParentView();
                    showHideJobAlertPopup(true);
                    jobAlertIndex = 1;
                    isExistingJobAlert = true;
                    updateResultMessage = "Job Alert is not saved. ";
                } else {
                    showScrollBar('html');
                    $(document).trigger(Events.CommonEventsNames.JobAlertUpdated);
                }
                
                $jobAlertEditView.addClass("hidden");
                hideScrollBar('html');
                $("#footer-new").hide();
                $("#skip-to-content-button").hide();
                self.closeEditMode(updateResultMessage);
                gJobs.dialogHelper.setTabIndexOnJobAlertsPopup("#setJobAlertDialog");
                if (!response.isSuccessfull) {
                    window.isJobAlertEdit = true;
                }
            })
    };

    function showHideElementsOnDialog(hide) {
        gJobs.dialogHelper.showHideElementsOnDialog(
            {
                selector: '#body-container, #main-container,'
                    + '#footer, #footer-new, #sjobs-footer-new, .new-job-flyout, #skip-to-content-button,'
                    + '#last-focusable-element, #cookie-consent, #account-settings',
                shouldDisableRestoreTabIndex: true,
                hide: hide
            }
        );
    }

    self.closeEditMode = function (updateResultMessage) {
        window.isJobAlertEdit = false;
        var flyoutCloseMessage = "Edit Job Alert flyout is closed.";
        if (updateResultMessage) flyoutCloseMessage = updateResultMessage + flyoutCloseMessage;
        gJobs.screenReadersService.setAriaLiveNotification(flyoutCloseMessage);
        ARIA_LIVE_NOTIFICATION_CONTAINER.focus();
        showHideElementsOnDialog(false);
        $jobAlertEditView.addClass("hidden");
        showScrollBar('html');
        $("#account-settings").attr('aria-hidden', false);
        var $tabbableElements;
        $tabbableElements = $('#account-settings').find(':tabbable');
        $tabbableElements.attr('tabindex', 0);
        $("#footer-new").show();
        $("#sjobs-footer-new").show();
        $("#skip-to-content-button").show();
        gJobs.dialogHelper.setTabIndexOnJobAlertsPopup("#setJobAlertDialog");
        focusOnEditButton(jobAlertIndex);
    }

    self.keyDown = function (jobAlert, event) {
        if (event.keyCode == 13) {
            changeJobAlert(jobAlert,event);
        }
    }

    self.getJobAlertFilterChangePrefix = function (jobAlertFilter, facetFilterValue) {
        var filterIsAppliedPrefix = " filter is applied";
        var filterIsRemovedPrefix = " filter is removed";

        return jobAlertFilter === facetFilterValue
            ? filterIsAppliedPrefix
            : filterIsRemovedPrefix;
    }

    self.getJobAlertChangeMessage = function (jobAlert, event) {
        var facetFilterValue = $(event.target).data(facetFilterNameDataAttribute);
        var facetGroupValue = $(event.target).data(facetGroupNameDataAttribute);
 
        var message = facetGroupValue + " , " + facetFilterValue;

        if (facetGroupValue === facetGroupNames.organizations) {
            message += self.getJobAlertFilterChangePrefix(jobAlert.Organization, facetFilterValue);
        } else if (facetGroupValue === facetGroupNames.categories) {
            message += self.getJobAlertFilterChangePrefix(jobAlert.Category, facetFilterValue);
        } else if (facetGroupValue === facetGroupNames.jobType) {
            message += self.getJobAlertFilterChangePrefix(jobAlert.JobType, facetFilterValue);
        } else if (facetGroupValue === facetGroupNames.salary) {
            message += self.getJobAlertFilterChangePrefix("$" + jobAlert.MinimumSalary + "+", facetFilterValue.replace(',',''));
        } else if (facetGroupValue === facetGroupNames.datePosted) {
            message += self.getJobAlertFilterChangePrefix(jobAlert.DaysPosted, facetFilterValue);
        } else if (facetGroupValue === facetGroupNames.remote) {
            message += self.getJobAlertFilterChangePrefix(jobAlert.RemoteOptionsText, facetFilterValue);
        }

        return message;
    }

    self.changeJobAlert = function (jobAlert, event) {
        if (!jobAlert.JobAlertId || jobAlert.JobAlertId === 0) {
            jobAlert.JobAlertId = document.getElementById('job-alert-id').textContent;
        }

        selectedOrganization = null;
        selectedCategory = null;
        selectedJobType = null;

        if (jobAlert.Organization) {
            jobAlert.Organization = jobAlert.Organization[0];
            selectedOrganization = jobAlert.Organization;
        }
        if (jobAlert.Category) {
            jobAlert.Category = jobAlert.Category[0];
            selectedCategory = jobAlert.Category;
        }
        if (jobAlert.JobType) {
            jobAlert.JobType = jobAlert.JobType[0];
            selectedJobType = jobAlert.JobType;
        }
        selectedRemoteWorkOptionId = jobAlert.RemoteWorkOptionId;
        //selectedJobType = jobAlert.JobType;
        selectedSalary = jobAlert.MinimumSalary;
        jobAlert.Location = document.getElementById('job-alert-location-search-input').value;
        jobAlert.Keyword = document.getElementById('job-alert-keyword-search-input').value;
        var screenReaderChangeMessage = "";
        if (event) {
            screenReaderChangeMessage = self.getJobAlertChangeMessage(jobAlert, event);
        }
        OnlineApp.Services.jobAlertService.getAll().then(function (data) {
            data.jobAlerts.sort(function (a, b) {
                return a.SiteSource - b.SiteSource;
            });
            data.jobAlerts.forEach(function (value, i) {
                value.Index = i;
                if (value.JobAlertId == jobAlert.JobAlertId) {
                    jobAlert.SiteSource = value.SiteSource;
                }
            })

            OnlineApp.Services.jobAlertService.getJobAlertEditModel(jobAlert)
                .done(function (response) {
                    $jobAlertEditView.html(response.data);
                    $searchFormView.html(response.searchForm);

                    $jobAlertEditView.removeClass("hidden");
                    $jobAlertEditView.css({ height: window.screen.height - 95 });
                    hideScrollBar('html');
                    document.getElementById('save-job-alert').removeAttribute("disabled");
                    gJobs.screenReadersService.setAriaLiveNotification(screenReaderChangeMessage);                    
                    $("#skip-to-content-button").show();
                    $('#save-job-alert').focus();
                })
        })
    };

    self.clearFilter = function (jobAlert) {
        jobAlert.Location = document.getElementById('job-alert-location-search-input').value;
        jobAlert.Keyword = document.getElementById('job-alert-keyword-search-input').value;
        selectedCategory = null;
        selectedOrganization = null;
        selectedSalary = null;
        selectedRemoteWorkOptionId = 0;
        selectedJobType = null;
        //$("#skip-to-content-button").show();
        $("#skip-to-content-button").focus();
        OnlineApp.Services.jobAlertService.getJobAlertEditModel(jobAlert)
            .done(function (response) {
                var jobAlertId = document.getElementById('job-alert-id').textContent;
                $jobAlertEditView.html(response.data);
                document.getElementById('job-alert-id').textContent = jobAlertId;
                $searchFormView.html(response.searchForm);

                $jobAlertEditView.removeClass("hidden");
                $jobAlertEditView.css({ height: window.screen.height-95 });
                hideScrollBar('html');
                gJobs.screenReadersService.setAriaLiveNotification("Filter are cleared.");
                ARIA_LIVE_NOTIFICATION_CONTAINER.focus();
            })
    }

    self.clearFilterOnKeyDown = function (jobAlert, event) {
        if (event.keyCode == $.ui.keyCode.ENTER) {
            jobAlert.Location = document.getElementById('job-alert-location-search-input').value;
            jobAlert.Keyword = document.getElementById('job-alert-keyword-search-input').value;
            selectedCategory = null;
            selectedOrganization = null;
            selectedSalary = null;
            selectedRemoteWorkOptionId = 0;
            selectedJobType = null;
            //$("#skip-to-content-button").show();
            $("#skip-to-content-button").focus();
            OnlineApp.Services.jobAlertService.getJobAlertEditModel(jobAlert)
                .done(function (response) {
                    var jobAlertId = document.getElementById('job-alert-id').textContent;
                    $jobAlertEditView.html(response.data);
                    document.getElementById('job-alert-id').textContent = jobAlertId;
                    $searchFormView.html(response.searchForm);

                    $jobAlertEditView.removeClass("hidden");
                    $jobAlertEditView.css({ height: window.screen.height-95 });
                    hideScrollBar('html');
                    gJobs.screenReadersService.setAriaLiveNotification("Filter are cleared.");
                    ARIA_LIVE_NOTIFICATION_CONTAINER.focus();
                })
        }
    }

    self.blurInputs = function () {
        $('#job-alert-keyword-search-input').blur();
        $('#job-alert-location-search-input').blur();
    }

    self.anounceTooltip = function () {
        var isDisabled = document.getElementById('save-job-alert').disabled;
        if (isDisabled) {
            gJobs.screenReadersService.setAriaLiveNotification('To set a job alert, you must select/apply at least one filter. To apply a filter, click on the “Show results” button.');
            ARIA_LIVE_NOTIFICATION_CONTAINER.focus();
        }
    }

    self.disableSaveButton = function (e) {
        if (initialLocation === undefined) {
            initialLocation = document.getElementById('job-alert-location-search-input').value;
        }
        if (e.keyCode !== $.ui.keyCode.TAB && !e.shiftKey) {
            document.getElementById('save-job-alert').setAttribute("disabled", "disabled");
        }
    }

    self.jobAlertLocationFieldAfterRender = function () {
        var initOptions = {
            autocompleteMenuClassName: jobAlertLocationAutocompleteMenuClassName
        };

        var options = {
            searchFieldSelectors: [jobAlertSearchFieldSelector],
            additionalCssClassNames: initOptions.autocompleteMenuClassName
        };

        $(document).trigger(OnlineApp.Events.CommonEventsNames.InitSearchFieldsWithAutocomplete, options);

    };

    self.jobAlertKeywordFieldAfterRender = function () {
        var initOptions = {
            autocompleteMenuClassName: jobAlertKeywordAutocompleteMenuClassName
        };

        var options = {
            searchFieldSelectors: [jobAlertKeywordSearchFieldSelector],
            additionalCssClassNames: initOptions.autocompleteMenuClassName
        };

        $(document).trigger(OnlineApp.Events.CommonEventsNames.InitSearchFieldsWithAutocomplete, options);
    }

    self.showResults = function (className) {
        var jobAlert = [];
        jobAlert.Location = document.getElementById('job-alert-location-search-input').value;
        jobAlert.Keyword = document.getElementById('job-alert-keyword-search-input').value;
        jobAlert.JobAlertId = document.getElementById('job-alert-id').textContent;
        jobAlert.Organization = selectedOrganization;
        jobAlert.Category = selectedCategory;
        jobAlert.MinimumSalary = selectedSalary;
        jobAlert.RemoteWorkOptionId = selectedRemoteWorkOptionId;
        jobAlert.JobType = selectedJobType;

        OnlineApp.Services.jobAlertService.updateJobAlertEditModel(jobAlert)
            .done(function (response) {
                var jobAlertId = document.getElementById('job-alert-id').textContent;
                $jobAlertEditView.html(response.data);
                document.getElementById('job-alert-id').textContent = jobAlertId;
                $searchFormView.html(response.searchForm);

                $jobAlertEditView.removeClass("hidden");
                $jobAlertEditView.css({ height: window.screen.height-95 });
                hideScrollBar('html');
                document.getElementById('save-job-alert').removeAttribute("disabled");
                gJobs.screenReadersService.setAriaLiveNotification("New results are uploaded.");
                $("#skip-to-content-button").show();
                gJobs.screenReadersService.silenceScreenreaderForBanner("");
                if (className == "btn-gjobs-secondary") {
                    setFocusOnEditJobAlert(editJobAlertIndex);
                }
            })
    }
    
    self.toggleModels = function () {
        var loginModel = OnlineApp.ViewModels.applicationViewModel.loginViewModel;
        loginModel.signInViewModel.isActive(!loginModel.signInViewModel.isActive());
        loginModel.registerViewModel.isActive(!loginModel.registerViewModel.isActive());
    }

    self.closeAccessMembershipAlert = function () {
        if (window.enableStickyHeader) {
            $stickyHeader.show();
            $('#content').addClass('respect-sticky-header');
        }

        showHideElementsOnDialog(false);       

        self.showHideJobAlertAcessMembershipPopup(false, true);
        showScrollBar('html');
        $setJobAlertBtn.focus();
        checkAndRemoveEmailVerificationParam();
    }
    self.closeJobAlertOnKeydown = function (event) {
        if (event.keyCode == 13) {
            setTimeout(function () {
                var closeJobAlertButton = document.getElementById("close-job-alert");
                closeJobAlertButton.click();
            },200);
        }
    }
    self.closeJobAlert = function (isAuthorizationPopup, isAddedSuccessfully, showEditPageBack) {
        if (window.enableStickyHeader) {
            if (!($jobAlertAccessMembershipPopup[0] && !$('#job-alert-access-membership-popup')[0])){
                $stickyHeader.show();
                $('#content').addClass('respect-sticky-header');
            }
        }

        showHideElementsOnDialog(false);

        gJobs.screenReadersService.setAriaLiveNotification("Set Job Alert modal is closed.");
        ARIA_LIVE_NOTIFICATION_CONTAINER.focus();

        OnlineApp.ViewModels.applicationViewModel.loginViewModel.signInViewModel.showJobAlert(false);
        OnlineApp.ViewModels.applicationViewModel.loginViewModel.registerViewModel.showJobAlert(false);

        if (isAuthorizationPopup) {
            showHideJobAlertAuthPopup(false);
            showScrollBar('html');
        }        
        else {
            showHideJobAlertPopup(false);
            if (showEditPageBack) {
                $jobAlertEditView.removeClass("hidden");
                var $tabbableElements;

                $tabbableElements = $('#account-settings')
                    .find(':tabbable');
                $tabbableElements.attr('tabindex', -1);
                $(".close-job-alert-edit-mode").attr('tabindex', 0);
                $("#job-alert-keyword-search-input").attr('tabindex', 0);
                $("#job-alert-location-search-input").attr('tabindex', 0);
                $("#show-results").attr('tabindex', 0);
                $("#save-job-alert").attr('tabindex', 0);
                $tabbableElements = $('#header-content')
                    .find(':tabbable');
                $tabbableElements.attr('tabindex', 0);
                $("#footer-new").hide();
                $tabbableElements = $jobAlertEditView
                    .find(':tabbable');
                $tabbableElements.attr('tabindex', 0);
                $("#footer-new").hide();
                $tabbableElements = $("#facet-container")
                    .find('a');
                $tabbableElements.attr('tabindex', 0);
                $('#save-job-alert').focus();
                $("#footer-new").hide();
                $stickyHeader.hide();
            }
            else {
                showScrollBar('html');
            }
        }

        if (isAddedSuccessfully) {
            OnlineApp.Services.jobAlertService.generateJobAlertAlreadyAddedView()
                .done(function (response) {
                    $('#job-alert-out-container').html(response);
                });
        }

        $setJobAlertBtn.focus();
        gJobs.dialogHelper.setTabIndexOnJobAlertsPopup("#setJobAlertDialog");

        checkAndRemoveEmailVerificationParam();        
    }

    function checkAndRemoveEmailVerificationParam() {
        if (window.enableEmailVerificationRefinements) {
            if (window.utils.getUrlParameter(displayJobAlertsLoginPopupQueryParameter)) {
                var currentUrl = removeEmailVerificationParametersFromUrl();
                history.pushState(null, "", currentUrl);
            }
        }
    }

    self.showJobAlertEditView = function () {
        $jobAlertEditView.removeClass("hidden");
        var $tabbableElements;
        $tabbableElements = $('#account-settings')
            .find(':tabbable');
        $tabbableElements.attr('tabindex', -1);
        $(".close-job-alert-edit-mode").attr('tabindex', 0);
        $("#job-alert-keyword-search-input").attr('tabindex', 0);
        $("#job-alert-location-search-input").attr('tabindex', 0);
        $("#show-results").attr('tabindex', 0);
        $("#save-job-alert").attr('tabindex', 0);
        $tabbableElements = $('#header-content')
            .find(':tabbable');
        $tabbableElements.attr('tabindex', 0);
        $tabbableElements = $jobAlertEditView
            .find(':tabbable');
        $tabbableElements.attr('tabindex', 0);
        $tabbableElements = $("#facet-container")
            .find('a');
        $tabbableElements.attr('tabindex', 0);
        hideScrollBar('html');
        $("#footer-new").hide();
        $('#save-job-alert').focus();
    }

    self.isAuthorized = ko.observable(false);

    self.loginLoaded = function () {
        $(document).trigger('JobAlertsViewModel:ViewLoaded');
    };

    self.goToAccountSettingsPage = function () {
        var accountSettingsPagePath = gJobs.accountSettingsHelper.getLinkForAccountSettings();

        window.open(accountSettingsPagePath, '_blank');
    };

    self.enrollAcessMembership = function () {
        OnlineApp.Services.dataService.accessMembership.post({
            wantsToUpgrade: true,
            credential: null
        }).done(function (data) {
            gJobs.common.analytics.trackEvent(
                'Access Membership Page',
                'Upgraded'
            );

            $jobAlertAccessMembershipPopup.remove();
            gJobs.screenReadersService.setAriaLiveNotification("Access Membership Enrolled and Set Job Alert modal is opened.");
            ARIA_LIVE_NOTIFICATION_CONTAINER.focus();
            $('#job-alert-out-container').removeClass('hidden');
            gJobs.dialogHelper.setTabIndexOnJobAlertsPopup("#setJobAlertDialog");
        });
    };

    self.showHideJobAlertAcessMembershipPopup = function (show, showShadow) {
        hideScrollBar('body');
        hideScrollBar('html');
        if (show) {
            $jobAlertAccessMembershipPopup.removeClass('hidden');
            if (showShadow) {
                $jobAlertShadow.removeClass('hidden');
                $headerShadow.removeClass('hidden');
            }
            gJobs.screenReadersService.setAriaLiveNotification("Enroll in Free Access Membership modal is opened.");
            ARIA_LIVE_NOTIFICATION_CONTAINER.focus();
            gJobs.dialogHelper.setTabIndexOnJobAlertsPopup('#job-alert-access-membership-popup');
            focusOnFistTabbableDialogElement($jobAlertAccessMembershipPopup);

        } else {
            $jobAlertAccessMembershipPopup.addClass('hidden');
            if (showShadow) {
                $jobAlertShadow.addClass('hidden');
                $headerShadow.addClass('hidden');
            }
            gJobs.screenReadersService.setAriaLiveNotification("Enroll in Free Access Membership modal is closed.");
            ARIA_LIVE_NOTIFICATION_CONTAINER.focus();
        }
    };

    function hideScrollBar(element) {
        $(element).css({ 'overflow': 'hidden' });
    }

    function showScrollBar(element) {
        $(element).css({ 'overflow-y': 'scroll' });
    }

    function focusOnFistTabbableDialogElement(element) {
        element.find(":tabbable").first().focus();
    }

    function focusOnEditButton(index) {
        if (index == undefined) {
            if (!$('.job-alert-edit-btn')[0]) return;
            $('.job-alert-edit-btn')[0].focus();
            setTimeout(function () { $('.job-alert-edit-btn')[0].focus(); }, 1500);
        }
        else {
            $('#skip-to-content-button').show();
            $('.job-alert-edit-btn')[index].focus();
            setTimeout(function () { $('.job-alert-edit-btn')[index].focus(); }, 1500);
        }
    }

    function setFocusOnEditJobAlert(i) {
        showHideElementsOnDialog(false);
        $jobAlertEditView.addClass("hidden");
        showScrollBar('html');
        $("#account-settings").attr('aria-hidden', false);
        var $tabbableElements;
        $tabbableElements = $('#account-settings').find(':tabbable');
        $tabbableElements.attr('tabindex', 0);
        $("#footer-new").show();
        $("#skip-to-content-button").show();
        if ($('.job-alert-edit-btn').length > 0) {
            $('.job-alert-edit-btn')[i].focus();
            setTimeout(function () { $('.job-alert-edit-btn')[i].focus(); }, 1500);
        }
    }

    function focusOnDeleteButton(index) {
        if (index !== undefined) {
            $('.job-alert-delete-btn')[index].focus();
        }
    }

    function showHideDeleteJobAlertPopup(show) {
        if (show) {
            $jobAlertShadow.removeClass('hidden');
            $deleteJobAlertPopup.removeClass('hidden');
            $headerShadow.removeClass('hidden');
        } else {
            $jobAlertShadow.addClass('hidden');
            $deleteJobAlertPopup.addClass('hidden');
            $headerShadow.addClass('hidden');
        }
    }

    function showHideJobAlertPopup(show) {
        if (show) {
            $jobAlertShadow.removeClass('hidden');
            $jobAlertPopup.removeClass('hidden');
            $headerShadow.removeClass('hidden');
        } else {
            $jobAlertShadow.addClass('hidden');
            $jobAlertPopup.addClass('hidden');
            $headerShadow.addClass('hidden');
        }
    }

    function showHideJobAlertAuthPopup(show) {
        hideScrollBar('body');
        hideScrollBar('html');
        if (show) {
            $jobAlertAuthorizationPopup.removeClass('hidden');
            $jobAlertShadow.removeClass('hidden');
            $headerShadow.removeClass('hidden');
        } else {
            $jobAlertAuthorizationPopup.addClass('hidden');
            $jobAlertShadow.addClass('hidden');
            $headerShadow.addClass('hidden');
        }
    }    

    function removeEmailVerificationParametersFromUrl() {
        var currentUrl = window.location.href.replace(/&?(displayJobAlertsLoginPopup)=([^&]$|[^&]*)/ig, "");

        return currentUrl;
    }

    function addEmailVerificationParametersToUrl() {
        var currentUrl = window.location.search + "&displayJobAlertsLoginPopup=true";

        return currentUrl;
    }

    $(document).ready(function() {
        if (window.enableEmailVerificationRefinements) {
            if (window.utils.getUrlParameter(displayJobAlertsLoginPopupQueryParameter)) {
                self.setJobAlert();
            }
        }
    });

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        jobAlertsViewModel: JobAlertsViewModel
    });

})(window); ;
(function(window, undefined) {
    'use strict';

    function TwoStepVerificationViewModel() {
        var CONTACT_INFO_TAB_LINK_SELECTOR = '.contact-info-tab-link';
        var SAVE_2FA_BUTTON_SELECTOR = '#two-step-verification-tab .btn-app-primary-save';

        var config = {
            endpoint: 'twoFactorAuthenticationPreferences'
        };

        var self = OnlineApp.ViewModels.Base.EditableViewModel.call(this, config) || this;

        self.isEmailVerified = ko.observable(false).extend({ ignoreOnSerialization: true });

        self.isTwoFactorAuthenticationEnabledInitial = ko.observable(false).extend({ ignoreOnSerialization: true });

        self.isTwoFactorAuthenticationEnabled = ko.observable(false);

        self.isTwoFactorAuthenticationEnabled.subscribe(function(value) {
            $(SAVE_2FA_BUTTON_SELECTOR).prop('disabled', false);
            OnlineApp.Helpers.layoutHelper.tabbing.updateIndices();

            var twoStepVerificationNotification = 'Two step verification is ' +
                (value ? 'active' : 'inactive');

            gJobs.screenReadersService.setAriaLiveNotification(twoStepVerificationNotification);
        });

        self.fromDataModel = function(data) {
            if (!data) {
                return;
            }

            self.isTwoFactorAuthenticationEnabledInitial(data.isTwoFactorAuthenticationEnabled);

            self.isTwoFactorAuthenticationEnabled(data.isTwoFactorAuthenticationEnabled);

            self.isEmailVerified(data.isEmailVerified);
        };

        self.saveChanges = function() {
            gJobs.focusService.setFocusOnEmptyElement(
                $(SAVE_2FA_BUTTON_SELECTOR),
                function() {
                    OnlineApp.Helpers.layoutHelper.tabbing.updateIndices();
                }
            );

            $(SAVE_2FA_BUTTON_SELECTOR).prop('disabled', true);

            self.isTwoFactorAuthenticationEnabledInitial(self.editableItem().isTwoFactorAuthenticationEnabled());

            var agencyFolderName = AgencyPages.pageInfoService
                ? AgencyPages.pageInfoService.getCurrentAgencyFolderName()
                : gJobs.pageInfoService.getCurrentAgencyPageFolderName();

            var viewModelData = self.editableItem().toDataModel();

            self.save(viewModelData, true, false, { agencyFolderName: agencyFolderName })
                .done(function() {
                    if (viewModelData.isTwoFactorAuthenticationEnabled) {
                        toastr.success("2-step verification enabled");
                    }
                    else {
                        var $disableAction = $('#two-step-verification-preferences');
                        OnlineApp.Helpers.layoutHelper.tabbing.updateIndices($disableAction);

                        gJobs.screenReadersService.setNotification($disableAction.find('.sr-notification'), 'Two step verification disabled', null, true);
                    }
                });
        };

        self.discardChanges = function() {
            self.editableItem().isTwoFactorAuthenticationEnabled(self.isTwoFactorAuthenticationEnabledInitial());
            var $cancelAction = $('#two-step-verification-preferences');
            OnlineApp.Helpers.layoutHelper.tabbing.updateIndices($cancelAction);

            gJobs.screenReadersService.setNotification($cancelAction.find('.sr-notification'), 'Changes cancelled successfully', null, true);
        };

        self.navigateToContactInfoTab = function() {
            $(CONTACT_INFO_TAB_LINK_SELECTOR).focus();
            $(CONTACT_INFO_TAB_LINK_SELECTOR).tab('show');
        };

        self.isFormDisabled = function () {
            return !self.isEmailVerified();
        }

        $(document).on(OnlineApp.Events.CommonEventsNames.EmailVerified, function(event) {
            self.isEmailVerified(true);
        });

        $(document).on(OnlineApp.Events.CommonEventsNames.EmailWasChanged, function(event, data) {
            if (data && data.changedEmailAddressWasAdded && data.isEmailChanged) return;

            self.isEmailVerified(false);

            if (self.editableItem()) {
                self.editableItem().isTwoFactorAuthenticationEnabled(false);
                self.saveChanges();
            }
        });
    }

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        TwoStepVerificationViewModel: TwoStepVerificationViewModel
    });

})(window);
;
(function (window, undefined) {
    'use strict';

    function AccountSettingsViewModel() {
        var self = OnlineApp.ViewModels.Base.CompositeEditableViewModel.apply(this, arguments) || this;

        self.navigationController = OnlineApp.Controllers.navigationController;

        self.showAuthorizedContent = ko.observable(false);
        self.isHtmlTemplateLoaded = ko.observable(false);

        self.showChangePasswordTab = ko.observable(false);
        self.showEmailPreferencesTab = ko.observable(false);
        self.showTextMessagingPreferencesTab = ko.observable(false);
        self.showPreferencesTab = ko.observable(false);
        self.showTwoStepVerificationTab = ko.observable(window.enableTwoFactorAuthentication);

        self.contactInfo = new OnlineApp.ViewModels.ContactInfoViewModel({ isEmailEditable: true, isEmailVerificationNotificationEnabled: true });
        self.changePasswordViewModel = new OnlineApp.ViewModels.ChangePasswordViewModel();
        self.emailPreferences = new OnlineApp.ViewModels.EmailPreferencesViewModel();
        self.talentSearchPreferences = new OnlineApp.ViewModels.TalentSearchPreferencesViewModel();
        self.textMessagingPreferences = new OnlineApp.ViewModels.TextMessagingPreferencesViewModel();
        self.twoStepVerificationViewModel = new OnlineApp.ViewModels.TwoStepVerificationViewModel();
        self.jobAlertsPreferencesViewModel = new OnlineApp.ViewModels.jobAlertsViewModel();

        self.isImpersonatedJobSeeker = false;
        self.isJobAlertsEnabled = ko.observable(false);

        OnlineApp.Services.jobAlertService.isJobAlertsEnabled()
            .then(function (data) {
                var currentArea = gJobs.areaInfoService.getCurrentArea();
                var isAgencyPages = currentArea === gJobs.areaInfoService.areaNames.Agency;
                self.isJobAlertsEnabled(data.isJobAlertsEnabled && !isAgencyPages);
            })

        self.addParts([
            self.contactInfo,
            self.changePasswordViewModel,
            self.talentSearchPreferences,
            self.textMessagingPreferences
        ]);

        self.isInEditMode.subscribe(function(newValue) {
            if (($(document.documentElement).hasClass('device-tablet') 
                || $(document.documentElement).hasClass('device-phone'))
                && gJobs.areaInfoService.getCurrentNamespace() === gJobs.areaInfoService.namespaceNames.CareerPages
            ) {
                var elementsToDisableSelector = '#title-bar :focusable, .dropdown-nav.nav.nav-pills :focusable, .links-container :focusable';
                if (newValue) {
                    $(elementsToDisableSelector).addClass('ignore-tabindex-update');

                    OnlineApp.Services.tabIndexService.disableTabIndex({
                        tabIndexElementsSelector: elementsToDisableSelector
                    });
                } else {
                    $(elementsToDisableSelector).removeClass('ignore-tabindex-update');

                    OnlineApp.Services.tabIndexService.restoreTabIndex({
                        tabIndexElementsSelector: elementsToDisableSelector
                    });
                }
            }
        });

        function confirmedDeleteAccount() {
            $.post('/user/deleteaccount')
                .done(function(data) {
                    if (data.isSuccess) {
                        var $deleteAccount = $('#delete-account');
                        OnlineApp.Helpers.layoutHelper.tabbing.updateIndices($deleteAccount);

                        gJobs.screenReadersService.setNotification($deleteAccount.find('.sr-notification'), 'Account deleted successfully', null, true);

                        var options = {
                            isExternalLogin: data.isExternalLogin,
                            providerName: data.providerName
                        }

                        setTimeout(() => OnlineApp.Services.authenticationService.logout(options)
                            .done(function() { location.reload(); }), 1000);
                    }
                    else {
                        toastr.error(Resources.NotificationMessages.EncounteredProblem);
                    }
                })
                .fail(function() {
                    toastr.error(Resources.NotificationMessages.EncounteredProblem);
                });
        }

        function cancelDeleteAccount() {
            OnlineApp.Services.authenticationService
                .getUserData();
        }

        self.fromDataModel = function (accountSettingsData) {
            var contactInfoData = accountSettingsData.contactInfo;
            var externalLoginData = accountSettingsData.externalLogin;
            var emailPreferencesData = accountSettingsData.emailPreferences;
            var talentSearchPreferencesData = accountSettingsData.talentSearchPreferences;
            var textMessagingPreferencesData = accountSettingsData.textMessagingPreferences;

            if (!contactInfoData) {
                toastr.warning("AccountSettingsViewModel.fromDataModel data undefined");
                return;
            }

            self.contactInfo.fromDataModel(contactInfoData);
            self.contactInfo.registerValidation(
                    self.contactInfo.getValidationConfig()
                );
            self.contactInfo.suppressValidationErrors();

            var shouldShowPasswordTab = externalLoginData.isAbleChangePassword;

            self.talentSearchPreferences.fromDataModel(talentSearchPreferencesData);
            self.emailPreferences.fromDataModel(emailPreferencesData);
            self.textMessagingPreferences.fromDataModel(textMessagingPreferencesData);

            self.showEmailPreferencesTab(!!emailPreferencesData);
            self.showTextMessagingPreferencesTab(!!textMessagingPreferencesData);
            self.showPreferencesTab(!!talentSearchPreferencesData);
            self.showChangePasswordTab(shouldShowPasswordTab);
            if (window.location.href.indexOf("#preferences") !== -1) {
                setTimeout(function () { self.showAuthorizedContent(true); }, 1500);
            }
            else {
                self.showAuthorizedContent(true);
            }

            if (window.enableTwoFactorAuthentication && window.enableEmailVerification) {
                var twoFactorAuthenticationPreferencesData = accountSettingsData.twoFactorAuthenticationPreferences;

                self.twoStepVerificationViewModel.fromDataModel(twoFactorAuthenticationPreferencesData);

                self.twoStepVerificationViewModel.isEmailVerified(accountSettingsData.emailVerificationInfo.isEmailVerified);

                self.twoStepVerificationViewModel.beginEdit(self.twoStepVerificationViewModel, null, true, null);
            }
        };

        self.deleteAccount = function () {
            $(".confirm-dialog h1").text('Are you sure you want to delete your account?');
            $(document).trigger(
                Events.CommonEventsNames.ShowConfirmDialog,
                {
                    header: 'Are you sure you want to delete your account?',
                    hideSubHeader: true,
                    confirmButtonText: 'Delete Account',
                    confirmClick: function () {
                        sessionStorage.setItem("isTermsDeclined", "1");
                        localStorage.setItem("istermsAndPrivacyPolicyDialogContainer", "1");
                        confirmedDeleteAccount();
                    },
                    cancelClick: function () { 
                        localStorage.setItem("istermsAndPrivacyPolicyDialogContainer", "0");
                        var popup = document.getElementById("terms-and-privacy-policy-update-confirmation");
                        if (popup) {
                            popup.style.display = "block";
                            sessionStorage.setItem("isTermsDeclined", "0");
                        }
                        cancelDeleteAccount();
                    }
                }
            );
        };

        self.isFieldRequired = function (fieldName) {
            return OnlineApp.FieldSettings[fieldName] && OnlineApp.FieldSettings[fieldName].required;
        }

        self.isOnCareerArea = function() {
            var abstractAreaInfoService = new gJobs.AbstractAreaInfoService();

            var currentArea = gJobs.areaInfoService.getCurrentArea();

            return currentArea === abstractAreaInfoService.areaNames.Career;
        };

        self.FocusinValidationVisibleChange = OnlineApp.ViewModels.applicationViewModel.FocusinValidationVisibleChange;
        self.FocusinTooltipVisibleChange = OnlineApp.ViewModels.applicationViewModel.FocusinTooltipVisibleChange;

        $(document)
            .off(OnlineApp.Events.CommonEventsNames.PreSaveValidationFailed)
            .on(OnlineApp.Events.CommonEventsNames.PreSaveValidationFailed, function (e) {
                self.navigationController.scrollToTopValidationError(e.target);
            })
            .on(Events.CommonEventsNames.AccessMembershipEnabled, function(event) {
                self.talentSearchPreferences.isAccessMembershipEnabled(true);
            });

        self.onAccountSettingsNavigation = function(event) {
            if (window.enableStickyHeader) {
                var $stickyHeader = $('#sticky-header');
                var preferencesTabHash = '#preferences-tab';

                if (event.currentTarget.hash === preferencesTabHash
                    || self.talentSearchPreferences.isAccessMembershipEnabled()) {
                    $stickyHeader.hide();
                } else {
                    $stickyHeader.show();
                }
            }
        };
    };

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        AccountSettingsViewModel: AccountSettingsViewModel,
        accountSettingsViewModel: new AccountSettingsViewModel()
    });

})(window);;
(function (window, undefined) {
    'use strict';


    function DefinitionViewModel() {
        var self = this;

        self.items = ko.observableArray();

        self.findItemByField = function (fieldName, fieldValue) {
            var items = self.items();
            for (var i in items) {
                var item = items[i];

                if (item.hasOwnProperty(fieldName) && item[fieldName] == fieldValue) {
                    return item;
                }
            }
            return {};
        };

        self.findItemById = function (id) {
            return self.findItemByField("id", id);
        };
    }


    function ConstantDefinitionViewModel(items) {
        var self = DefinitionViewModel.apply(this, arguments) || this;

        self.items(items);
    }


    function ServiceBasedDefinitionViewModel(dataServiceEndpoint) {
        var self = DefinitionViewModel.apply(this, arguments) || this;


        var items = [];


        var loadItemsAsync = function () {
            dataServiceEndpoint
                .get()
                .done(function (data) {
                    items = data;
                    self.isLoaded(true);
                });
        };


        self.isLoaded = ko.observable(false);

        self.items = ko.computed(function () {
            if (!self.isLoaded()) {
                loadItemsAsync();
            }

            return items;
        });
    }

    function DeferredDefinitionViewModel() {
        var self = DefinitionViewModel.apply(this, arguments) || this;

        var deferred = $.Deferred();
        var promise = deferred.promise();

        self.setItems = function (definition) {
            deferred.resolve(definition);
            self.variableItems(definition);
        }

        self.resetItems = function() {
            deferred.reject();
        }

        self.variableItems = ko.observableArray([]);

        self.items = ko.computed(function () {
            return self.variableItems();
        });

        self.get = function() {
            return promise;
        }
    }

    function DefinitionsViewModel(fetchDeferredDefinitions) {
        var self = this;

        var endpoints = OnlineApp.Services.dataService.definitions;

        // todo: combine this logic into CompositeDefinitionsViewModel
        for (var endpointName in endpoints) {
            if (endpoints.hasOwnProperty(endpointName)) {
                self[endpointName] = new DeferredDefinitionViewModel();
            }
        }

        if (fetchDeferredDefinitions) {

            OnlineApp.Services.dataService.PastFutureRange
                .get()
                .done(function (range) {
                    var currentTime = new Date();
                    var currentYear = currentTime.getFullYear();

                    var pastRange = new Array();
                    for (var i = currentYear; i >= range.data.minYear; i--) {
                        pastRange.push({ id: i, text: i });
                    }
                    self.PastToPresentYear.setItems(pastRange);
                    
                    var pastFutureRange = new Array();
                    for (var i = range.data.maxYear; i >= range.data.minYear; i--) {
                        pastFutureRange.push({ id: i, text: i });
                    }
                    self.PastToFutureYear.setItems(pastFutureRange);
                });

            OnlineApp.Services.dataService.compositeDefinitions
                .get()
                .done(function(definitions) {
                    for (var endpointName in endpoints) {
                        if (endpoints.hasOwnProperty(endpointName)) {
                            self[endpointName].setItems(definitions[endpointName]);
                        }
                    }
                })
                .fail(function() {
                    for (var endpointName in endpoints) {
                        if (endpoints.hasOwnProperty(endpointName)) {
                            self[endpointName].resetItems();
                        }
                    }
                });
                
            OnlineApp.Services.dataService.InvalidSsnValues
                .get()
                .done(function (invalidSsnValues) {
                    self.invalidSsnValues = invalidSsnValues;
                });
        }

        //fetch required data
        OnlineApp.Services.dataService.sessionExpirationData
            .get()
            .done(function (sessionExpirationData){
                self.sessionExpirationData.setItems(sessionExpirationData);
            })
            .fail(function() {
                self.sessionExpirationData.resetItems();
            })

        self.PastToPresentYear = new DeferredDefinitionViewModel();
        self.PastToFutureYear = new DeferredDefinitionViewModel();
        self.sessionExpirationData = new DeferredDefinitionViewModel();

        self.invalidSsnValues = new Array();

        self.menuStepIds = {
            loginSuccess: 0,
            loginFailure: 1,
            resume: 2,
            info: 3,
            work: 4,
            education: 5,
            additional: 6,
            references: 7,
            questions: 8,
            attachments: 9,
            review: 10,
            submit: 11,
            profile: 12,
            register: 13,
            payment: 14,
            contactInfo: 15,
            changePassword: 16,
            deleteAccount: 17,
            emailPreferences: 18,
            preferences: 19,
            textMessagingPreferences: 20,
            twoFactorPreferences: 21
        };

        self.menuStep = new ConstantDefinitionViewModel([
            { id: self.menuStepIds.loginSuccess, text: 'LoginSuccess'},
            { id: self.menuStepIds.loginFailure, text: 'LoginFailure'},
            { id: self.menuStepIds.resume, text: 'Resume', tabId:'#resume-tab'},
            { id: self.menuStepIds.info, text: 'Info', tabId: '#general-info-tab'},
            { id: self.menuStepIds.work, text: 'Work', tabId: '#work-tab' },
            { id: self.menuStepIds.education, text: 'Education', tabId: '#education-tab' },
            { id: self.menuStepIds.additional, text: 'Additional', tabId: '#additional-info-tab' },
            { id: self.menuStepIds.references, text: 'References', tabId: '#references-tab' },
            { id: self.menuStepIds.questions, text: 'Questions', tabId: '#questions-tab' },
            { id: self.menuStepIds.attachments, text: 'Attachments', tabId:  '#attachments-tab'},
            { id: self.menuStepIds.review, text: 'Review', tabId: '#review-tab' },
            { id: self.menuStepIds.submit, text: 'Submit', tabId: '#submit-tab' },
            { id: self.menuStepIds.profile, text: 'Profile', tabId: '#profile-tab' },
            { id: self.menuStepIds.register, text: 'Register' },
            { id: self.menuStepIds.payment, text: 'Payment', tabId: '#payment-tab' },
            { id: self.menuStepIds.contactInfo, text: 'Contact Info', tabId: '#contact-info-tab' },
            { id: self.menuStepIds.changePassword, text: 'Change Password', tabId: '#change-password-tab' },
            { id: self.menuStepIds.deleteAccount, text: 'DeleteAccount', tabId: '#delete-account-tab' },
            { id: self.menuStepIds.emailPreferences, text: 'Email Preferences', tabId: '#email-preferences-tab' },
            { id: self.menuStepIds.preferences, text: 'Preferences', tabId: '#preferences-tab' },
            { id: self.menuStepIds.textMessagingPreferences, text: 'Text Messaging Preferences', tabId: '#text-messaging-preferences-tab' },
            { id: self.menuStepIds.twoFactorPreferences, text: 'Two Factor Preferences', tabId: '#two-step-verification-tab' }
        ]);

        // generate days array
        var days = [];
        for (var i = 1; i <= 31; i++) {
            days.push({
                id: i,
                text: i + ''
            });
        }
        self.day = new ConstantDefinitionViewModel(days);

        self.month = new ConstantDefinitionViewModel([
            { id: 1, text: 'January' },
            { id: 2, text: 'February' },
            { id: 3, text: 'March' },
            { id: 4, text: 'April' },
            { id: 5, text: 'May' },
            { id: 6, text: 'June' },
            { id: 7, text: 'July' },
            { id: 8, text: 'August' },
            { id: 9, text: 'September' },
            { id: 10, text: 'October' },
            { id: 11, text: 'November' },
            { id: 12, text: 'December' }
        ]);
        
        self.educationUnitType = new ConstantDefinitionViewModel([
            { id: 'Semester', text: 'Semester Units' },
            { id: 'Quarter', text: 'Quarter Units' }
        ]);

        self.extendedMonth = new ConstantDefinitionViewModel([
            { id: 1, text: 'January' },
            { id: 2, text: 'February' },
            { id: 3, text: 'March' },
            { id: 4, text: 'April' },
            { id: 5, text: 'May' },
            { id: 6, text: 'June' },
            { id: 7, text: 'July' },
            { id: 8, text: 'August' },
            { id: 9, text: 'September' },
            { id: 10, text: 'October' },
            { id: 11, text: 'November' },
            { id: 12, text: 'December' },
            { id: 14, text: 'Present' }
        ]);

        self.monthWithNoExpiration = new ConstantDefinitionViewModel([
            { id: 1, text: 'January' },
            { id: 2, text: 'February' },
            { id: 3, text: 'March' },
            { id: 4, text: 'April' },
            { id: 5, text: 'May' },
            { id: 6, text: 'June' },
            { id: 7, text: 'July' },
            { id: 8, text: 'August' },
            { id: 9, text: 'September' },
            { id: 10, text: 'October' },
            { id: 11, text: 'November' },
            { id: 12, text: 'December' },
            { id: 15, text: 'No Expiration' }
        ]);
        
        self.year = new ConstantDefinitionViewModel([
            { id: 2013, text: '2013' },
            { id: 2012, text: '2012' },
            { id: 2011, text: '2011' },
            { id: 2010, text: '2010' },
            { id: 2009, text: '2009' },
            { id: 2008, text: '2008' },
            { id: 2007, text: '2007' },
            { id: 2006, text: '2006' },
            { id: 2005, text: '2005' },
            { id: 2004, text: '2004' },
            { id: 2003, text: '2003' },
            { id: 2002, text: '2002' },
            { id: 2001, text: '2001' },
            { id: 2000, text: '2000' },
            { id: 1999, text: '1999' },
            { id: 1998, text: '1998' },
            { id: 1997, text: '1997' },
            { id: 1996, text: '1996' },
            { id: 1995, text: '1995' },
            { id: 1994, text: '1994' },
            { id: 1993, text: '1993' },
            { id: 1992, text: '1992' },
            { id: 1991, text: '1991' },
            { id: 1990, text: '1990' },
            { id: 1989, text: '1989' },
            { id: 1988, text: '1988' },
            { id: 1987, text: '1987' },
            { id: 1986, text: '1986' },
            { id: 1985, text: '1985' },
            { id: 1984, text: '1984' },
            { id: 1983, text: '1983' },
            { id: 1982, text: '1982' },
            { id: 1981, text: '1981' },
            { id: 1980, text: '1980' },
            { id: 1979, text: '1979' },
            { id: 1978, text: '1978' },
            { id: 1977, text: '1977' },
            { id: 1976, text: '1976' },
            { id: 1975, text: '1975' },
            { id: 1974, text: '1974' },
            { id: 1973, text: '1973' },
            { id: 1972, text: '1972' },
            { id: 1971, text: '1971' },
            { id: 1970, text: '1970' }
        ]);

        var expirationYears = [];
        var maxExpirationYearSeed = 15;
        var currentYear = new Date().getFullYear();
        var maxExpirationYear = currentYear + maxExpirationYearSeed;
        for (var i = currentYear; i < maxExpirationYear; i++) {
            expirationYears.push({ id: i, text: i.toString() });
        }
        self.expirationYear = new ConstantDefinitionViewModel(expirationYears);
        
        self.notificationType = new ConstantDefinitionViewModel([
            { id: 0, text: 'None' },
            { id: 1, text: 'Email' },
            { id: 2, text: 'Paper' }
        ]);

        self.relocationType = new ConstantDefinitionViewModel([
            { id: 0, text: 'None' },
            { id: 1, text: 'Yes' },
            { id: 2, text: 'No' },
            { id: 3, text: 'Maybe' },
            { id: 4, text: 'No Response' }
        ]);

        self.shiftType = new ConstantDefinitionViewModel([
            { id: 0, text: 'None' },
            { id: 1, text: 'Day' },
            { id: 2, text: 'Evening' },
            { id: 3, text: 'Night' },
            { id: 4, text: 'Rotating' },
            { id: 5, text: 'Weekends' },
            { id: 6, text: 'On Call' }
        ]);

        self.positionType = new ConstantDefinitionViewModel([
            { id: 0, text: 'None' },
            { id: 1, text: 'Regular' },
            { id: 2, text: 'Temporary' },
            { id: 3, text: 'Seasonal' },
            { id: 4, text: 'Internship' }
        ]);

        self.workType = new ConstantDefinitionViewModel([
            { id: 0, text: 'None' },
            { id: 1, text: 'Full Time' },
            { id: 2, text: 'Part Time' },
            { id: 3, text: 'Per Diem' }
        ]);

        self.level = new ConstantDefinitionViewModel([
            { id: 0, text: 'None' },
            { id: 1, text: 'Beginner' },
            { id: 2, text: 'Intermediate' },
            { id: 3, text: 'Expert' }
        ]);

        self.referenceType = new ConstantDefinitionViewModel([
            { id: 0, text: 'Personal' },
            { id: 1, text: 'Professional' }
        ]);

        self.creditCardType = new ConstantDefinitionViewModel([
            { id: 1, text: 'American Express' },
            { id: 2, text: 'Discover' },
            { id: 3, text: 'MasterCard' },
            { id: 4, text: 'Visa' }
        ]);
        
        self.disabilityAnswer = new ConstantDefinitionViewModel([
            { id: 1, text: 'No' },
            { id: 2, text: 'Yes' },
            { id: 3, text: 'NoAnswer' }
        ]);
    }


    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        DefinitionsViewModel: DefinitionsViewModel
    });

    OnlineApp.Namespace.extend('OnlineApp.ViewModels', {
        ServiceBasedDefinitionViewModel: ServiceBasedDefinitionViewModel
    });

})(window);;
(function (window, undefined) {
    'use strict';

    var vm = OnlineApp.ViewModels,
        accountSettingsViewModel = OnlineApp.ViewModels.accountSettingsViewModel,
        definitionsViewModel = new vm.DefinitionsViewModel(true),
        tabsNavigationController = OnlineApp.Controllers.tabsNavigationController,
        accountSettingsContainer = '#account-settings',
        dropdownMenu = null,
        leftMenu = null,
        layoutHelper = OnlineApp.Helpers.layoutHelper,
        areaInfoService = gJobs.areaInfoService,
        stickyHeader = '#sticky-header';

    var initializeMenu = function() {
        dropdownMenu = $(accountSettingsContainer).find('.dropdown-menu');
        leftMenu = $(accountSettingsContainer).find('.left-menu-nav');

        tabsNavigationController.enableHashChangeTracking();

        registerOnTabShownHandler();

        tabsNavigationController.syncCurrentTab();
        notifySelectedTabOnPageLoad();

        if (!$('#terms-and-privacy-policy-update-confirmation').hasClass('active')) {
            document.activeElement.blur();
            gJobs.skipToContentService.showOnNextTab();
        }
    },
        synchronizeMenu = function(tabName) {
            // Dropdown sync
            dropdownMenu.find('li').removeClass('active');
            var activeTabLink = dropdownMenu.find('a[href$="' + tabName + '"]');
            activeTabLink.parent('li').addClass('active');

            // Dropdown header sync
            $(accountSettingsContainer).find('.dropdown-toggle .dropdown-content')
                .html(activeTabLink.html());

            // Left menu sync
            leftMenu.find('li').removeClass('active');
            leftMenu.find('a[href$="' + tabName + '"]')
                .parent('li').addClass('active');
        },
        getHtmlTemplates = function() {
            // prevent template re-loading
            var promise = $.when();

            if (!accountSettingsViewModel.isHtmlTemplateLoaded()) {
                promise = OnlineApp.Services.authenticationService
                    .getAccountSettingsPageHtmlTemplates()
                    .done(function(layout) {
                        // place templates into DOM
                        $('#template-container').html(layout);
                        accountSettingsViewModel.isHtmlTemplateLoaded(true);
                    })
                    .fail(function() {
                        toastr.warning(Resources.NotificationMessages.ServerConnectionFailed);
                    });
            }

            return promise;
        },
        registerOnTabShownHandler = function () {
            $(accountSettingsContainer).find('.dropdown-menu, .left-menu-nav')
                .find('a[data-toggle="tab"]').on('shown', function (e) {
                    var tabName = $(e.currentTarget).attr('href');
                    if (!tabName)
                        return;

                    tabName = tabName.substr(1, tabName.length - 1);

                    synchronizeMenu(tabName);

                    tabsNavigationController.syncHash();

                    var menuStep = definitionsViewModel.menuStep.findItemByField('tabId', '#' + tabName);
                    if (menuStep) {
                        OnlineApp.Services.auditService.setAction(undefined, menuStep.id);
                    }

                    layoutHelper.tabbing.updateIndices();

                    $(document).trigger('layoutUpdated');
                })
                .on('click', accountSettingsViewModel.onAccountSettingsNavigation);
        },
        getAgencyFolderName = function () {
            var employerFolderName = AgencyPages.pageInfoService
                ? AgencyPages.pageInfoService.getCurrentAgencyFolderName()
                : gJobs.pageInfoService.getCurrentAgencyPageFolderName();
            if (employerFolderName) {
                return employerFolderName;
            }

            return null;
        },
        getAccountSettingsData = function () {
            var folderName = getAgencyFolderName();
            if (folderName){
                return OnlineApp.Services.dataService.accountSettingsData.get(null, { agencyFolderName: folderName });
            }
            return OnlineApp.Services.dataService.accountSettingsData.get();
        },
        getCurrentQueryParams = function () {
            return url.get(window.location.search.slice(1), { array: true })
        },
        removeQueryParamsFromUrl = function (activeTabId) {
            var accountSettingsPagePath = gJobs.accountSettingsHelper.getLinkForAccountSettings();

            namespace(areaInfoService.getCurrentNamespace())
                .router.navigate(accountSettingsPagePath + activeTabId, false);
        },
        notifySelectedTabOnPageLoad = function() {
            var tabName = $(accountSettingsContainer).find('.dropdown-menu, .left-menu-nav')
            .find('li[class="active"]')
            .find('a[data-toggle="tab"]')
            .attr('href');

            var menuStep = definitionsViewModel.menuStep.findItemByField('tabId', tabName);

            gJobs.screenReadersService.setAriaLiveNotification(menuStep.text + ' tab is selected.');
        };

    var navigationController = OnlineApp.Controllers.navigationController;

    accountSettingsViewModel.accountSettingsTemplateAfterRender = function() {
        initializeMenu();
    };

    accountSettingsViewModel.changePasswordTemplateAfterRender = function () {
        OnlineApp.Helpers.popoverHelper.accountInitializePopover('body', '#change-password .note');
        if (!gJobs.browserDetector.isIE()) {
            $('#change-password .note')
                .on('show.bs.popover', function() {
                    $(this).attr('role', 'dialog');
                });
        }
    };

    accountSettingsViewModel.deleteAccountTabAfterRender = function (elements, viewModel) {
        var currentQueryParams = getCurrentQueryParams();
        if (currentQueryParams.declined === "true") {
            viewModel.deleteAccount();

            removeQueryParamsFromUrl("#delete");
        }
    }

    var init = function () {
        layoutHelper.showOnlineAppSpinner(true);

        // wait for two requests to complete
        getHtmlTemplates().then(
            function() {
                getAccountSettingsData().then(
                    function (accountSettingsData) {
                        if (!accountSettingsData.contactInfo) {
                            toastr.warning("Sorry.. Nothing to show");
                            return;
                        }

                        vm.applicationViewModel.definitionsViewModel = definitionsViewModel;
                        accountSettingsViewModel.definitionsViewModel = vm.applicationViewModel.definitionsViewModel;
                        accountSettingsViewModel.fromDataModel(accountSettingsData);
                        $("#skip-to-content-button").show();
                        gJobs.screenReadersService.silenceScreenreaderForBanner("");
                    },
                    function () {
                        toastr.warning(Resources.NotificationMessages.EncounteredProblem);
                    }
                )
            },
            // failed callback
            function () {
                toastr.warning(Resources.NotificationMessages.EncounteredProblem);
            }
        )
        .always(function () {
            layoutHelper.hideOnlineAppSpinner(true);
            $(document).trigger('layoutUpdated');

            // Apply ko bindings only for specific region on a page.
            var accountSettingsPage = $(accountSettingsContainer);
            if (accountSettingsPage.length > 0) {
                ko.applyBindings(accountSettingsViewModel, accountSettingsPage.get(0));
            }
        });

        OnlineApp.Services.authenticationService.getUserData()
            .then(function (data) {
                accountSettingsViewModel.isImpersonatedJobSeeker = data.isImpersonating;

                return data;
            });

        $(document)
            .off(OnlineApp.Events.CommonEventsNames.EditableItemBeginEdit)
            .off(OnlineApp.Events.CommonEventsNames.EditItemComplete)
            .on(OnlineApp.Events.CommonEventsNames.EditableItemBeginEdit, function (e, data) {
                layoutHelper.tabbing.updateIndices();

                if (!data.editEvent) {
                    return;
                }

                var editableItemContainer = $('.box-container').last();

                layoutHelper.tabbing.activateFirstElement(editableItemContainer);
            })
            .on(OnlineApp.Events.CommonEventsNames.EditItemComplete, function (e) {
                navigationController.scrollToView(e.targetMetrics);
                layoutHelper.tabbing.updateIndices();

                var $editableItemContainer = $(e.editableItemContainer);
                var $editButton = $editableItemContainer.find('.item-edit-button');
                $editButton.focus();

                if ($('#preferences-tab').hasClass('active')) {
                    var talentSearchPreferences = accountSettingsViewModel.talentSearchPreferences;
                    if (talentSearchPreferences.isDataChanged()) {
                        var status =  talentSearchPreferences.isAccessMembershipEnabled() ? 'Enabled' : 'Disabled';
                        gJobs.common.analytics.trackEvent(
                            'Access Membership Preferences Section',
                            status
                        );
                    }
                }

            })
            .on(OnlineApp.Events.CommonEventsNames.EndSave, function (e, args) {
            if (args == "success") {
                toastr.success("Account settings saved");
            }
        });
    };

    $(document).ready(function() {
        OnlineApp.Services.authenticationService.isLoggedIn()
            .done(function(isLoggedIn) {
                if (isLoggedIn) {
                    if (window.enableStickyHeader && gJobs.pageInfoService.isOnPreferencesSectionPage()) {
                        $(stickyHeader).hide();
                    }

                    init();
                } else {
                    OnlineApp.ViewModels.applicationViewModel.checkIfShouldCreateNewAccount();
                }

                $(document).trigger('layoutUpdated');
            });

        var eventNames = 'loginEvent registerEvent';
        $(document).on(eventNames,
            function() {
                var $accountSettingsContainer = $(accountSettingsContainer);
                $accountSettingsContainer.show();

                gJobs.ajax.ajaxGet("/Applications/AccountSettingsPartial")
                    .done(function(data) {
                        $accountSettingsContainer
                            .find(".partial-container")
                            .html(data);

                        init();
                    });
            });

        var currentQueryParams = getCurrentQueryParams();
        if (currentQueryParams.changeEmail === 'true') {
            gJobs.common.analytics.trackEvent('Email change', 'Change email link clicked');
        }

        gJobs.pageTabNavigationService.adjustNavigationForFixedHeader($('body'));
    });
})(window);;
(function(window, undefined) {
    $(document).ready(function() {
        var $cancelVerificationRequestDialog = $('#cancel-verification-request-dialog');

        //
        // Initializer
        //
        $(function() {
            var dialogElement = $cancelVerificationRequestDialog.get(0);

            if (dialogElement) {
                var viewModel = new gJobs.ViewModels.CancelVerificationRequestDialogViewModel();

                ko.applyBindings(viewModel, dialogElement);
            }
        });
    });
})(window);;
(function(window) {
    $(document).ready(function() {
        var $cancelVerificationRequestDialog = $('#cancel-verification-request-dialog'),
            $body = $('body'),
            initialBodyClasses = '',
            disableScrollClasses = 'scroll-disable inner-scrollbar',
            dialogHeaderSelector = '#dialog-header-cancel-request',
            dialogContentSelector = '.inner-content-container p',
            proceedButtonSelector = '.btn-app-secondary';

        function CancelVerificationRequestDialogViewModel(options) {
            var self = this;

            self.visible = ko.observable(false);

            self.visible.subscribe(function(value) {
                showHideElementsOnDialog(value);
                if (value) {
                    setTimeout(function() {
                        focusOnFistTabbableDialogElement();
                    });
                }
            });

            self.proceedCancelling = function() {
                gJobs.screenReadersService.setAriaLiveNotification(
                    'You are proceeding without verifying the new email address. The modal dialog has been closed.'
                );

                hideDialog();

                OnlineApp.Services.emailVerificationService.deactivateEmailVerificationCode()
                    .done(function(response) {
                        $(document).trigger(OnlineApp.Events.CommonEventsNames.ContactInfoEmailVerificationFormClosed);

                        var applicationProcessUrl = sessionStorage.getItem(OnlineApp.SessionKeys.ApplicationProcessUrl);

                        if (applicationProcessUrl) {
                            sessionStorage.removeItem(OnlineApp.SessionKeys.ApplicationProcessUrl);

                            window.location = applicationProcessUrl;
                        }
                    });
            };

            self.goBack = function() {
                gJobs.screenReadersService.setAriaLiveNotification(
                    'The modal dialog has been closed.'
                );

                hideDialog();
            };

            function showHideElementsOnDialog(hide) {
                gJobs.dialogHelper.showHideElementsOnDialog(
                    {
                        selector: '#header #body-container, #main-container,'
                            + '#footer, #footer-new, .new-job-flyout, #skip-to-content-button,'
                            + '#last-focusable-element, #cookie-consent, #contact-info-tab, #account-settings ul.nav.left-menu-nav',
                        shouldDisableRestoreTabIndex: true,
                        hide: hide
                    }
                );
            }

            function announceDialogContent() {
                var dialogHeaderMessage = $cancelVerificationRequestDialog.find(dialogHeaderSelector).text();
                var dialogContentMessage = $cancelVerificationRequestDialog.find(dialogContentSelector).text();
                var message = dialogHeaderMessage + ' ' + dialogContentMessage;

                var $proceedButton = $cancelVerificationRequestDialog.find(proceedButtonSelector);

                var options = {
                    message: message,
                    $element: $proceedButton
                };

                gJobs.screenReadersService.onceNotification(options);
            }

            function hideDialog() {
                $body.attr('class', initialBodyClasses);
                $cancelVerificationRequestDialog.removeClass('active');
                self.visible(false);
            }

            function showDialog() {
                announceDialogContent();
                $cancelVerificationRequestDialog.addClass('active');
                self.visible(true);
                initialBodyClasses = $body.attr('class') || '';
                $body.addClass(disableScrollClasses);
            }

            function focusOnFistTabbableDialogElement() {
                $cancelVerificationRequestDialog.find(":tabbable").first().focus();
            }

            $(document).on('keydown', function(e) {
                if (e.keyCode === $.ui.keyCode.ESCAPE && self.visible()) {
                    self.goBack();
                }
            });

            $(document).on(OnlineApp.Events.CommonEventsNames.ShowCancelVerificationRequestDialog, function() {
                showDialog();
            });
        }

        OnlineApp.Namespace.extend('gJobs.ViewModels', {
            CancelVerificationRequestDialogViewModel: CancelVerificationRequestDialogViewModel
        });
    });
})(window);;
