/* Minification failed. Returning unminified contents.
(1,22): run-time error CSS1031: Expected selector, found '='
(1,22): run-time error CSS1025: Expected comma or open brace, found '='
(2,1): run-time error CSS1019: Unexpected token, found '$'
(2,2): run-time error CSS1019: Unexpected token, found '('
(2,12): run-time error CSS1031: Expected selector, found '('
(2,12): run-time error CSS1025: Expected comma or open brace, found '('
(10,2): run-time error CSS1019: Unexpected token, found ')'
(13,10): run-time error CSS1031: Expected selector, found 'globalKeyUp('
(13,10): run-time error CSS1025: Expected comma or open brace, found 'globalKeyUp('
(52,10): run-time error CSS1031: Expected selector, found 'loadSearchBoxClients('
(52,10): run-time error CSS1025: Expected comma or open brace, found 'loadSearchBoxClients('
(71,10): run-time error CSS1031: Expected selector, found 'sortSearchBox('
(71,10): run-time error CSS1025: Expected comma or open brace, found 'sortSearchBox('
(83,10): run-time error CSS1031: Expected selector, found 'patientSearchChange('
(83,10): run-time error CSS1025: Expected comma or open brace, found 'patientSearchChange('
(125,10): run-time error CSS1031: Expected selector, found 'userNavClick('
(125,10): run-time error CSS1025: Expected comma or open brace, found 'userNavClick('
(136,10): run-time error CSS1031: Expected selector, found 'showSearch('
(136,10): run-time error CSS1025: Expected comma or open brace, found 'showSearch('
(144,10): run-time error CSS1031: Expected selector, found 'patientSearchClick('
(144,10): run-time error CSS1025: Expected comma or open brace, found 'patientSearchClick('
(151,10): run-time error CSS1031: Expected selector, found 'killSlides('
(151,10): run-time error CSS1025: Expected comma or open brace, found 'killSlides('
(180,10): run-time error CSS1031: Expected selector, found 'searchItemHover('
(180,10): run-time error CSS1025: Expected comma or open brace, found 'searchItemHover('
(185,10): run-time error CSS1031: Expected selector, found 'clearSearchSelected('
(185,10): run-time error CSS1025: Expected comma or open brace, found 'clearSearchSelected('
(189,10): run-time error CSS1031: Expected selector, found 'patientSearchSelect('
(189,10): run-time error CSS1025: Expected comma or open brace, found 'patientSearchSelect('
(213,10): run-time error CSS1031: Expected selector, found 'patientSearchKeyDown('
(213,10): run-time error CSS1025: Expected comma or open brace, found 'patientSearchKeyDown('
(283,15): run-time error CSS1031: Expected selector, found ';'
(283,15): run-time error CSS1025: Expected comma or open brace, found ';'
(285,10): run-time error CSS1031: Expected selector, found 'takeScreenshot('
(285,10): run-time error CSS1025: Expected comma or open brace, found 'takeScreenshot('
(296,1): run-time error CSS1019: Unexpected token, found '$'
(296,2): run-time error CSS1019: Unexpected token, found '('
(296,12): run-time error CSS1031: Expected selector, found '('
(296,12): run-time error CSS1025: Expected comma or open brace, found '('
(305,2): run-time error CSS1019: Unexpected token, found ')'
(307,10): run-time error CSS1031: Expected selector, found 'jtxToggleSectionClick('
(307,10): run-time error CSS1025: Expected comma or open brace, found 'jtxToggleSectionClick('
(319,10): run-time error CSS1031: Expected selector, found 'jtxSearchBoxClose('
(319,10): run-time error CSS1025: Expected comma or open brace, found 'jtxSearchBoxClose('
(323,10): run-time error CSS1031: Expected selector, found 'jtxSearchBoxChange('
(323,10): run-time error CSS1025: Expected comma or open brace, found 'jtxSearchBoxChange('
(332,10): run-time error CSS1031: Expected selector, found 'toggleOptionBtnClick('
(332,10): run-time error CSS1025: Expected comma or open brace, found 'toggleOptionBtnClick('
(343,10): run-time error CSS1031: Expected selector, found 'jtxDropDownClick('
(343,10): run-time error CSS1025: Expected comma or open brace, found 'jtxDropDownClick('
(356,10): run-time error CSS1031: Expected selector, found 'jtxSelectListItemClick('
(356,10): run-time error CSS1025: Expected comma or open brace, found 'jtxSelectListItemClick('
(404,10): run-time error CSS1031: Expected selector, found 'jtxSimpleSelectListItemClick('
(404,10): run-time error CSS1025: Expected comma or open brace, found 'jtxSimpleSelectListItemClick('
(451,10): run-time error CSS1031: Expected selector, found 'jtxSelectListSelectAllClick('
(451,10): run-time error CSS1025: Expected comma or open brace, found 'jtxSelectListSelectAllClick('
(464,18): run-time error CSS1031: Expected selector, found ';'
(464,18): run-time error CSS1025: Expected comma or open brace, found ';'
(465,23): run-time error CSS1031: Expected selector, found '='
(465,23): run-time error CSS1025: Expected comma or open brace, found '='
(467,1): run-time error CSS1019: Unexpected token, found '$'
(467,2): run-time error CSS1019: Unexpected token, found '('
(467,12): run-time error CSS1031: Expected selector, found '('
(467,12): run-time error CSS1025: Expected comma or open brace, found '('
(497,2): run-time error CSS1019: Unexpected token, found ')'
(499,10): run-time error CSS1031: Expected selector, found 'PlaceFindFilePop('
(499,10): run-time error CSS1025: Expected comma or open brace, found 'PlaceFindFilePop('
(505,10): run-time error CSS1031: Expected selector, found 'WindowScroll('
(505,10): run-time error CSS1025: Expected comma or open brace, found 'WindowScroll('
(512,10): run-time error CSS1031: Expected selector, found 'WindowDoneScroll('
(512,10): run-time error CSS1025: Expected comma or open brace, found 'WindowDoneScroll('
(533,10): run-time error CSS1031: Expected selector, found 'DownloadClick('
(533,10): run-time error CSS1025: Expected comma or open brace, found 'DownloadClick('
(540,10): run-time error CSS1031: Expected selector, found 'VideoClick('
(540,10): run-time error CSS1025: Expected comma or open brace, found 'VideoClick('
(546,10): run-time error CSS1031: Expected selector, found 'FAQClick('
(546,10): run-time error CSS1025: Expected comma or open brace, found 'FAQClick('
(559,10): run-time error CSS1031: Expected selector, found 'testimonialScrollDot('
(559,10): run-time error CSS1025: Expected comma or open brace, found 'testimonialScrollDot('
(571,10): run-time error CSS1031: Expected selector, found 'testimonialScroll('
(571,10): run-time error CSS1025: Expected comma or open brace, found 'testimonialScroll('
(603,10): run-time error CSS1031: Expected selector, found 'submitEmailPreferences('
(603,10): run-time error CSS1025: Expected comma or open brace, found 'submitEmailPreferences('
(609,10): run-time error CSS1031: Expected selector, found 'downloadClickScroll('
(609,10): run-time error CSS1025: Expected comma or open brace, found 'downloadClickScroll('
(621,10): run-time error CSS1031: Expected selector, found 'openPopup('
(621,10): run-time error CSS1025: Expected comma or open brace, found 'openPopup('
(657,10): run-time error CSS1031: Expected selector, found 'deviceSelect('
(657,10): run-time error CSS1025: Expected comma or open brace, found 'deviceSelect('
(710,10): run-time error CSS1031: Expected selector, found 'nextClick('
(710,10): run-time error CSS1025: Expected comma or open brace, found 'nextClick('
(721,24): run-time error CSS1031: Expected selector, found ';'
(721,24): run-time error CSS1025: Expected comma or open brace, found ';'
(722,23): run-time error CSS1031: Expected selector, found ';'
(722,23): run-time error CSS1025: Expected comma or open brace, found ';'
(724,10): run-time error CSS1031: Expected selector, found 'displayMessage('
(724,10): run-time error CSS1025: Expected comma or open brace, found 'displayMessage('
(794,10): run-time error CSS1031: Expected selector, found 'displayMessages('
(794,10): run-time error CSS1025: Expected comma or open brace, found 'displayMessages('
(812,10): run-time error CSS1031: Expected selector, found 'clearMessages('
(812,10): run-time error CSS1025: Expected comma or open brace, found 'clearMessages('
(829,10): run-time error CSS1031: Expected selector, found 'handleAjaxMessages('
(829,10): run-time error CSS1025: Expected comma or open brace, found 'handleAjaxMessages('
(835,10): run-time error CSS1031: Expected selector, found 'checkAndHandleMessageFromHeader('
(835,10): run-time error CSS1025: Expected comma or open brace, found 'checkAndHandleMessageFromHeader('
(843,15): run-time error CSS1031: Expected selector, found '='
(843,15): run-time error CSS1025: Expected comma or open brace, found '='
(846,18): run-time error CSS1031: Expected selector, found '='
(846,18): run-time error CSS1025: Expected comma or open brace, found '='
(849,15): run-time error CSS1031: Expected selector, found ';'
(849,15): run-time error CSS1025: Expected comma or open brace, found ';'
(851,1): run-time error CSS1019: Unexpected token, found '$'
(851,2): run-time error CSS1019: Unexpected token, found '('
(851,12): run-time error CSS1031: Expected selector, found '('
(851,12): run-time error CSS1025: Expected comma or open brace, found '('
(954,2): run-time error CSS1019: Unexpected token, found ')'
(956,10): run-time error CSS1031: Expected selector, found 'addListeners('
(956,10): run-time error CSS1025: Expected comma or open brace, found 'addListeners('
(999,10): run-time error CSS1031: Expected selector, found 'createSubmit('
(999,10): run-time error CSS1025: Expected comma or open brace, found 'createSubmit('
(1008,10): run-time error CSS1031: Expected selector, found 'tableListTopMenu('
(1008,10): run-time error CSS1025: Expected comma or open brace, found 'tableListTopMenu('
(1037,10): run-time error CSS1031: Expected selector, found 'tableListMenu('
(1037,10): run-time error CSS1025: Expected comma or open brace, found 'tableListMenu('
(1072,10): run-time error CSS1031: Expected selector, found 'focusableFocus('
(1072,10): run-time error CSS1025: Expected comma or open brace, found 'focusableFocus('
(1077,10): run-time error CSS1031: Expected selector, found 'focusableKeydown('
(1077,10): run-time error CSS1025: Expected comma or open brace, found 'focusableKeydown('
(1130,10): run-time error CSS1031: Expected selector, found 'focusBack('
(1130,10): run-time error CSS1025: Expected comma or open brace, found 'focusBack('
(1143,10): run-time error CSS1031: Expected selector, found 'focusNext('
(1143,10): run-time error CSS1025: Expected comma or open brace, found 'focusNext('
(1172,10): run-time error CSS1031: Expected selector, found 'focusPrevious('
(1172,10): run-time error CSS1025: Expected comma or open brace, found 'focusPrevious('
(1201,10): run-time error CSS1031: Expected selector, found 'isIE('
(1201,10): run-time error CSS1025: Expected comma or open brace, found 'isIE('
(1215,10): run-time error CSS1031: Expected selector, found 'showMessage('
(1215,10): run-time error CSS1025: Expected comma or open brace, found 'showMessage('
(1222,10): run-time error CSS1031: Expected selector, found 'multiSelectChange('
(1222,10): run-time error CSS1025: Expected comma or open brace, found 'multiSelectChange('
(1231,10): run-time error CSS1031: Expected selector, found 'multiSelectOpen('
(1231,10): run-time error CSS1025: Expected comma or open brace, found 'multiSelectOpen('
(1295,10): run-time error CSS1031: Expected selector, found 'textareaAutosize('
(1295,10): run-time error CSS1025: Expected comma or open brace, found 'textareaAutosize('
(1311,10): run-time error CSS1031: Expected selector, found 'loadInTarget('
(1311,10): run-time error CSS1025: Expected comma or open brace, found 'loadInTarget('
(1364,10): run-time error CSS1031: Expected selector, found 'tableListSubmitForm('
(1364,10): run-time error CSS1025: Expected comma or open brace, found 'tableListSubmitForm('
(1371,10): run-time error CSS1031: Expected selector, found 'regularButtonLink('
(1371,10): run-time error CSS1025: Expected comma or open brace, found 'regularButtonLink('
(1381,10): run-time error CSS1031: Expected selector, found 'TrackPatientTime('
(1381,10): run-time error CSS1025: Expected comma or open brace, found 'TrackPatientTime('
(1392,10): run-time error CSS1031: Expected selector, found 'TrackGroupTherapyTime('
(1392,10): run-time error CSS1025: Expected comma or open brace, found 'TrackGroupTherapyTime('
(1403,10): run-time error CSS1031: Expected selector, found 'StartSessionTimer('
(1403,10): run-time error CSS1025: Expected comma or open brace, found 'StartSessionTimer('
(1440,10): run-time error CSS1031: Expected selector, found 'LoginTimeout('
(1440,10): run-time error CSS1025: Expected comma or open brace, found 'LoginTimeout('
(1471,10): run-time error CSS1031: Expected selector, found 'ReloadAfterDelay('
(1471,10): run-time error CSS1025: Expected comma or open brace, found 'ReloadAfterDelay('
(1479,10): run-time error CSS1031: Expected selector, found 'killLink('
(1479,10): run-time error CSS1025: Expected comma or open brace, found 'killLink('
(1484,10): run-time error CSS1031: Expected selector, found 'moduleTypeInfoMenuClick('
(1484,10): run-time error CSS1025: Expected comma or open brace, found 'moduleTypeInfoMenuClick('
(1493,10): run-time error CSS1031: Expected selector, found 'siteStatusResetClick('
(1493,10): run-time error CSS1025: Expected comma or open brace, found 'siteStatusResetClick('
(1499,10): run-time error CSS1031: Expected selector, found 'feedbackTypeClick('
(1499,10): run-time error CSS1025: Expected comma or open brace, found 'feedbackTypeClick('
(1504,10): run-time error CSS1031: Expected selector, found 'showLoading('
(1504,10): run-time error CSS1025: Expected comma or open brace, found 'showLoading('
(1509,10): run-time error CSS1031: Expected selector, found 'hideLoading('
(1509,10): run-time error CSS1025: Expected comma or open brace, found 'hideLoading('
(1518,10): run-time error CSS1031: Expected selector, found 'loginBreakout('
(1518,10): run-time error CSS1025: Expected comma or open brace, found 'loginBreakout('
(1526,10): run-time error CSS1031: Expected selector, found 'maintenanceBreakout('
(1526,10): run-time error CSS1025: Expected comma or open brace, found 'maintenanceBreakout('
(1533,10): run-time error CSS1031: Expected selector, found 'errorBreakout('
(1533,10): run-time error CSS1025: Expected comma or open brace, found 'errorBreakout('
(1541,10): run-time error CSS1031: Expected selector, found 'shareChanged('
(1541,10): run-time error CSS1025: Expected comma or open brace, found 'shareChanged('
(1551,10): run-time error CSS1031: Expected selector, found 'addSharedUser('
(1551,10): run-time error CSS1025: Expected comma or open brace, found 'addSharedUser('
(1593,10): run-time error CSS1031: Expected selector, found 'toggleSharedUser('
(1593,10): run-time error CSS1025: Expected comma or open brace, found 'toggleSharedUser('
(1601,10): run-time error CSS1031: Expected selector, found 'toggleSharedUserElement('
(1601,10): run-time error CSS1025: Expected comma or open brace, found 'toggleSharedUserElement('
(1637,10): run-time error CSS1031: Expected selector, found 'checkLastClinician('
(1637,10): run-time error CSS1025: Expected comma or open brace, found 'checkLastClinician('
(1648,10): run-time error CSS1031: Expected selector, found 'togglePatientLogin('
(1648,10): run-time error CSS1025: Expected comma or open brace, found 'togglePatientLogin('
(1663,10): run-time error CSS1031: Expected selector, found 'toggleEmail('
(1663,10): run-time error CSS1025: Expected comma or open brace, found 'toggleEmail('
(1679,10): run-time error CSS1031: Expected selector, found 'toggleTwoFactor('
(1679,10): run-time error CSS1025: Expected comma or open brace, found 'toggleTwoFactor('
(1689,10): run-time error CSS1031: Expected selector, found 'toggleDORSubscribeEmail('
(1689,10): run-time error CSS1025: Expected comma or open brace, found 'toggleDORSubscribeEmail('
(1698,10): run-time error CSS1031: Expected selector, found 'toggleReportGroupingGroupWarning('
(1698,10): run-time error CSS1025: Expected comma or open brace, found 'toggleReportGroupingGroupWarning('
(1707,10): run-time error CSS1031: Expected selector, found 'toggleTrial('
(1707,10): run-time error CSS1025: Expected comma or open brace, found 'toggleTrial('
(1716,10): run-time error CSS1031: Expected selector, found 'toggleLudoFitSubscriptionEnabled('
(1716,10): run-time error CSS1025: Expected comma or open brace, found 'toggleLudoFitSubscriptionEnabled('
(1724,10): run-time error CSS1031: Expected selector, found 'toggleLudoFitTrialDuration('
(1724,10): run-time error CSS1025: Expected comma or open brace, found 'toggleLudoFitTrialDuration('
(1734,10): run-time error CSS1031: Expected selector, found 'toggleLoginSettings('
(1734,10): run-time error CSS1025: Expected comma or open brace, found 'toggleLoginSettings('
(1746,10): run-time error CSS1031: Expected selector, found 'toggleSubLimit('
(1746,10): run-time error CSS1025: Expected comma or open brace, found 'toggleSubLimit('
(1758,10): run-time error CSS1031: Expected selector, found 'editInLine('
(1758,10): run-time error CSS1025: Expected comma or open brace, found 'editInLine('
(1793,10): run-time error CSS1031: Expected selector, found 'showMenu('
(1793,10): run-time error CSS1025: Expected comma or open brace, found 'showMenu('
(1812,10): run-time error CSS1031: Expected selector, found 'showProfileMenu('
(1812,10): run-time error CSS1025: Expected comma or open brace, found 'showProfileMenu('
(1834,10): run-time error CSS1031: Expected selector, found 'loadAsync('
(1834,10): run-time error CSS1025: Expected comma or open brace, found 'loadAsync('
(1853,10): run-time error CSS1031: Expected selector, found 'launchPatientProgram('
(1853,10): run-time error CSS1025: Expected comma or open brace, found 'launchPatientProgram('
(1859,10): run-time error CSS1031: Expected selector, found 'actionAndReplace('
(1859,10): run-time error CSS1025: Expected comma or open brace, found 'actionAndReplace('
(1876,10): run-time error CSS1031: Expected selector, found 'highlightWarning('
(1876,10): run-time error CSS1025: Expected comma or open brace, found 'highlightWarning('
(1880,10): run-time error CSS1031: Expected selector, found 'reachedWaiverBottom('
(1880,10): run-time error CSS1025: Expected comma or open brace, found 'reachedWaiverBottom('
(1893,10): run-time error CSS1031: Expected selector, found 'reportSubscribeExpandDropdown('
(1893,10): run-time error CSS1025: Expected comma or open brace, found 'reportSubscribeExpandDropdown('
(1908,10): run-time error CSS1031: Expected selector, found 'reportUnsubscribeAll('
(1908,10): run-time error CSS1025: Expected comma or open brace, found 'reportUnsubscribeAll('
(1923,1): run-time error CSS1019: Unexpected token, found '$'
(1923,2): run-time error CSS1019: Unexpected token, found '('
(1923,12): run-time error CSS1031: Expected selector, found '('
(1923,12): run-time error CSS1025: Expected comma or open brace, found '('
(1936,2): run-time error CSS1019: Unexpected token, found ')'
(1938,10): run-time error CSS1031: Expected selector, found 'bootBackdropClick('
(1938,10): run-time error CSS1025: Expected comma or open brace, found 'bootBackdropClick('
(1946,10): run-time error CSS1031: Expected selector, found 'tableListElementPopForm('
(1946,10): run-time error CSS1025: Expected comma or open brace, found 'tableListElementPopForm('
(1954,10): run-time error CSS1031: Expected selector, found 'tableListFilterSubBarPopForm('
(1954,10): run-time error CSS1025: Expected comma or open brace, found 'tableListFilterSubBarPopForm('
(1963,10): run-time error CSS1031: Expected selector, found 'bootPopupHidden('
(1963,10): run-time error CSS1025: Expected comma or open brace, found 'bootPopupHidden('
(1968,10): run-time error CSS1031: Expected selector, found 'bootPopupVisible('
(1968,10): run-time error CSS1025: Expected comma or open brace, found 'bootPopupVisible('
(1981,10): run-time error CSS1031: Expected selector, found 'postActionLink('
(1981,10): run-time error CSS1025: Expected comma or open brace, found 'postActionLink('
(2058,10): run-time error CSS1031: Expected selector, found 'getBootPopupContentClick('
(2058,10): run-time error CSS1025: Expected comma or open brace, found 'getBootPopupContentClick('
(2064,10): run-time error CSS1031: Expected selector, found 'getBootPopupContent('
(2064,10): run-time error CSS1025: Expected comma or open brace, found 'getBootPopupContent('
(2096,10): run-time error CSS1031: Expected selector, found 'processBootPopupSubmitResponse('
(2096,10): run-time error CSS1025: Expected comma or open brace, found 'processBootPopupSubmitResponse('
(2231,10): run-time error CSS1031: Expected selector, found 'openBootPopup('
(2231,10): run-time error CSS1025: Expected comma or open brace, found 'openBootPopup('
(2431,10): run-time error CSS1031: Expected selector, found 'handlePopAjaxResponse('
(2431,10): run-time error CSS1025: Expected comma or open brace, found 'handlePopAjaxResponse('
(2485,10): run-time error CSS1031: Expected selector, found 'submitBootPopupForm('
(2485,10): run-time error CSS1025: Expected comma or open brace, found 'submitBootPopupForm('
(2550,10): run-time error CSS1031: Expected selector, found 'updateBootView('
(2550,10): run-time error CSS1025: Expected comma or open brace, found 'updateBootView('
(2592,10): run-time error CSS1031: Expected selector, found 'removeBlocById('
(2592,10): run-time error CSS1025: Expected comma or open brace, found 'removeBlocById('
(2597,10): run-time error CSS1031: Expected selector, found 'handleError('
(2597,10): run-time error CSS1025: Expected comma or open brace, found 'handleError('
 */
var searchBoxContent = "";
$(function () {
    $(document).on('click', "#header .patientSearch", patientSearchClick);
    $(document).on('click', "#searchMask", killSlides);
    $(document).on('mouseenter', "#searchBox .searchItems .searchItem", searchItemHover);
    $(document).on('keydown', "#header .patientSearch", patientSearchKeyDown);
    $(document).on('click', "#header .navBarUser", userNavClick);
    $(document).on('keyup', "#header .patientSearch input", patientSearchChange);
    $(document).on('keydown', globalKeyUp);
});


function globalKeyUp(e) {
    var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;

    //s
    if (key == 83 && !($(e.target).is('input, textarea')) && !($('#searchMask').is(':visible'))) {
        $("#header .patientSearch input").focus();
        $("#header .patientSearch input").click();
    }

    //kill backspace navigate back behavior
    if (e.which === 8 && !$(e.target).is("input, textarea")) {
        e.preventDefault();
    }

    //esc kill pop or logout
    if (e.which === 27) {
        var modal = $('#modal-holder');
        if (modal != null && modal.is(":visible")) {
            $("button[value='cancel']").click();
        } else if ($('#searchMask').is(":visible")) {
            killSlides();
        } else {
            killSlides();
            var url = $('#confirmLogout').attr('href');
            if (url) {
                getBootPopupContent(url);
            }
        }
        e.preventDefault();
    }

    //enter if patient re-launch
    if (e.which === 13) {
        if (!($('#modal-holder:visible').length > 0)) {
            $('#patientDashboard .launch').click();
        }
    }
}

function loadSearchBoxClients(url) {
    $.ajax({
        url: url,
        success: function (data) {

            if ($('#searchBox .searchItems').html().length > 0) {
                $('#searchBox .loading').hide();
            }

            $('#searchBox .searchItems').append(data);
            sortSearchBox();
            patientSearchChange(true);
        },
        error: function () {
            handleError();
        }
    });
}

function sortSearchBox() {
    var items = $('#searchBox .searchItems .searchItem');
    items = items.sort(function (a, b) {
        if ($(a).data('name') > $(b).data('name')) {
            return 1;
        } else {
            return -1;
        }
    });
    $('#searchBox .searchItems').html(items);
}

function patientSearchChange(force) {
    if ($('#header .patientSearch input').val() && $('#header .patientSearch input').val().length != 0) {
        showSearch();
    }
    if (force || $('#header .patientSearch input').val() != searchBoxContent) {
        searchBoxContent = $('#header .patientSearch input').val();
        if (searchBoxContent) {
            var words = searchBoxContent.split(" ");
            var results = $('#searchBox .searchItems .searchItem');
            results.show();
            $.each(results,
                function(i, element) {
                    //console.log(element)
                    var match = false;
                    var wordCount = 0;
                    var matchCount = 0;
                    $.each(words,
                        function(j, w) {
                            if (w != "") {
                                if ($(element).find('.name').text().toLowerCase().indexOf(w.toLowerCase()) >= 0) {
                                    matchCount++;
                                }
                                wordCount++;
                            }
                        });
                    if (matchCount >= wordCount) {
                        match = true;
                    }
                    if (match) {
                        results = results.not(element);
                    }
                });
            results.hide();
            clearSearchSelected();
            $('#searchBox .searchItems .searchItem:visible').first().addClass('selected');
        } else {
            var results = $('#searchBox .searchItems .searchItem');
            results.show();
        }
    }
}

function userNavClick(event) {
    event.preventDefault();
    $('#userMenu').css({ width: $(this).outerWidth() });

    var rightOffset = $(this).offset().left + $(this).outerWidth();

    $('#userMenu').css({ left: rightOffset - $('#userMenu').outerWidth() });
    $('#userMenu:hidden').slideDown(200);
    $('#searchMask:hidden').show();
}

function showSearch() {
    var left = $('#header .patientSearch').offset().left;
    $('#searchBox').css({ left: left });
    $('#searchBox:hidden').slideDown(200);
    $('#searchMask:hidden').show();
    $('#header .patientSearch').addClass('open');
}

function patientSearchClick(event) {
    showSearch();
    clearSearchSelected();
    $('#searchBox .searchItems .searchItem:visible').first().addClass('selected');
    $('#searchBox').scrollTop(0);
}

function killSlides(event) {
    //console.log('kill')

    if (!$(this).hasClass('patientSearch')) {
        $('#searchBox:visible').slideUp(200);
        $('#header .patientSearch').removeClass('open');
        $('#searchMask:visible').hide();
        $('.dimmed').removeClass('dimmed');
        $('#userMenu:visible').slideUp(200);
        $('.showMenu').removeClass('open');
        $('.showMenu.menu:visible').slideUp(200);
        $('.elementDropMenu:visible').slideUp(200);
        $('.profileMenu.menu:visible').slideUp(200);

        if ($('.profileMenu.menu').is(':visible')) {
            showProfileMenu();
        }
        $('.dropdownMultiSelectOptions:visible').slideUp(200);
        if ($("#support").hasClass('up')) {
            slideLauncherDown();
        }

        if (typeof closeTableListFilterSubBar === "function") {
            closeTableListFilterSubBar();
        }
    }
    return false;
}

function searchItemHover() {
    clearSearchSelected();
    $(this).addClass('selected');
}

function clearSearchSelected() {
    $('#searchBox .searchItems').children().removeClass('selected');
}

function patientSearchSelect(comp) {

    //clearSearchSelected();
    var scrollTop = $('#searchBox .searchItems').scrollTop();
    var scrollHeight = $('#searchBox .searchItems').height();
    var itemTop = comp.position().top;
    var itemHeight = comp.height(); //console.log("scroll t:" + scrollTop + " h:" + scrollHeight + "  " + "item t:" + itemTop + " h:" + itemHeight)

    if (itemTop + itemHeight > scrollHeight) {
        //console.log('Too Low')
        $('#searchBox .searchItems').scrollTop(scrollTop + (itemTop + itemHeight) - scrollHeight);
    }

    if (itemTop < 0) {
        //console.log('Too High')
        $('#searchBox .searchItems').scrollTop(scrollTop + itemTop);
    }

    setTimeout(function () {
        clearSearchSelected();
        comp.addClass('selected');
    }, 100);
}

function patientSearchKeyDown(e) {
    var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;

    //up
    if (key == 38) {
        var index = $('#searchBox .searchItems .searchItem.selected').index();
        var min = 10000;
        var nextIndex = -1;
        $('#searchBox .searchItems .searchItem:visible').each(function (i, el) {
            if (Math.abs(index - $(el).index()) < min && $(el).index() < index) {
                nextIndex = $(el).index();
                min = Math.abs(index - $(el).index());
            }
        });
        if (nextIndex < 0) {
            nextIndex = $('#searchBox .searchItems .searchItem:visible').first().index();
        }

        if (nextIndex >= 0) {
            var prev = $('#searchBox .searchItems').children().get(nextIndex);
            patientSearchSelect($(prev));
        }
        e.preventDefault();
        return false;
    }

    //down
    if (key == 40) {
        var index = $('#searchBox .searchItems .searchItem.selected').index();
        var min = 10000;
        var nextIndex = -1;
        $('#searchBox .searchItems .searchItem:visible').each(function (i, el) {
            if (Math.abs($(el).index() - index) < min && $(el).index() > index) {
                nextIndex = $(el).index();
                min = Math.abs(index - $(el).index());
            }
        });
        if (nextIndex < 0) {
            nextIndex = $('#searchBox .searchItems .searchItem:visible').last().index();
        }

        if (nextIndex >= 0) {
            var next = $('#searchBox .searchItems').children().get(nextIndex);
            patientSearchSelect($(next));
        }

        e.preventDefault();
        return false;

    }

    //enter
    if (key == 13) {
        var url = $('#searchBox .searchItems').children('.selected').attr("href");
        if (url) {
            window.location = url;
        }
        e.preventDefault();
        return false;
    }

    //escape
    if (key == 27) {
        killSlides();
        e.preventDefault();
        return false;
    }
}

//For Selenium screenshot taking using CEFSharp
var screenshot;

function takeScreenshot() {
    html2canvas(document.body, {
        onrendered: function (canvas) {
            screenshot = canvas.toDataURL();
        }
    });
}
/***    
    THIS IS THE JS FILE USED FOR THE COMMON UI COMPONENTS
***/

$(function () {
    $(document).on('click', ".jtxToggleOption input", toggleOptionBtnClick); //multi option select
    $(document).on('click', ".jtxDropDown .jtxBtn", jtxDropDownClick);
    $(document).on('change', ".jtxSelectList .jtxSelectListItem:not(.disabled)", jtxSelectListItemClick);
    $(document).on('change', ".jtxSelectList #selectAll", jtxSelectListSelectAllClick);
    $(document).on('keyup', ".jtxSearchBox input", jtxSearchBoxChange);
    $(document).on('click', ".jtxSearchBox i.clear", jtxSearchBoxClose);
    $(document).on('click', ".jtxToggleSection .jtxToggleLink", jtxToggleSectionClick);
    //$(document).on('click', ".jtxCheckbox", jtxCheckboxClick);
});

function jtxToggleSectionClick() {
    var section = $(this).parents(".jtxToggleSection");
    var target = $(section).find(".jtxToggleShow");
    if (section.hasClass('open')) {
        section.removeClass('open');
        target.slideUp();
    } else {
        section.addClass('open');
        target.slideDown();
    }
}

function jtxSearchBoxClose() {
    $(this).parents('.jtxSearchBox').find('input').val("").trigger('keyup');
}

function jtxSearchBoxChange() {
    if ($(this).val().length == 0) {
        $(this).parents('.jtxSearchBox').find('i.clear').addClass('noDisplay');
    } else {
        $(this).parents('.jtxSearchBox').find('i.clear').removeClass('noDisplay');
    }
}


function toggleOptionBtnClick() {
    var optionClicked = $(this).closest("label");
    var toggleWrapper = optionClicked.closest(".jtxToggleOption");
    if (optionClicked.has("input[type=radio]").length > 0) {
        toggleWrapper.find("label").removeClass("selected");
        optionClicked.addClass("selected");
    } else {
        optionClicked.toggleClass("selected");
    }
}

function jtxDropDownClick() {
    var dropdown = $(this).parents('.jtxDropDown');
    var isOpen = dropdown.hasClass('open');
    var list = $(this).parents('.jtxDropDown').find('.jtxSelectList');
    if (isOpen) {
        list.slideUp();
        dropdown.removeClass("open");
    } else {
        list.slideDown();
        dropdown.addClass("open");
    }
}

function jtxSelectListItemClick() {
    //console.log('HI');

    var optionClicked = $(this).closest("label");
    var wrapper = optionClicked.closest(".jtxSelectList");

    if (optionClicked.has("input[type=radio]").length > 0) {
        //console.log('HERE')
        wrapper.find("label").removeClass("selected");
        optionClicked.addClass("selected");
    } else {

        if (optionClicked.find("input:checkbox").is(':checked')) {
            //console.log(optionClicked)
            optionClicked.addClass("selected");
        } else {
            optionClicked.removeClass("selected");
        }

        //update buttonStatus if dropdown
        if (wrapper.parents('.jtxDropDown').length > 0) {
            if (wrapper.find("input:checkbox:checked").length > 0) {
                wrapper.parents('.jtxDropDown').addClass('selected');
                wrapper.parents('.jtxDropDown').find('.jtxBtn').addClass('selected');
            } else {
                wrapper.parents('.jtxDropDown').removeClass('selected');
                wrapper.parents('.jtxDropDown').find('.jtxBtn').removeClass('selected');
            }
        }

        //update selectedAll line
        var selectAll = wrapper.find('#selectAll');
        var sLabel = selectAll.closest("label");

        if (wrapper.find("input:checkbox").not(':checked').not(selectAll).length == 0) {
            if (!sLabel.hasClass('selected')) {
                sLabel.addClass('selected');
                sLabel.find('input:checkbox').prop('checked', true);
            }
        } else {
            if (sLabel.hasClass('selected')) {
                sLabel.removeClass('selected');
                sLabel.find('input:checkbox').prop('checked', false);
            }
        }
    }
}

function jtxSimpleSelectListItemClick() {

    var optionClicked = $(this).closest("label");
    var wrapper = optionClicked.closest(".jtxSimpleSelectList");

    if (optionClicked.has("input[type=radio]").length > 0) {
        wrapper.find("label").removeClass("selected");
        optionClicked.addClass("selected");
    } else {

        if (optionClicked.find("input:checkbox").is(':checked')) {
            //console.log(optionClicked)
            optionClicked.addClass("selected");
        } else {
            optionClicked.removeClass("selected");
        }

        //update buttonStatus if dropdown
        if (wrapper.parents('.jtxDropDown').length > 0) {
            if (wrapper.find("input:checkbox:checked").length > 0) {
                wrapper.parents('.jtxDropDown').addClass('selected');
                wrapper.parents('.jtxDropDown').find('.jtxBtn').addClass('selected');
            } else {
                wrapper.parents('.jtxDropDown').removeClass('selected');
                wrapper.parents('.jtxDropDown').find('.jtxBtn').removeClass('selected');
            }
        }

        //update selectedAll line
        var selectAll = wrapper.find('#selectAll');
        var sLabel = selectAll.closest("label");

        if (wrapper.find("input:checkbox").not(':checked').not(selectAll).length == 0) {
            if (!sLabel.hasClass('selected')) {
                sLabel.addClass('selected');
                sLabel.find('input:checkbox').prop('checked', true);
            }
        } else {
            if (sLabel.hasClass('selected')) {
                sLabel.removeClass('selected');
                sLabel.find('input:checkbox').prop('checked', false);
            }
        }
    }
}


function jtxSelectListSelectAllClick() {
    var optionClicked = $(this).closest("label");
    var wrapper = optionClicked.closest(".jtxSelectList");
    var checkBox = optionClicked.find("input:checkbox");
    //only checkboxes
    if (!optionClicked.has("input[type=radio]").length > 0) {
        if (checkBox.is(':checked')) {
            wrapper.find('input:checkbox').not(':checked').not(checkBox).prop('checked', true).change();
        } else {
            wrapper.find('input:checkbox:checked').not(checkBox).prop('checked', false).change();
        }
    }
}
var scrollSection;
var firedScrollEvents = [];

$(function () {
    $(document).on('click', "a.openPop", openPopup);
    $(document).on('click', "#LudoFitLandingWrapper .section.device .deviceOption", deviceSelect);
    $(document).on('click', "#LudoFitLandingWrapper .section.buttons .jtxBtn.next", nextClick);
    $(document).on('click', "#LudoFitLandingWrapper .mainDownloadButton ", downloadClickScroll);
    $(document).on('submit', "#LudoFitLandingWrapper .emailPreferences form", submitEmailPreferences);
    $(document).on('click', "#LudoFitLandingWrapper .section.testimonials .scrollBtn", testimonialScroll);
    $(document).on('click', "#LudoFitLandingWrapper .section.testimonials .dots a", testimonialScrollDot);
    $(document).on('click', "#LudoFitLandingWrapper .section.faq a.question", FAQClick);
    $(document).on('click', "#LudoFitLandingWrapper .section.download .appStoreBtn, #LudoFitLandingWrapper .section.download .mainDownloadButton,#LudoFitFindFilePop .mainDownloadButton", DownloadClick);

    $("#mainContent").bind('scroll', WindowScroll);

    //detect click on video iframe
    var monitor = setInterval(function () {
        var elem = document.activeElement;
        if (elem && elem.tagName == 'IFRAME' && $(elem).hasClass('sproutvideo-player')) {
            clearInterval(monitor);
            VideoClick();
        }
    }, 100);

    //build list for scroll tracking
    scrollSections = $('.scrollTrack').map(function () {
        var eventName = $(this).data("eventname");
        if (eventName.length) {
            return { name: eventName, top: $(this).offset().top }
        }
    });

});

function PlaceFindFilePop() {
    var btnTop = $('.step.two .jtxBtn').offset().top - ($('#LudoFitFindFilePop.iframe').width() / 2) + 100;
    var left = ($('#LudoFitLandingWrapper').width() - $('#LudoFitFindFilePop.iframe').width()) / 2;
    $('#LudoFitFindFilePop.iframe').css("top", btnTop + "px").css("left", left + "px").css("position", "fixed");
}

function WindowScroll(event) {
    clearTimeout($.data(this, 'scrollTimer'));
    $.data(this, 'scrollTimer', setTimeout(function () {
        WindowDoneScroll();
    }, 250));
}

function WindowDoneScroll() {
    var top = $("#mainContent").offset().top;
    var scrollTop = $("#mainContent").scrollTop();
    var height = $("#mainContent").height();
    var scrollBottom = top + scrollTop + (height / 2);

    var toFire = scrollSections.map(function () {
        if (scrollBottom > $(this)[0].top && !(firedScrollEvents.indexOf($(this)[0].name) > -1)) {
            return $(this)[0].name;
        }
    });

    $(toFire).each(function (item) {
        if (typeof gtag === "function") {
            gtag('event', 'ScrollSection_' + toFire[item], {});
        }
        firedScrollEvents.push(toFire[item]);
    });
}


function DownloadClick(event) {
    if (typeof gtag === "function") {
        var which = $(this).data('eventname');
        gtag('event', 'Download_' + which, {});
    }
}

function VideoClick(event) {
    if (typeof gtag === "function") {
        gtag('event', 'VideoClick', {});
    }
}

function FAQClick(event) {
    event.preventDefault();
    var isOpen = $(this).parents('.accordion').hasClass('open');

    if (isOpen) {
        $(this).parents('.accordion').removeClass('open');
        $(this).parents('.accordion').find('.answer').slideUp();
    } else {
        $(this).parents('.accordion').addClass('open');
        $(this).parents('.accordion').find('.answer').slideDown();
    }
}

function testimonialScrollDot(event) {
    event.preventDefault();

    var next = $(this).index();

    $('.sliderContent').find('.sliderItem').removeClass('selected');
    $($('.sliderContent').find('.sliderItem')[next]).addClass('selected');
    $('.slider').find('.dots a').removeClass('selected');
    $($('.slider').find('.dots a')[next]).addClass('selected');

}

function testimonialScroll(event) {
    event.preventDefault();
    var isUp = $(this).hasClass('right');
    var current = $('.sliderContent').find('.sliderItem.selected').index();
    var total = $('.scrollBtn.right').parents('.slider').find('.sliderItem').length;

    //console.log(current);
    //console.log(total);

    var next = current;
    if (isUp) {
        next++;
    } else {
        next--;
    }
    if (next >= total) {
        next = 0;
    }
    if (next < 0) {
        next = total - 1;
    }

    //console.log(next);

    $('.sliderContent').find('.sliderItem').removeClass('selected');
    $($('.sliderContent').find('.sliderItem')[next]).addClass('selected');
    $('.slider').find('.dots a').removeClass('selected');
    $($('.slider').find('.dots a')[next]).addClass('selected');

}


function submitEmailPreferences(event) {
    event.preventDefault();
    var form = $(this).closest('form');
    submitBootPopupForm("submit", form);
}

function downloadClickScroll(event) {
    //scroll to step 1
    var frameTop = $('#mainContent').offset().top;
    var scrollTop = $('#mainContent').scrollTop();
    var elementTop = $('.title.howTo').offset().top;

    //scroll then check if we need to show the savecontinue button
    $('#mainContent').animate({
        scrollTop: elementTop + scrollTop - frameTop - 20
    }, 500);
}

function openPopup(event) {
    event.preventDefault();

    if (!$("#modal-holder").is(":visible")) {
        $("#modal-holder").modal();
    }

    $("#modal-holder .modal-footer button, #modal-holder .modal-header button, #modal-holder .modal-footer a").each(function () {

        var button = $(this);
        var buttonValue = button.attr("value");
        if (buttonValue == null || buttonValue == "cancel" || buttonValue == "download") {
            button.click(function () {
                $("#modal-holder").modal('hide');
                if (buttonValue != "download") {
                    return false;
                } else {
                    return true;
                }
            });
        }
    });


    if (typeof gtag === "function") {
        var whichBtn = $(this).data('eventname');
        var whichPop = $('#modal-holder').data('eventname');

        gtag('event', 'OpenPopup_' + whichPop + "_" + whichBtn, {});
    }


    PlaceFindFilePop();
}


function deviceSelect(event) {
    event.preventDefault();

    //highlight
    $(this).parents('.deviceOptions').find('.deviceOption').removeClass('selected');
    $(this).addClass('selected');

    //change url
    var button = $('#LudoFitLandingWrapper .buttonWrapper .jtxBtn.next');
    var href = button.attr('href');
    var device = $(this).data('device')

    //param is always at the end
    var ind = href.indexOf('&device=');
    //cut off param
    if (ind > 0) {
        href = href.substring(0, ind);
    }
    //could be no &
    ind = href.indexOf('device=');
    //cut off param
    if (ind > 0) {
        href = href.substring(0, ind);
    }


    if (href.includes('?')) {
        href = href + "&device=" + device;
    } else {
        href = href + "?device=" + device;
    }

    //set new link
    button.attr('href', href);
    //popup link
    $('#LudoFitTabletStandPop .jtxBtn').attr('href', href);

    //enable button
    button.removeClass('disabled');
    button.addClass('enabled');

    //scroll to buttons if zoomed
    var frameTop = $('#mainContent').offset().top;
    var scrollTop = $('#mainContent').scrollTop();
    var elementTop = button.offset().top;

    //scroll to the button (will be the bottom of the page)
    $('#mainContent').animate({
        scrollTop: elementTop + scrollTop - frameTop - 20
    }, 500);
}


function nextClick(event) {
    if ($(this).hasClass('disabled')) {
        event.preventDefault();
    } else {
        //show tablet stand 
        //if ($('.deviceOption.ipad').hasClass('selected')) {
        //    openPopup(event);
        //}
    }
}

var messageClearTimeout;
var messageShowTimeout;

function displayMessage(message, messageType, actionText, actionCallback) {
    var delay = 0;
    var duplicateMessage = false;

    //clear any old messages and delay if needed for animation
    if ($("#notification .content .text").html().length > 0) {
        //console.log('already msg')
        if ($("#notification .content .text").html() == message) {
            //console.log('duplicate')
            duplicateMessage = true;
        } else {
            clearMessages(true);
            delay = 500;
        }
    }

    if (!duplicateMessage) {
        clearTimeout(messageShowTimeout);
        messageShowTimeout = setTimeout(function () {
            $("#notification").attr('data-messagetype', messageType);
            $("#notification .content .text").html(
                //'<div class="message">' + messageType + '</div>' +
                //'<div class="text">' + message + '</div>');
                message);

            if (actionText) {
                $("#notification .content .action").off('click');
                $("#notification .content .action").on('click',
                    function () {
                        $("#notification .content .action").off('click');
                        clearMessages();
                        actionCallback();
                    });
                $("#notification .content .action").html(actionText);
            } else {
                $("#notification .content .action").off('click');
                $("#notification .content .action").html("");
            }

            //animated success icon
            if (messageType == "Success") {
                //var img = document.createElement('img');
                //img.src = "/Content/images/successThumbsUp.gif?p" + Math.random();

                //$("#notification .content .icon").css({ backgroundImage: "url(" + img.src + ")" });
                $("#notification .content .icon").css({
                    backgroundImage: "url(/Content/images/successThumbsUp.gif?p" + Math.random() + ")"
                });
                /* Once the image has loaded, set it as the background-image */
                //$(img).load(function () {
                //});
            } else if (messageType == "Error" || messageType == "Warning") {
                $("#notification .content .icon").css({
                    backgroundImage: "url(/Content/images/exclamation.png?p" + Math.random() + ")"
                });
                //var img = document.createElement('img');
                //img.src = "/Content/images/exclamation.png?p" + Math.random();

                //* Once the image has loaded, set it as the background-image */
                //$(img).load(function () {
                //    $("#notification .content .icon").css({ backgroundImage: "url(" + img.src + ")" });
                //});
            } else {
                $("#notification .content .icon").css({ backgroundImage: 'none' });
            }
            displayMessages();
        }, delay);
    }
}

function displayMessages() {
    if ($("#notification .content .text").html().length > 0) {
        $("#notification").fadeIn(500, function () {
            messageClearTimeout = setTimeout(function () {
                //console.log('Delay hide');
                clearMessages();
            }, 4000);
            $("#notification").click(function () {
                //console.log('click hide');
                clearTimeout(messageClearTimeout);
                clearMessages();
            });
        });
    } else {
        $("#notification").hide();
    }
}

function clearMessages(quick) {
    //default to faluse if not set
    quick = typeof quick !== 'undefined' ? quick : false;

    //console.log('clear')
    clearTimeout(messageClearTimeout);
    var delay = 500;
    if (quick) {
        delay = 100;
    }

    $("#notification").fadeOut(delay, function () {
        $("#notification").attr('data-messagetype', '');
        $("#notification .content .text").empty();
    });
}

function handleAjaxMessages() {
    $(document).ajaxSuccess(function (event, request) {
        checkAndHandleMessageFromHeader(request);
    });
}

function checkAndHandleMessageFromHeader(request) {

    var msg = request.getResponseHeader('X-Message');
    if (msg) {
        displayMessage(msg, request.getResponseHeader('X-Message-Type'));
    }
}
//for newsfeed
var isLoading = false;

//for inactivity checker
var prevloggedin = false;

//for site Status checker
var origStatus;

$(function () {

    //Start login status checker
    LoginTimeout();

    var ci = $("meta[name='accept-language']").attr("content");
    Globalize.culture(ci);
    //console.log(Globalize.culture().language) // "fr-FR"

    //for notifications
    if (typeof (handleAjaxMessages) == "function") {
        handleAjaxMessages();
        displayMessages();
    }

    //Listeners
    addListeners();

    $.fn.visible = function (partial) {
        try {
            var $t = $(this),
                $w = $(window),
                viewTop = $w.scrollTop(),
                viewBottom = viewTop + $w.height(),
                _top = $t.offset().top,
                _bottom = _top + $t.height(),
                compareTop = partial === true ? _bottom : _top,
                compareBottom = partial === true ? _top : _bottom;

            return ((compareBottom <= viewBottom) && (compareTop >= viewTop));
        } catch (e) {
            return false;
        }
    };

    $.fn.extend({
        // When adding/removing a line in a form, recalculate the right index for all inputs
        reinitializeLineIndex: function (namePrefix) {
            //console.log('reinit')

            // need to loop twice, if we do the driect rename once, it messes up radio buttons as the name is the same for a split second [ie 2 level 0's before the second is renamed to 1]

            // reindex and add an 'a'
            $(this).each(function (index) {
                $(this).find("select,input,label").each(function () {
                    var searchName = new RegExp(namePrefix + '[[0-9A-Z]{0,4}\]', 'gi');
                    var searchId = new RegExp(namePrefix + '_[0-9A-Z]{0,4}', 'gi');
                    var id = $(this).attr("id");
                    var name = $(this).attr("name");
                    var labelFor = $(this).attr("for");
                    if (name) {
                        $(this).attr("name", $(this).attr("name").replace(searchName, namePrefix + "a[" + index + "]"));
                    }
                    if (id) {
                        $(this).attr("id", $(this).attr("id").replace(searchId, namePrefix + "a_" + index));
                    }
                    if (labelFor) {
                        $(this).attr("for", $(this).attr("for").replace(searchId, namePrefix + "a_" + index));
                    }
                });

                $(this).find(".sorter .value").html(index + 1);
            });

            // reindex and remove the 'a'
            $(this).each(function (index) {
                $(this).find("select,input,label").each(function () {
                    var searchName = new RegExp(namePrefix + 'a[[0-9A-Z]{0,4}\]', 'gi');
                    var searchId = new RegExp(namePrefix + 'a_[0-9A-Z]{0,4}', 'gi');
                    var id = $(this).attr("id");
                    var name = $(this).attr("name");
                    var labelFor = $(this).attr("for");

                    if (name) {
                        $(this).attr("name", $(this).attr("name").replace(searchName, namePrefix + "[" + index + "]"));
                    }
                    if (id) {
                        $(this).attr("id", $(this).attr("id").replace(searchId, namePrefix + "_" + index));
                    }
                    if (labelFor) {
                        $(this).attr("for", $(this).attr("for").replace(searchId, namePrefix + "_" + index));
                    }
                });

                $(this).find(".sorter .value").html(index + 1);
            });
        }
    });

    if (typeof initUIFeatures === "function") {
        initUIFeatures();
    }

    //preload
    (new Image()).src = '/content/images/portal_spinner_50.gif';

    //polyfill for IE
    if (!String.prototype.startsWith) {
        String.prototype.startsWith = function (searchString, position) {
            position = position || 0;
            return this.indexOf(searchString, position) === position;
        };
    }
});

function addListeners() {
    $(document).on('click', "a.disabled", killLink); //kill links when disabled
    $(document).on('change', '#patientSharingSetting .shareTo select', shareChanged); //patient sharing
    $(document).on('click', '#patientSharingSetting .remove, #patientSharingSetting .reenable', toggleSharedUser); //patient sharing remove user
    $(document).on('click', '#patientSharingSetting .add', addSharedUser); //patient sharing remove user
    $(document).on('change', '#PatientLogin,#IndependentLogin', togglePatientLogin); //pateient create form show/hide email
    $(document).on('change', '#RegisterNow', toggleEmail); //pateient create form show/hide email
    $(document).on('change', '#TrialPeriod', toggleTrial); //group create form show/hide trial
    $(document).on('change', '#SubscriptionsEnabled, #SubscriptionSettings_SubscriptionsEnabled', toggleLudoFitSubscriptionEnabled); //group create form show/hide user trial
    $(document).on('change', '#LudoFitTrialDurationOverride, #SubscriptionSettings_TrialDurationOverride', toggleLudoFitTrialDuration); //group create form show/hide user trial
    $(document).on('change', '#UseCurrentLoginSettings', toggleLoginSettings); //user enable independent login form show/hide invite send
    $(document).on('change', '#IsDistributor', toggleSubLimit); //group create form show/hide trial
    $(document).on('click', ".editInLine a.editLink", editInLine); //inline editing field
    $(document).on('click', "#profile .showMenu", showProfileMenu); //various slide down menus
    $(document).on('click', ".actionAndReplace input", actionAndReplace); //currently only for clinic-wide sharing setting  TODO Update group edit viewmodels to do this as well
    $(document).on('click', ".waiver .checkbox.inactive", highlightWarning); //bring attention to waring if click on the inactive waiver
    $(".waiver .text").on('scroll', reachedWaiverBottom); //activate waiver accept once read
    $(document).on('click', ".tableList .submitForm", tableListSubmitForm); //for inline form submit
    $(document).on('click', ".tableList div.regularLink", regularButtonLink); //for inline buttons inside a different link
    $(document).on('click', ".tableList .element .showMenu", tableListMenu); //for inline show menu inside a different link
    $(document).on('click', ".tableList .headerBar .showMenu", tableListTopMenu); //for  show menu at the top of a tablelist
    $(document).on('click', "a.showMenu", showMenu); //various slide down menus
    $(document).on('click', ".feedbackType label", feedbackTypeClick); //change type of feedback
    $(document).on('click', "#siteStatus button.reset", siteStatusResetClick); //change type of feedback
    $(document).on('contextmenu', "#videoPopup", function () { return false; }); //prevent right click for video player
    $(document).on('click', "a.loadInTarget, button.loadInTarget", loadInTarget); //ajax load in page
    $(document).on('keyup', "textarea.autosize", textareaAutosize); //autosize textarea height
    $(document).on('mousedown', ".dropdownMultiSelectInput", multiSelectOpen); //multi open
    $(document).on('change', ".dropdownMultiSelectOptions input[type='checkbox']", multiSelectChange); //multi open
    $(document).on('click', "#ModuleTypeInfo .typeMenu a", moduleTypeInfoMenuClick); //ajax load in page
    $(document).on('change', '#IsFacilityReportSubscribed', toggleDORSubscribeEmail); //pateient create form show/hide email
    $(document).on('change', '#ReportGrouping', toggleReportGroupingGroupWarning); //notify of group change
    $(document).on('click', '#FacilityReportAdminSubscribe .jtxDropDown .jtxBtn', reportSubscribeExpandDropdown);
    $(document).on('click', '#FacilityReportAdminSubscribe .unsubscribeAll', reportUnsubscribeAll);
    $(document).on('focus', '.focusable', focusableFocus);
    $(document).on('keydown', '.focusable', focusableKeydown);
    $(document).on('change', '#TwoFactorEnabled, #TwoFactor_TwoFactorEnabled', toggleTwoFactor); //TwoFactorEnabled form show/hide phone
    $(document).on('submit', 'form.CompleteRegistration', createSubmit); //prevent 

}


//prevent multi-submit
function createSubmit(event) {
    //console.log('HELLO');
    if ($(this).valid()) {
        showLoading();
    } else {
        event.preventDefault();
    }
}

function tableListTopMenu(event) {
    //console.log('topMenu');

    event.preventDefault();

    var target = $(this).parent().find('.showMenu');
    var menu = $(this).next();
    //console.log($('.topSection div.elementDropMenu').is(":visible"))
    if (menu.is(":visible")) {
        //console.log('close')
        menu.slideUp(200).addClass("noDisplay");
        $(this).removeClass('open');
    }
    else {
        //console.log('show')
        $('#searchMask:hidden').show();
        //menu.width(target.width() - 4);//for 2px border
        var width = menu.width(); //do this here as some animation stuff moves it around

        menu.removeClass("noDisplay").css({ left: target.offset().left + (target.width()) - (menu.width()), top: target.offset().top + target.height() + 20 }).hide().show("slide", { direction: "up" }, 200);

        //menu.removeClass("noDisplay").css({ left: target.offset().left - width - 20, top: target.offset().top + 2 }).hide().show("slide", { direction: "right" }, 250);
        //menu.removeClass("noDisplay").css({ left: target.offset().left - width - 20, top: target.offset().top + 2 }).hide().show("fold", { size: 50, direction: "left" }, 250);
        $(this).addClass('open');
    }

    return false;
}

function tableListMenu(event) {
    event.preventDefault();

    var target = $(this).parent().find('.showMenu');
    var menu = $(this).next();


    if (menu.is(":visible")) {
        menu.slideUp(200).addClass("noDisplay");
        $(this).removeClass('open');
    }
    else {
        //console.log('show')
        $('#searchMask:hidden').show();
        var pageHeight = $(window).height();

        //menu.width(target.width() - 4);//for 2px border
        //menu.slideDown(200).removeClass("noDisplay").css({ left: target.offset().left + (target.width() / 2) - (menu.width() / 2), top: target.offset().top + target.height() + 10 });
        var width = menu.width(); //do this here as some animation stuff moves it around
        var height = menu.height();

        var top = target.offset().top + 2;
        if (top + menu.height() > pageHeight) {
            top = pageHeight - menu.height() - 10;
        }


        menu.removeClass("noDisplay").css({ left: target.offset().left - width - 20, top: top }).hide().show("slide", { direction: "right" }, 250);
        //menu.removeClass("noDisplay").css({ left: target.offset().left - width - 20, top: target.offset().top + 2 }).hide().show("fold", { size: 50, direction: "left" }, 250);
        $(this).addClass('open');
    }

    return false;
}

function focusableFocus() {
    $('.focusable').removeClass('focused');
    $(this).addClass('focused');
}

function focusableKeydown(event) {
    //40=down, 38=up, 9=tab, 13=enter, 37=left,39=right, 27=esc, 8=backspace
    //console.log(event.which)

    $('.focused').focus();

    //enter
    if (event.which == 13) {
        $('.focused').trigger('click');
    }

    //close date picker
    $('.hasDatepicker').datepicker("hide");

    //select next
    if (event.which == 40 || event.which == 39 || (event.which == 9 && !event.shiftKey)) {

        if (!(event.which == 39 && ($('.focused').is(':text') || $('.focused').is(':password')))) {
            focusNext();
            event.preventDefault();
        } else {
            var pos = $('.focused')[0].selectionStart;
            var length = $('.focused').val().length
            if (pos == length || !$('.focused').is(':focus')) {
                focusNext();
                event.preventDefault();
            }
        }
    }

    //select previous
    if (event.which == 38 || event.which == 37 || (event.which == 9 && event.shiftKey)) {

        if (!(event.which == 37 && ($('.focused').is(':text') || $('.focused').is(':password')))) {
            focusPrevious();
            event.preventDefault();
        } else {
            var pos = $('.focused')[0].selectionStart;
            if (pos == 0) {
                focusPrevious();
                event.preventDefault();
            }
        }
    }

    //Back/cancel
    if (event.which == 27) {
        event.preventDefault();
        focusBack();
        return false;
    }
}

function focusBack() {
    var current = $('.focused');
    var isBootPopup = current.parents('.modal-dialog:visible').length > 0;

    if (isBootPopup) {
        //close popup
        $("#modal-holder").modal('hide');
    } else {
        //click "cancel" if exists
        $('.focusable:visible.cancel').trigger('click');
    }
}

function focusNext() {
    var current = $('.focused');
    var index = 0;
    var length = 0;
    var isBootPopup = current.parents('.modal-dialog:visible').length > 0;

    //only rotate through popup contents [the stuff underneath is sill "visible"]
    if (isBootPopup) {
        index = $('.modal-dialog .focusable:visible').index(current);
        length = $('.modal-dialog .focusable:visible').length;
    } else {
        index = $('.focusable:visible').index(current);
        length = $('.focusable:visible').length;
    }

    var next = index + 1;
    if (next == length) {
        next = 0;
    }
    if (isBootPopup) {
        $('.modal-dialog .focusable:visible')[next].focus();

    } else {
        $('.focusable:visible')[next].focus();
    }

}


function focusPrevious() {

    var current = $('.focused');
    var index = 0;
    var length = 0;
    var isBootPopup = current.parents('.modal-dialog:visible').length > 0;

    //only rotate through popup contents [the stuff underneath is sill "visible"]
    if (isBootPopup) {
        index = $('.modal-dialog .focusable:visible').index(current);
        length = $('.modal-dialog .focusable:visible').length;
    } else {
        index = $('.focusable:visible').index(current);
        length = $('.focusable:visible').length;
    }

    var next = index - 1;
    if (next < 0) {
        next = length - 1;
    }
    if (isBootPopup) {
        $('.modal-dialog .focusable:visible')[next].focus();
    } else {
        $('.focusable:visible')[next].focus();
    }

}


function isIE() {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))  // If Internet Explorer, return version number
    {
        return true;
    }
    else  // If another browser, return 0
    {
        return false;
    }
}

function showMessage(event) {
    var msg = $(this).data('message');
    displayMessage(msg, "Error");
    event.preventDefault();
    return false;
}

function multiSelectChange() {
    $(this).parents('.option').removeClass('selected');
    if ($(this).is(':checked')) {
        $(this).parents('.option').addClass('selected');
    } else {
        $(this).parents('.option').removeClass('selected');
    }
}

function multiSelectOpen(event) {

    var options = $(this).parent().find('.dropdownMultiSelectOptions');

    if ($(options).is(':visible')) {
        return true;
    } else {
        //clear event from a prev open without a close
        $(document).off('click.multiselect');

        //special behavior for sessionnotes
        //if its a question that is not selected, kill click and scroll to the question
        var question = $(this).closest('.question');

        if (question.length > 0) {
            //if clicked question is not selected, scroll to it
            if (!question.hasClass('selected')) {
                scrollTo(question);
                event.preventDefault();
                return false;
            } else {
                $(options).slideDown();
            }
        } else {
            //if not session notes, we need to position it
            var target = $(this);
            if ($(this).css('float') == 'right') {
                $(options).slideDown(200).removeClass("noDisplay").css({ right: 150, top: target.height() + 8 });
            }
        }

        setTimeout(function () {
            //add outside click listener, need to delay as this current event triggers it
            $(document).off('click.multiselect');
            $(document).on('click.multiselect', function (e) {
                if (!$(e.target).closest('.dropdownMultiSelectOptions').length && !$(e.target).closest('.typeahead .dropdownMultiSelectInput').length) {
                    if ($('.dropdownMultiSelectOptions').is(":visible")) {
                        $('.dropdownMultiSelectOptions').slideUp();
                        $(document).off('click.multiselect');
                        //flip arrow if applciable
                        $(this).find('.up').hide();
                        $(this).find('.down').show();
                    }
                }
            });
        }, 500);

        //flip arrow if applciable
        $(this).find('.up').show();
        $(this).find('.down').hide();

        //if not text area, kill normal flow preventing selectbox from droping down
        if (!$(this).find('textarea').length > 0) {
            event.preventDefault();
            return false;
        } else {
            //trigger event to condition list
            $(this).find('textarea').trigger('keyup');
            //$(this).find('textarea').focus();
        }
        return true;
    }
}

function textareaAutosize() {
    var minHeight = 70;

    if ($(this).closest('.typeahead').length > 0) {
        minHeight = 40;
    }

    $(this).height(minHeight);
    //grow
    if ($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
        while ($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
            $(this).height($(this).height() + 1);
        };
    }
}

function loadInTarget() {

    if ($(this).hasClass('disabled')) {
        return false;
    }

    var target = $(this).data("target");
    var replace = $(this).data("replace");

    var link = $(this);
    var url = link.find("a").attr("href");
    if (!url) {
        url = link.attr("href");
    }

    showLoading();

    $.ajax({
        type: "GET",
        url: url,
        success: function (data) {
            if (replace) {
                $(target).replaceWith(data);
            } else {
                //console.log($(target));
                $(target).html(data);
            }
            // apply print block for ios 
            if (isIOS()) {
                $('.notIpad').hide();
                if (!$('.exportLink').attr('href').includes('canPrint')) {
                    $('.exportLink').attr('href', $('.exportLink').attr('href') + '&canPrint=false')
                }

                // apply print block for ios 
                $('#sessionHistory .top a.openBootPopup').each(function () {
                    if (!($(this).attr('href').includes('canPrint'))) {
                        $(this).attr('href', $(this).attr('href') + '&canPrint=false')
                    }
                });
            }
        }, error: function (jqXHR) {
            handleError(jqXHR);
        },
        complete: function () {
            hideLoading();
        }
    });

    return false;
}


function tableListSubmitForm() {
    //showLoading();
    var form = $(this).parents('.element').find('form');
    form.submit();
}


function regularButtonLink() {

    //showLoading();
    var url = $(this).attr("href");
    window.location = url;
    return false;
}
//#endregion

//#region session timer
function TrackPatientTime(patientId) {
    $.ajax(
        {
            url: '/heartbeat/tracktime',
            data: { timestamp: new Date().getTime(), id: patientId },
            complete: function (data) {
                setTimeout(TrackPatientTime, 60000, patientId);
            }
        });
}

function TrackGroupTherapyTime() {
    $.ajax(
        {
            url: '/heartbeat/tracktime',
            data: { timestamp: new Date().getTime(), isGroup: true },
            complete: function (data) {
                setTimeout(TrackGroupTherapyTime, 60000);
            }
        });
}

function StartSessionTimer(offset, starttime) {
    if (!starttime) {
        starttime = (new Date()).valueOf();
    }
    var obj = {};
    obj._milliseconds = (new Date()).valueOf() - starttime + offset / 10000;
    obj.milliseconds = obj._milliseconds % 1000;
    obj._seconds = (obj._milliseconds - obj.milliseconds) / 1000;
    obj.seconds = obj._seconds % 60;
    obj._minutes = (obj._seconds - obj.seconds) / 60;
    obj.minutes = obj._minutes % 60;
    obj._hours = (obj._minutes - obj.minutes) / 60;
    obj.hours = obj._hours % 24;

    var time = obj.seconds;


    if (obj.seconds < 10) {
        time = 0 + "" + time;
    }

    time = obj.minutes + ":" + time;


    if (obj.minutes < 10) {
        time = 0 + "" + time;
    }

    if (obj.hours > 0) {
        time = obj.hours + ":" + time;
    }

    $('#patientTimer .time').html(time);
    setTimeout(StartSessionTimer, 1000, offset, starttime);
}
//#endregion

function LoginTimeout() {
    $.ajax(
        {
            url: '/heartbeat/amiloggedin',
            data: { timestamp: new Date().getTime() },
            success: function (data) {
                if (data == "True") {
                    prevloggedin = true;
                } else {
                    //require a true->false to distingush pages that require login [ie don't redirect on login page etc]
                    if (prevloggedin == true) {
                        window.location.href = "/" + Globalize.culture().language + "/account/timedout";
                    }
                }
            },
            complete: function (data, textStatus) {

                //If we go from any other status to a 503 (maintenance) then reload the page to hit the maintenance msg
                if (origStatus == undefined) {
                    origStatus = data.status;
                }
                if (data.status == 503 && origStatus != 503) {
                    window.location.reload();
                }
                setTimeout(LoginTimeout, 60000);
            }
        });

}


function ReloadAfterDelay(delay) {
    setTimeout(function () {
        window.location.reload();
    }, delay);


}

function killLink(event) {
    event.preventDefault();
    return false;
}

function moduleTypeInfoMenuClick(event) {
    event.preventDefault();
    var url = $(this).data('targettab');
    $(this).parent().children().removeClass('selected');
    $(this).addClass('selected');
    $('#' + url).parent().children().removeClass('selected');
    $('#' + url).addClass('selected');
}

function siteStatusResetClick(event) {
    event.preventDefault();
    $('#NotificationMessageTextEn').val($('#NotificationMessageDefaultEn').val());
    $('#NotificationMessageTextFr').val($('#NotificationMessageDefaultFr').val());
}

function feedbackTypeClick() {
    $(".feedbackType label").removeClass("selected");
    $(this).addClass("selected");
}

function showLoading() {
    $(".ui-dialog").mask("Loading...");
    $("body").mask("Loading...");
}

function hideLoading() {
    $("#patientInfo").unmask();
    $("#container").unmask();
    $(".ui-dialog").unmask();
    $("#wrapper").unmask();
    $("#modal-holder").unmask();
    $("body").unmask();
}

function loginBreakout() {

    var index = $(".loginbody").index();
    if (index < 0) {
        location.reload();
    }
}

function maintenanceBreakout() {
    index = $(".maintenancebody").index();
    if (index < 0) {
        location.reload();
    }
}

function errorBreakout() {
    index = $(".errorbody").index();
    if (index < 0) {
        location.reload();
    }
}

//#region Patient Sharing
function shareChanged() {
    if ($(this).val() != "") {
        $('#patientSharingSetting .shareTo .buttonGroup').show();
    } else {
        $('#patientSharingSetting .shareTo .buttonGroup').hide();
    }
    //default email to false
    $('#sendEmail').attr('checked', false);
}

function addSharedUser() {
    var id = $('#AvailableClinicians').val();
    var name = $('#AvailableClinicians option:selected').text();
    var sendEmail = $('.shareTo #sendEmail').is(':checked');

    var cloned = $('#patientSharingSetting .element').last().clone();

    $('#patientSharingSetting .list').append(cloned);

    cloned.find("input[id*='Id']").val(id);
    cloned.find("input[id*='IsMe']").val("False");
    cloned.find("input[id*='SendEmail']").val(sendEmail);
    cloned.find('.details .center').html(name);

    if (cloned.find("input[id*='Remove']").val() == "True") {
        toggleSharedUserElement(cloned);
    }

    //update index
    $("#patientSharingSetting .element").each(function (index) {
        var searchName = new RegExp('SharedClinicians[[0-9A-Z]{0,4}\]', 'gi');
        var searchId = new RegExp('SharedClinicians_[0-9A-Z]{0,4}', 'gi');
        $(this).find('input').each(function () {
            var idEl = $(this).attr("id");
            var nameEl = $(this).attr("name");
            if (nameEl) {
                $(this).attr("name", $(this).attr("name").replace(searchName, "SharedClinicians[" + index + "]"));
            }
            if (idEl) {
                $(this).attr("id", $(this).attr("id").replace(searchId, "SharedClinicians_" + index));
            }
        });
    });

    // remove from dropdown and fire change handler
    $('#AvailableClinicians option:selected').remove();
    $('#AvailableClinicians').change();

    //validate last patient count
    checkLastClinician();
}

function toggleSharedUser(event) {
    event.preventDefault();
    var item = $(this).parents('.element');
    toggleSharedUserElement(item);
    return false;
}


function toggleSharedUserElement(item) {
    //dont remove last user
    if (item.find('.remove:visible').hasClass('disabled')) {
        return;
    }

    var remove = item.find("input[id*='Remove']");
    var isMe = item.find("input[id*='IsMe']");

    //if removing, deactivate row and show add btn
    if (remove.val() == "False") {
        //show warning if your removing yourself
        if (isMe.val() == "True") {
            $('#patientSharingSetting .warning').removeClass('noDisplay');
        }
        remove.val("True");
        item.find('.icon').addClass("deactivated");
        item.find('.details').addClass("deactivated");
        item.find('.remove').addClass('noDisplay');
        item.find('.reenable').removeClass('noDisplay');
        //if adding, reactivate row and show remove btn
    } else {
        // hide warning if re-adding youself
        if (isMe.val() == "True") {
            $('#patientSharingSetting .warning').addClass('noDisplay');
        }
        remove.val("False");
        item.find('.icon').removeClass("deactivated");
        item.find('.details').removeClass("deactivated");
        item.find('.remove').removeClass('noDisplay');
        item.find('.reenable').addClass('noDisplay');
    }

    checkLastClinician()
}

function checkLastClinician() {
    // if only 1 user left, disable the remove btn
    if ($('#patientSharingSetting .remove:visible').length <= 1) {
        $('#patientSharingSetting .remove').addClass('disabled');
    } else {
        $('#patientSharingSetting .remove').removeClass('disabled');
    }
}
//#endregion


function togglePatientLogin() {

    if ($(this).val() == "True") {
        $(".placeHolder").slideDown(200);
        //set button text appropriately
        $('#RegisterNow').trigger("change");
    }
    else {
        $(".placeHolder").slideUp(200);
        // add button text
        $(".addClientSubmit").removeClass('noDisplay');
        $(".registerNowSubmit").addClass('noDisplay');
    }
}

function toggleEmail() {

    //console.log($(this).val());

    if ($(this).val() == "True") {
        $(".emailInput").slideUp(200);
        $(".addClientSubmit").addClass('noDisplay');
        $(".registerNowSubmit").removeClass('noDisplay');
    } else {
        $(".emailInput").slideDown(200);
        $(".addClientSubmit").removeClass('noDisplay');
        $(".registerNowSubmit").addClass('noDisplay');
    }

}

function toggleTwoFactor() {
    //console.log($(this).val());
    if ($(this).val() == "True") {
        $(".twoFactorField").removeClass('disabled');
        $(".twoFactorField input,.twoFactorField select").removeAttr('disabled');
    } else {
        $(".twoFactorField").addClass('disabled');;
        $(".twoFactorField input,.twoFactorField select").attr('disabled', 'True');;
    }
}
function toggleDORSubscribeEmail() {
    //console.log($(this).val());
    if ($(this).val() == "True") {
        $(".emailDOR").slideDown(200);
    } else {
        $(".emailDOR").slideUp(200);
    }
}

function toggleReportGroupingGroupWarning() {
    if ($(this).find("option:selected").text().includes("[SNF]") || $(this).val() == "Other") {
        $(".SNFGroupWarning").slideDown(200);
    } else {
        $(".SNFGroupWarning").slideUp(200);
    }
}


function toggleTrial() {

    if ($(this).val() == "True") {
        $(".trialExpiry").slideDown(200);
    } else {
        $(".trialExpiry").slideUp(200);
    }
}

function toggleLudoFitSubscriptionEnabled() {
    if ($(this).val() == "True") {
        $(".ludoFitSubscriptionsEnabled").slideDown(200);
    } else {
        $(".ludoFitSubscriptionsEnabled").slideUp(200);
    }
}

function toggleLudoFitTrialDuration() {
    //console.log($(this).val())
    if ($(this).val() == "True") {
        $(".ludoFitTrialDuration").slideDown(200);
    } else {
        $(".ludoFitTrialDuration").slideUp(200);
    }
}


function toggleLoginSettings() {
    if ($(this).val() == "False") {
        $(".email .tip").slideDown(200);
        $(".newInvitationSection").slideDown(200);
    }
    else {
        $(".email .tip").slideUp(200);
        $(".newInvitationSection").slideUp(200);
    }
}


function toggleSubLimit() {

    if ($(this).val() == "True") {
        $(".subLimit").slideDown(200);

    }
    else {
        $(".subLimit").slideUp(200);
    }
}


function editInLine() {
    var link = $(this);
    var url = link.attr("href");
    var editBloc = link.closest(".editInLine");
    var text = editBloc.find(".text");
    var form = editBloc.find(".inLineEditor");
    form.toggleClass("noDisplay");
    link.toggleClass("noDisplay");
    text.toggleClass("noDisplay");
    form.find("a").click(function () {
        editBloc.find(".editLink").show();
        form.toggleClass("noDisplay");
        text.toggleClass("noDisplay");
        if ($(this).hasClass("ok")) {
            editBloc.find(".noElement").remove();
            editBloc.parent().mask("loading");
            var changedText = form.find(".inputText").val();
            form.find(".inputText").val("");
            text.html(changedText);
            if (url) {
                $.post(url, { text: changedText }, function (data) {
                    editBloc.parent().unmask();
                    if (!data.success) {
                        editBloc.after(data);
                    }
                });
            }
        }
        form.find("a").unbind("click");
        return false;
    });

    return false;
}

function showMenu(event) {
    //console.log('menu')

    event.preventDefault();
    var target = $(this).parent().find('.showMenu');
    var menu = $(this).next();
    if (menu.is(":visible")) {
        menu.slideUp(200).addClass("noDisplay");
        $(this).removeClass('open');
    }
    else {
        $('#searchMask:hidden').show();
        menu.width(target.width() - 0);//for 2px border
        menu.slideDown(200).removeClass("noDisplay").css({ left: target.offset().left, top: target.offset().top + target.height() });
        $(this).addClass('open');
    }
}


function showProfileMenu(event) {

    if (event) {
        event.preventDefault();
    }

    var menu = $('.profileMenu');

    if (menu.is(":visible")) {
        menu.slideUp(200).addClass("noDisplay");
        $('.showMenu').removeClass('open');
        $(menu).prependTo($('#profile')); //move into target to ensure it gets replaced if patient info is updated
    }
    else {
        $('#searchMask:hidden').show();
        $('.showMenu').addClass('open');
        menu.slideDown(200).removeClass("noDisplay").css({ left: $('#profile .showMenu').offset().left });
        $(menu).prependTo('body'); //move out of target to ensure it gets displayed on top of the mask
    }
}

//loads element 
function loadAsync(el) {
    if (el) {
        var url = el.find('a').attr('href');
        if (url) {
            el.mask("Loading...");
            $.ajax({
                url: url,
                success: function (data) {
                    el.unmask();
                    el.html(data);
                },
                error: function (data) {
                    el.unmask();
                }
            });
        }
    }
}

function launchPatientProgram() {
    if (!$('#patientDashboard a.launch').hasClass('disabled')) {
        $('#patientDashboard a.launch').trigger("click");
    }
}

function actionAndReplace() {
    showLoading();
    var input = $(this);
    var form = input.closest("form");
    var url = form.attr("action");
    $.post(url, form.serialize(), function (data) {
        if (data.result == "success") {
            location.reload();
        } else {
            var divId = $(data).attr("id");
            $('#' + divId).replaceWith(data);
            hideLoading();
        }
    });
}

//#region waiver
function highlightWarning() {
    $(this).closest(".field").find(".explanation").css("color", "red");
}

function reachedWaiverBottom() {
    var waiver = $(this);
    //console.log('SCROLL: ' + waiver[0].scrollHeight);
    if (waiver.scrollTop() + waiver.innerHeight() >= (waiver[0].scrollHeight - 5)) { //-5 due to off but border on mobile
        //console.log('DONE');
        var checkbox = waiver.closest(".waiver").find(".checkbox");
        checkbox.removeClass("inactive");
        checkbox.find("input[type=checkbox]").removeAttr("disabled");
    }
}
//#endregion


function reportSubscribeExpandDropdown() {

    var dropdown = $(this).parents('.jtxDropDown');
    var isOpen = dropdown.hasClass('open');
    //console.log('arg')
    if (isOpen) {
        $('.modal #Email').parents('.field').slideDown();
        $('.modal #WeeklyOrMonthly').parents('.field').slideDown();
    } else {
        $('.modal #Email').parents('.field').slideUp();
        $('.modal #WeeklyOrMonthly').parents('.field').slideUp();
    }
}


function reportUnsubscribeAll() {

    var pop = $(this).parents('.modal');

    var group = pop.find('#GroupReportSubscribe');

    //if selected, toggle
    if (group.closest('label').hasClass('selected')) {
        group.click();
    }

    //trigger unselect all for dropdown
    pop.find('#selectAll').prop('checked', false).change();
}

$(function () {
    $(document).on('click', '.actionLink', postActionLink);
    $(document).on('click', ".openBootPopup", getBootPopupContentClick);
    $(document).on('click', ".tableList .element .popForm", tableListElementPopForm); //for inline form pop submit
    $(document).on('click', ".tableList .filterSubBar .popForm", tableListFilterSubBarPopForm); //for search var form pop submit

    $(document).on('click', bootBackdropClick); //popup backdrop click
    $(document).on('hidden.bs.modal	', '#modal-holder', bootPopupHidden); //popup hide done transition
    $(document).on('shown.bs.modal	', '#modal-holder', bootPopupVisible); //popup visible done transition

    // This fixes a flood of errors caused by bootstrap modal on creation, not sure why it occurs
    $.fn.modal.Constructor.prototype.enforceFocus = function () { };

});

function bootBackdropClick(e) {

    if ($(e.target).hasClass("fade") && $('body').hasClass('modal-open')) {
        //do the reload as required
        $("button[value='reload']").first().click();
    }
}

function tableListElementPopForm() {
    killSlides();
    showLoading();
    var form = $(this).parents('.element').find('form');
    var url = form.attr("action");
    getBootPopupContent(url, form.serialize());
}

function tableListFilterSubBarPopForm() {
    showLoading();
    var form = $(this).parents('.filterSubBar').find('form');
    var url = form.attr("action");
    //console.log(url);
    //console.log(form.serialize())
    getBootPopupContent(url, form.serialize());
}

function bootPopupHidden() {
    $("button[value='cancel']").first().click();
    $('.focusable:visible:not(.close):first').focus(); //focus on first focusable item outside popup
}

function bootPopupVisible() {

    if ($('#modal-holder .focusable.focused:visible:not(.close)').length > 0) {
        $('#modal-holder .focusable.focused:visible:not(.close):first').focus(); //focus on first focused focusable item (so we can focus not the first item)
    } else {
        $('#modal-holder .focusable:visible:not(.close):first').focus(); //focus on first focusable item
    }

    $('#modal-holder .modal-body').scrollTop(0);//prevent scrolling down to selected input

    $("#modal-holder").modal('handleUpdate');
}

function postActionLink() {
    killSlides();

    var link = $(this);
    var url = link.find("a").attr("href");
    if (!url) {
        url = link.attr("href");
    }

    var showLoadingMask = !link.hasClass("noLoading");

    if (showLoadingMask) {
        showLoading();
    }
    $.ajax({
        type: "POST",
        url: url,
        success: function (data) {
            if (!data || data.action == "close") {
                hideLoading();
                if ($("#modal-holder").is(":visible")) {
                    $("#modal-holder").modal("hide");
                }
            }
            if (data.success == 1 && data.toggle) {
                link.parent().children().toggleClass("noDisplay");
            }
            else if (data.success == 1 && data.reload) {
                window.location.reload(true);
            } else if (data.success == 1 && data.hide) {
                var hideTarget = link.parents(data.hide);
                if (hideTarget.hasClass('All')) {
                    hideTarget.find('.btn').toggleClass("noDisplay");
                    //hideTarget.find('.archived').toggleClass("noDisplay");
                    hideTarget.toggleClass("archived");
                } else {
                    hideTarget.hide();
                }
            } else if (data.success == 1 && data.remove) {
                var target = link.parents(data.remove);
                if (data.args) {
                    var bloc = "#" + data.args;
                    target = $(bloc);
                }
                if (target.hasClass('All') && !data.force) {
                    target.find('.btn').toggleClass("noDisplay");
                    target.find('.jtxBtn.enableDisable').toggleClass("noDisplay");
                    target.find('.archived').toggleClass("noDisplay");
                    target.toggleClass("archived");
                } else {
                    target.remove();
                }
            }
            else if (!data.noPop) {
                handlePopAjaxResponse(data);
            } else if (data.noPop) {
                processBootPopupSubmitResponse(data);
            }
            if (link.hasClass("removeLine")) {
                link.parentsUntil("tr").parent().addClass("noDisplay");
            }

            if (link.data('removeclass') && link.data('removeclasstarget')) {
                $(link.data('removeclasstarget')).removeClass(link.data('removeclass'));
            }
        }, error: function (jqXHR) {
            handleError(jqXHR);
        },
        complete: function () {
            hideLoading();
        }
    });

    return false;
}


function getBootPopupContentClick() {
    var contentUrl = $(this).attr("href");
    getBootPopupContent(contentUrl);
    return false;
}

function getBootPopupContent(url, data) {

    if (!data) {
        data = { timestamp: new Date().getTime() };
    }
    //console.log(url)
    showLoading();
    $.ajax({
        url: url,
        data: data,
        success: function (result) {

            if (result.redirect != null || result.url != null || result.action != null) {
                hideLoading();
                processBootPopupSubmitResponse(result);
            }
            else {
                openBootPopup(result);
            }
        },
        error: function (jqXHR) {
            handleError(jqXHR);
            hideLoading();
            //if we're quitting, quit to be sure
            if (data.isQuit) {
                appQuit();
            }
        }
    });
    return true;
}

function processBootPopupSubmitResponse(data) {

    if (!data || data.action == "close") {
        hideLoading();
        if ($("#modal-holder").is(":visible")) {
            $("#modal-holder").modal("hide");
        }
    }

    console.log(data.message)
    console.log(data.msgType)

    //show notification if needed
    if (data.message) {
        displayMessage(data.message, data.msgType);
    }

    if (data.action == "forgetUser") {
        hideLoading();
        if ($("#modal-holder").is(":visible")) {
            $("#modal-holder").modal("hide");
        }
        ForgetUser(data.username);
    } else if (data.redirect) {
        if (!data.noloading) {
            showLoading();
        }
        window.location = data.redirect;
    } else if (data.success == 1 && data.remove) {

        var bloc = "#" + data.args;
        var target = $(bloc);
        if (target.hasClass('All') && !data.force) { // line item remove if not displaying all, toggle otherwise
            target.find('.btn').toggleClass("noDisplay");
            target.find('.jtxBtn.enableDisable').toggleClass("noDisplay");
            target.find('.archived').toggleClass("noDisplay");
            target.toggleClass("archived");
        } else {
            target.remove();
        }
    }
    else if (data.action == "remove") {
        hideLoading();
        if ($("#modal-holder").is(":visible")) {
            $("#modal-holder").modal("hide");
        }
        removeBlocById(data.args);
    } else if (data.action == "launch") {
        //if ($("#modal-holder").is(":visible")) {
        //$("#modal-holder").modal("hide");
        //}
        hideLoading();
        launchElement(data.moduleId, data.programId, data.clientId, data.token, data.url, data.reloadOnClose);
    }
    else if (data.action == "remember") {
        rememberCredentials(data.username);
        hideLoading();

        if ($("#modal-holder").is(":visible")) {
            $("#modal-holder").modal("hide");
        }
        launchPatientProgram();
    }
    else if (data.action == "neverRemember") {
        neverRememberCredentials(data.username, data.email);
        hideLoading();

        if ($("#modal-holder").is(":visible")) {
            $("#modal-holder").modal("hide");
        }
        launchPatientProgram();
    } else if (data.action == "launchPatient") {
        hideLoading();
        if ($("#modal-holder").is(":visible")) {
            $("#modal-holder").modal("hide");
        }
        launchPatientProgram();
    } else if (data.action == "logout") {
        $('#logoutForm').submit();
    } else if (data.action == "quit") {
        hideLoading();
        appQuit();
    } else if (data.reload) {
        //console.log('reload')
        location.reload();
    } else if (data.url && data.pop) {
        getBootPopupContent(data.url);
    } else if (data.url) {
        showLoading();
        $.ajax({
            url: data.url,
            type: "GET",
            data: { timestamp: new Date().getTime() },
            success: function (content) {
                if (data.replace) {
                    $(data.replace).html(content);
                    hideLoading();
                } else if (data.add) {
                    $(data.add).append(content);
                    $(data.add).scrollTop($(data.add)[0].scrollHeight);
                    hideLoading();
                } else {
                    updateBootView(content, data.refresh == "add", data.refresh == "replace");
                }

                if (data.callback) {
                    if (jQuery.isFunction(window[data.callback])) {
                        window[data.callback]();
                    }
                }
            }, error: function (jqXHR) {
                handleError(jqXHR);
            }
        });

        //openBootPopup(data);
    } else if (data.documentUrl) {
        if ($("#modal-holder").is(":visible")) {
            $("#modal-holder").modal("hide");
        }
        if (data.token && data.token != "") {
            openPortal(data.documentUrl, data.token);
        } else {
            window.location = data.documentUrl;
        }
    } else if (data.replace && data.content) {

        $(data.replace).html(data.content);
        hideLoading();
    } else {
        updateBootView(data, false, true);
    }

}

function openBootPopup(data) {
    //close any open menus/sliders
    killSlides();

    $("#modal-holder").html(data);

    if (!$("#modal-holder").is(":visible")) {
        $("#modal-holder").modal();
    }

    if (typeof initUIFeatures === "function") {
        initUIFeatures();
    }

    var form = $("#modal-holder form");


    //custom attribute to validate hidden form fields
    var validator = form.data('validator');
    if (validator) {
        validator.settings.ignore = ":hidden:not([data-force-val='true'])";
    }

    jQuery.validator.unobtrusive.parse(form);

    $.datepicker.setDefaults($.datepicker.regional[Globalize.culture().language]);
    $("#From").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        dateFormat: Globalize.culture().language == "en" ? "mm/dd/yy" : "dd/mm/yy",
        onClose: function (selectedDate) {
            $("#To").datepicker("option", "minDate", selectedDate);
        }
    });

    $("#To").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        dateFormat: Globalize.culture().language == "en" ? "mm/dd/yy" : "dd/mm/yy",
        onClose: function (selectedDate) {
            $("#From").datepicker("option", "maxDate", selectedDate);
        },
        onChangeMonthYear: function (month, year, obj) {
            var maxDateForMonth = new Date(obj.selectedYear, obj.selectedMonth + 1, 0).getDate();
            var toSetDate = obj.currentDay;
            if (obj.currentDay > maxDateForMonth) {
                toSetDate = maxDateForMonth;
            }
            $(this).datepicker('setDate', new Date(obj.selectedYear, obj.selectedMonth, toSetDate));
        }
    });

    $("#FromMonth").datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'MM yy',
        onClose: function () {
            var iMonth = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var iYear = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(iYear, iMonth, 1));
        },
        beforeShow: function () {
            if ((selDate = $(this).val()).length > 0) {
                iYear = selDate.substring(selDate.length - 4, selDate.length);
                iMonth = jQuery.inArray(selDate.substring(0, selDate.length - 5),
                    $(this).datepicker('option', 'monthNames'));
                $(this).datepicker('option', 'defaultDate', new Date(iYear, iMonth, 1));
                $(this).datepicker('setDate', new Date(iYear, iMonth, 1));
            }

            $('#ui-datepicker-div').removeClass("fromMonth");
            $('#ui-datepicker-div').removeClass("toMonth");
            $('#ui-datepicker-div').addClass("fromMonth");
        },
        onChangeMonthYear: function (month, year, obj) {
            var maxDateForMonth = new Date(obj.selectedYear, obj.selectedMonth + 1, 0).getDate();
            var toSetDate = obj.currentDay;
            if (obj.currentDay > maxDateForMonth) {
                toSetDate = maxDateForMonth;
            }
            $(this).datepicker('setDate', new Date(obj.selectedYear, obj.selectedMonth, toSetDate));
        }
    });

    $("#ToMonth").datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'MM yy',
        onClose: function () {
            var iMonth = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var iYear = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(iYear, iMonth, 1));
        },
        beforeShow: function () {
            if ((selDate = $(this).val()).length > 0) {
                iYear = selDate.substring(selDate.length - 4, selDate.length);
                iMonth = jQuery.inArray(selDate.substring(0, selDate.length - 5),
                    $(this).datepicker('option', 'monthNames'));
                $(this).datepicker('option', 'defaultDate', new Date(iYear, iMonth, 1));
                $(this).datepicker('setDate', new Date(iYear, iMonth, 1));
            }

            $('#ui-datepicker-div').removeClass("fromMonth");
            $('#ui-datepicker-div').removeClass("toMonth");
            $('#ui-datepicker-div').addClass("toMonth");
        },
        onChangeMonthYear: function (month, year, obj) {
            var maxDateForMonth = new Date(obj.selectedYear, obj.selectedMonth + 1, 0).getDate();
            var toSetDate = obj.currentDay;
            if (obj.currentDay > maxDateForMonth) {
                toSetDate = maxDateForMonth;
            }
            $(this).datepicker('setDate', new Date(obj.selectedYear, obj.selectedMonth, toSetDate));
        }
    });

    $("#modal-holder button.submitButton, #modal-holder .modal-footer button, #modal-holder .modal-header button, #modal-holder .modal-footer a").each(function () {
        var button = $(this);
        var buttonValue = button.attr("value");
        var buttonKeepalive = button.data("keepalive");

        if (buttonValue == null || buttonValue == "cancel") {
            button.click(function () {

                if (!buttonKeepalive) {
                    if (typeof setKeepAlive === "function") {
                        setKeepAlive(false);
                    }
                }

                if ($("#modal-holder .closeConfirm:hidden").length > 0) {
                    $("#modal-holder .closeConfirm").slideDown();
                    return false;
                }

                $("#modal-holder").modal('hide');
                //clear content
                $("#modal-holder").html("");
                if (!button.attr('href')) {
                    return false;
                }
                return true;
            });
        } else if (buttonValue == "reload") {
            button.click(function () {
                $("#modal-holder").modal('hide');
                location.reload();
                return false;
            });
        } else if (buttonValue == "reloadProgram") {
            var url = button.attr("href");
            button.click(function () {
                $("#modal-holder").modal('hide');
                handlePopAjaxResponse({ "target": "#tool", "url": url });
                return false;
            });
        } else if (buttonValue == "disabled" || buttonValue == "ignore") {
            //ignore
        } else {
            //console.log('SUB')
            button.click(function (e) {

                //if not _target=blank
                if (!form.attr('target') || !form.attr('target') == '_blank') {
                    e.preventDefault();


                    var validator = form.data('validator');
                    if (validator) {
                        //add our handler
                        validator.settings.submitHandler = function (form) {
                            //valid form
                            submitBootPopupForm(buttonValue);
                            return false;
                        }
                    } else {
                        submitBootPopupForm(buttonValue);
                        return false;
                    }
                    form.submit();
                    return false;
                }

                //otherwise add action and submit
                $('<input />').attr('type', 'hidden').attr('name', "button").attr('value', buttonValue).appendTo(form);
                form.submit();
                $("#modal-holder").modal('hide');
                return true;
            });
        }
    });

    hideLoading();

    return false;
}


function handlePopAjaxResponse(data) {

    if (data.redirect) {
        showLoading();
        window.location = data.redirect;
    } else if (data.action == "launch") {
        hideLoading();
        launchElement(data.moduleId, data.programId, data.clientId, data.token, data.url, data.reloadOnClose);
    } else if (data.url && data.pop) {
        getBootPopupContent(data.url);
    } else if (data.url && data.target) {
        if (data.showLoading != false) {
            $(data.target).mask("Loading...");
        }
        if (data.target == "popup") {
            showLoading();
        }

        $.ajax({
            url: data.url,
            data: { timestamp: new Date().getTime() },
            success: function (content) {
                if (content.url) {
                    handlePopAjaxResponse(content);
                } else {
                    $(data.target).html(content).unmask();
                }
            }, error: function (jqXHR) {
                handleError(jqXHR);
                if (data.target == "popup") {
                    hideLoading();
                }
            }
        });

    } else if (data.reload) {
        location.reload();
    } else if (data.replace && data.url) {
        $.get(data.url, function (content) {
            $(data.replace).replaceWith(content);
        });
    } else if (data.replace && data.content) {
        $(data.replace).html(data.content);
    } else if (data.addCustomization == true && data.url) {
        if ($(".menuItem.RehabProgram-Preset").hasClass("selected") && ($("#customizationFilter input:checked").length == 0 || $("input[value=myPreset]").prop("checked"))) {
            $.get(data.url, function (element) {
                $("#result").prepend(element);
            });
        }
    } else {
        openBootPopup(data);
    }
}

function submitBootPopupForm(action, form) {

    if (!form) {
        form = $("#modal-holder").find('form');
    }
    var formUrl = form.attr("action");
    var contentType = 'application/x-www-form-urlencoded; charset=UTF-8';
    var processData = true;

    //show notification if needed
    if ($(this).data('message')) {
        var msgType = $(this).data('messageType');
        displayMessage($(this).data('message'), msgType);
    }

    var args = form.serialize();
    args += "&Environment=" + window.location;
    if (action != null) {
        args += "&action=" + action;
    }

    // Handle forms with files specially
    if (form.find('input[type=file]').length > 0) {
        processData = false;
        contentType = false;
        args = new FormData();
        form.find('input').each(function (index, element) {
            if ($(element).attr('type') == 'file') {
                $.each(element.files, function (key, value) {
                    args.append($(element).attr('name'), value);
                });
            } else {
                args.append($(element).attr('name'), $(element).val());
            }
        });
    }

    if (form.valid()) {
        //$("#modal-holder").mask("Loading...");


        var showLoadingMask = !$(this).hasClass("noLoading");

        if (showLoadingMask) {
            showLoading();
        }
        showLoading();

        $.ajax({
            url: formUrl,
            type: "POST",
            data: args,
            processData: processData,
            contentType: contentType,
            success: processBootPopupSubmitResponse,
            error: function (jqXHR) {
                handleError(jqXHR);
                hideLoading();
            }
        });
    }

    return false;
}

function updateBootView(data, isAdd, isReplace) {

    var dataObject = $(data).first();
    var elementId = dataObject.attr("id");
    var elementClass = dataObject.attr("class") != null ? dataObject.attr("class").replace(/ /g, '.') : null;

    if (isAdd) {
        $("." + elementClass).first().before(data);
    }
    else {
        var element;

        // If still visible, it messes up the blackout backgroud, so close and give it time to do the animation
        if (dataObject.hasClass("modal-dialog")) {

            openBootPopup(data);

            return;
        }
        else if (elementId != null) {
            element = $("#" + elementId);
        }

        if (elementClass != null && (element == null || element.length == 0)) {
            element = $("." + elementClass);
        }

        if (isReplace && element != null && element.length > 0) {
            element.replaceWith(data);
        }
        else {
            if (element) {
                element.parent().html(data);
            }
        }
    }

    hideLoading();
    $("#modal-holder").modal('handleUpdate');

}

function removeBlocById(id) {
    var bloc = "#" + id;
    $(bloc).fadeOut(500, function () { $(this).remove(); });
}

function handleError(jqXHR) {
    //if its access denied, reload the page to force login
    if (jqXHR && jqXHR.status && jqXHR.status == 403) {
        location.reload();
    } else {
        displayMessage('An error occurred, please try again', 'Error');
    }
}
