/* Minification failed. Returning unminified contents.
(1,18): run-time error CSS1031: Expected selector, found '='
(1,18): run-time error CSS1025: Expected comma or open brace, found '='
(2,27): run-time error CSS1031: Expected selector, found '='
(2,27): run-time error CSS1025: Expected comma or open brace, found '='
(4,1): run-time error CSS1019: Unexpected token, found '$'
(4,2): run-time error CSS1019: Unexpected token, found '('
(4,12): run-time error CSS1031: Expected selector, found '('
(4,12): run-time error CSS1025: Expected comma or open brace, found '('
(33,2): run-time error CSS1019: Unexpected token, found ')'
(35,10): run-time error CSS1031: Expected selector, found 'appReallyQuit('
(35,10): run-time error CSS1025: Expected comma or open brace, found 'appReallyQuit('
(48,10): run-time error CSS1031: Expected selector, found 'appQuit('
(48,10): run-time error CSS1025: Expected comma or open brace, found 'appQuit('
(66,10): run-time error CSS1031: Expected selector, found 'launchElement('
(66,10): run-time error CSS1025: Expected comma or open brace, found 'launchElement('
(122,10): run-time error CSS1031: Expected selector, found 'openPortal('
(122,10): run-time error CSS1025: Expected comma or open brace, found 'openPortal('
(139,10): run-time error CSS1031: Expected selector, found 'openUrl('
(139,10): run-time error CSS1025: Expected comma or open brace, found 'openUrl('
(155,10): run-time error CSS1031: Expected selector, found 'getCapsLock('
(155,10): run-time error CSS1025: Expected comma or open brace, found 'getCapsLock('
(166,10): run-time error CSS1031: Expected selector, found 'setCapsLock('
(166,10): run-time error CSS1025: Expected comma or open brace, found 'setCapsLock('
(176,10): run-time error CSS1031: Expected selector, found 'getSavedUsers('
(176,10): run-time error CSS1025: Expected comma or open brace, found 'getSavedUsers('
(193,10): run-time error CSS1031: Expected selector, found 'getPassword('
(193,10): run-time error CSS1025: Expected comma or open brace, found 'getPassword('
(209,10): run-time error CSS1031: Expected selector, found 'setUsername('
(209,10): run-time error CSS1025: Expected comma or open brace, found 'setUsername('
(225,10): run-time error CSS1031: Expected selector, found 'notifyLoggedIn('
(225,10): run-time error CSS1025: Expected comma or open brace, found 'notifyLoggedIn('
(243,10): run-time error CSS1031: Expected selector, found 'notifyLoggedOut('
(243,10): run-time error CSS1025: Expected comma or open brace, found 'notifyLoggedOut('
(261,10): run-time error CSS1031: Expected selector, found 'rememberCredentials('
(261,10): run-time error CSS1025: Expected comma or open brace, found 'rememberCredentials('
(275,10): run-time error CSS1031: Expected selector, found 'neverRememberCredentials('
(275,10): run-time error CSS1025: Expected comma or open brace, found 'neverRememberCredentials('
(292,10): run-time error CSS1031: Expected selector, found 'removeUser('
(292,10): run-time error CSS1025: Expected comma or open brace, found 'removeUser('
(306,10): run-time error CSS1031: Expected selector, found 'setKeepAlive('
(306,10): run-time error CSS1025: Expected comma or open brace, found 'setKeepAlive('
(325,10): run-time error CSS1031: Expected selector, found 'sessionKeepAlive('
(325,10): run-time error CSS1025: Expected comma or open brace, found 'sessionKeepAlive('
(347,22): run-time error CSS1031: Expected selector, found '='
(347,22): run-time error CSS1025: Expected comma or open brace, found '='
(348,1): run-time error CSS1019: Unexpected token, found '$'
(348,2): run-time error CSS1019: Unexpected token, found '('
(348,12): run-time error CSS1031: Expected selector, found '('
(348,12): run-time error CSS1025: Expected comma or open brace, found '('
(356,2): run-time error CSS1019: Unexpected token, found ')'
(359,10): run-time error CSS1031: Expected selector, found 'globalKeyUp('
(359,10): run-time error CSS1025: Expected comma or open brace, found 'globalKeyUp('
(398,10): run-time error CSS1031: Expected selector, found 'loadSearchBoxClients('
(398,10): run-time error CSS1025: Expected comma or open brace, found 'loadSearchBoxClients('
(417,10): run-time error CSS1031: Expected selector, found 'sortSearchBox('
(417,10): run-time error CSS1025: Expected comma or open brace, found 'sortSearchBox('
(429,10): run-time error CSS1031: Expected selector, found 'patientSearchChange('
(429,10): run-time error CSS1025: Expected comma or open brace, found 'patientSearchChange('
(471,10): run-time error CSS1031: Expected selector, found 'userNavClick('
(471,10): run-time error CSS1025: Expected comma or open brace, found 'userNavClick('
(482,10): run-time error CSS1031: Expected selector, found 'showSearch('
(482,10): run-time error CSS1025: Expected comma or open brace, found 'showSearch('
(490,10): run-time error CSS1031: Expected selector, found 'patientSearchClick('
(490,10): run-time error CSS1025: Expected comma or open brace, found 'patientSearchClick('
(497,10): run-time error CSS1031: Expected selector, found 'killSlides('
(497,10): run-time error CSS1025: Expected comma or open brace, found 'killSlides('
(526,10): run-time error CSS1031: Expected selector, found 'searchItemHover('
(526,10): run-time error CSS1025: Expected comma or open brace, found 'searchItemHover('
(531,10): run-time error CSS1031: Expected selector, found 'clearSearchSelected('
(531,10): run-time error CSS1025: Expected comma or open brace, found 'clearSearchSelected('
(535,10): run-time error CSS1031: Expected selector, found 'patientSearchSelect('
(535,10): run-time error CSS1025: Expected comma or open brace, found 'patientSearchSelect('
(559,10): run-time error CSS1031: Expected selector, found 'patientSearchKeyDown('
(559,10): run-time error CSS1025: Expected comma or open brace, found 'patientSearchKeyDown('
(629,15): run-time error CSS1031: Expected selector, found ';'
(629,15): run-time error CSS1025: Expected comma or open brace, found ';'
(631,10): run-time error CSS1031: Expected selector, found 'takeScreenshot('
(631,10): run-time error CSS1025: Expected comma or open brace, found 'takeScreenshot('
(639,1): run-time error CSS1019: Unexpected token, found '$'
(639,2): run-time error CSS1019: Unexpected token, found '('
(639,12): run-time error CSS1031: Expected selector, found '('
(639,12): run-time error CSS1025: Expected comma or open brace, found '('
(655,2): run-time error CSS1019: Unexpected token, found ')'
(657,10): run-time error CSS1031: Expected selector, found 'cancelValidation('
(657,10): run-time error CSS1025: Expected comma or open brace, found 'cancelValidation('
(663,10): run-time error CSS1031: Expected selector, found 'placeLogin('
(663,10): run-time error CSS1025: Expected comma or open brace, found 'placeLogin('
(682,10): run-time error CSS1031: Expected selector, found 'indicationsOfUseClick('
(682,10): run-time error CSS1025: Expected comma or open brace, found 'indicationsOfUseClick('
(699,10): run-time error CSS1031: Expected selector, found 'loginKeyPress('
(699,10): run-time error CSS1025: Expected comma or open brace, found 'loginKeyPress('
(709,10): run-time error CSS1031: Expected selector, found 'loginKeyUp('
(709,10): run-time error CSS1025: Expected comma or open brace, found 'loginKeyUp('
(715,10): run-time error CSS1031: Expected selector, found 'capsOn('
(715,10): run-time error CSS1025: Expected comma or open brace, found 'capsOn('
(719,10): run-time error CSS1031: Expected selector, found 'capsOff('
(719,10): run-time error CSS1025: Expected comma or open brace, found 'capsOff('
(724,10): run-time error CSS1031: Expected selector, found 'loginSubmit('
(724,10): run-time error CSS1025: Expected comma or open brace, found 'loginSubmit('
(739,10): run-time error CSS1031: Expected selector, found 'loginCancelClick('
(739,10): run-time error CSS1025: Expected comma or open brace, found 'loginCancelClick('
(750,10): run-time error CSS1031: Expected selector, found 'loginForgetClick('
(750,10): run-time error CSS1025: Expected comma or open brace, found 'loginForgetClick('
(761,10): run-time error CSS1031: Expected selector, found 'loginForgetCancelClick('
(761,10): run-time error CSS1025: Expected comma or open brace, found 'loginForgetCancelClick('
(773,10): run-time error CSS1031: Expected selector, found 'loginSelectionSelectClick('
(773,10): run-time error CSS1025: Expected comma or open brace, found 'loginSelectionSelectClick('
(806,10): run-time error CSS1031: Expected selector, found 'loginSelectionForgetClick('
(806,10): run-time error CSS1025: Expected comma or open brace, found 'loginSelectionForgetClick('
(815,10): run-time error CSS1031: Expected selector, found 'LoadUserList('
(815,10): run-time error CSS1025: Expected comma or open brace, found 'LoadUserList('
(864,10): run-time error CSS1031: Expected selector, found 'ForgetUser('
(864,10): run-time error CSS1025: Expected comma or open brace, found 'ForgetUser('
(870,15): run-time error CSS1031: Expected selector, found '='
(870,15): run-time error CSS1025: Expected comma or open brace, found '='
(873,18): run-time error CSS1031: Expected selector, found '='
(873,18): run-time error CSS1025: Expected comma or open brace, found '='
(876,15): run-time error CSS1031: Expected selector, found ';'
(876,15): run-time error CSS1025: Expected comma or open brace, found ';'
(878,1): run-time error CSS1019: Unexpected token, found '$'
(878,2): run-time error CSS1019: Unexpected token, found '('
(878,12): run-time error CSS1031: Expected selector, found '('
(878,12): run-time error CSS1025: Expected comma or open brace, found '('
(981,2): run-time error CSS1019: Unexpected token, found ')'
(983,10): run-time error CSS1031: Expected selector, found 'addListeners('
(983,10): run-time error CSS1025: Expected comma or open brace, found 'addListeners('
(1023,10): run-time error CSS1031: Expected selector, found 'tableListTopMenu('
(1023,10): run-time error CSS1025: Expected comma or open brace, found 'tableListTopMenu('
(1050,10): run-time error CSS1031: Expected selector, found 'tableListMenu('
(1050,10): run-time error CSS1025: Expected comma or open brace, found 'tableListMenu('
(1085,10): run-time error CSS1031: Expected selector, found 'focusableFocus('
(1085,10): run-time error CSS1025: Expected comma or open brace, found 'focusableFocus('
(1090,10): run-time error CSS1031: Expected selector, found 'focusableKeydown('
(1090,10): run-time error CSS1025: Expected comma or open brace, found 'focusableKeydown('
(1143,10): run-time error CSS1031: Expected selector, found 'focusBack('
(1143,10): run-time error CSS1025: Expected comma or open brace, found 'focusBack('
(1156,10): run-time error CSS1031: Expected selector, found 'focusNext('
(1156,10): run-time error CSS1025: Expected comma or open brace, found 'focusNext('
(1185,10): run-time error CSS1031: Expected selector, found 'focusPrevious('
(1185,10): run-time error CSS1025: Expected comma or open brace, found 'focusPrevious('
(1214,10): run-time error CSS1031: Expected selector, found 'isIE('
(1214,10): run-time error CSS1025: Expected comma or open brace, found 'isIE('
(1228,10): run-time error CSS1031: Expected selector, found 'showMessage('
(1228,10): run-time error CSS1025: Expected comma or open brace, found 'showMessage('
(1235,10): run-time error CSS1031: Expected selector, found 'multiSelectChange('
(1235,10): run-time error CSS1025: Expected comma or open brace, found 'multiSelectChange('
(1244,10): run-time error CSS1031: Expected selector, found 'multiSelectOpen('
(1244,10): run-time error CSS1025: Expected comma or open brace, found 'multiSelectOpen('
(1308,10): run-time error CSS1031: Expected selector, found 'textareaAutosize('
(1308,10): run-time error CSS1025: Expected comma or open brace, found 'textareaAutosize('
(1324,10): run-time error CSS1031: Expected selector, found 'loadInTarget('
(1324,10): run-time error CSS1025: Expected comma or open brace, found 'loadInTarget('
(1363,10): run-time error CSS1031: Expected selector, found 'tableListSubmitForm('
(1363,10): run-time error CSS1025: Expected comma or open brace, found 'tableListSubmitForm('
(1370,10): run-time error CSS1031: Expected selector, found 'regularButtonLink('
(1370,10): run-time error CSS1025: Expected comma or open brace, found 'regularButtonLink('
(1380,10): run-time error CSS1031: Expected selector, found 'TrackPatientTime('
(1380,10): run-time error CSS1025: Expected comma or open brace, found 'TrackPatientTime('
(1391,10): run-time error CSS1031: Expected selector, found 'TrackGroupTherapyTime('
(1391,10): run-time error CSS1025: Expected comma or open brace, found 'TrackGroupTherapyTime('
(1402,10): run-time error CSS1031: Expected selector, found 'StartSessionTimer('
(1402,10): run-time error CSS1025: Expected comma or open brace, found 'StartSessionTimer('
(1439,10): run-time error CSS1031: Expected selector, found 'LoginTimeout('
(1439,10): run-time error CSS1025: Expected comma or open brace, found 'LoginTimeout('
(1470,10): run-time error CSS1031: Expected selector, found 'ReloadAfterDelay('
(1470,10): run-time error CSS1025: Expected comma or open brace, found 'ReloadAfterDelay('
(1478,10): run-time error CSS1031: Expected selector, found 'killLink('
(1478,10): run-time error CSS1025: Expected comma or open brace, found 'killLink('
(1483,10): run-time error CSS1031: Expected selector, found 'moduleTypeInfoMenuClick('
(1483,10): run-time error CSS1025: Expected comma or open brace, found 'moduleTypeInfoMenuClick('
(1492,10): run-time error CSS1031: Expected selector, found 'siteStatusResetClick('
(1492,10): run-time error CSS1025: Expected comma or open brace, found 'siteStatusResetClick('
(1498,10): run-time error CSS1031: Expected selector, found 'feedbackTypeClick('
(1498,10): run-time error CSS1025: Expected comma or open brace, found 'feedbackTypeClick('
(1503,10): run-time error CSS1031: Expected selector, found 'showLoading('
(1503,10): run-time error CSS1025: Expected comma or open brace, found 'showLoading('
(1508,10): run-time error CSS1031: Expected selector, found 'hideLoading('
(1508,10): run-time error CSS1025: Expected comma or open brace, found 'hideLoading('
(1517,10): run-time error CSS1031: Expected selector, found 'loginBreakout('
(1517,10): run-time error CSS1025: Expected comma or open brace, found 'loginBreakout('
(1525,10): run-time error CSS1031: Expected selector, found 'maintenanceBreakout('
(1525,10): run-time error CSS1025: Expected comma or open brace, found 'maintenanceBreakout('
(1532,10): run-time error CSS1031: Expected selector, found 'errorBreakout('
(1532,10): run-time error CSS1025: Expected comma or open brace, found 'errorBreakout('
(1540,10): run-time error CSS1031: Expected selector, found 'shareChanged('
(1540,10): run-time error CSS1025: Expected comma or open brace, found 'shareChanged('
(1550,10): run-time error CSS1031: Expected selector, found 'addSharedUser('
(1550,10): run-time error CSS1025: Expected comma or open brace, found 'addSharedUser('
(1592,10): run-time error CSS1031: Expected selector, found 'toggleSharedUser('
(1592,10): run-time error CSS1025: Expected comma or open brace, found 'toggleSharedUser('
(1600,10): run-time error CSS1031: Expected selector, found 'toggleSharedUserElement('
(1600,10): run-time error CSS1025: Expected comma or open brace, found 'toggleSharedUserElement('
(1636,10): run-time error CSS1031: Expected selector, found 'checkLastClinician('
(1636,10): run-time error CSS1025: Expected comma or open brace, found 'checkLastClinician('
(1647,10): run-time error CSS1031: Expected selector, found 'togglePatientLogin('
(1647,10): run-time error CSS1025: Expected comma or open brace, found 'togglePatientLogin('
(1662,10): run-time error CSS1031: Expected selector, found 'toggleEmail('
(1662,10): run-time error CSS1025: Expected comma or open brace, found 'toggleEmail('
(1678,10): run-time error CSS1031: Expected selector, found 'toggleTwoFactor('
(1678,10): run-time error CSS1025: Expected comma or open brace, found 'toggleTwoFactor('
(1688,10): run-time error CSS1031: Expected selector, found 'toggleDORSubscribeEmail('
(1688,10): run-time error CSS1025: Expected comma or open brace, found 'toggleDORSubscribeEmail('
(1697,10): run-time error CSS1031: Expected selector, found 'toggleReportGroupingGroupWarning('
(1697,10): run-time error CSS1025: Expected comma or open brace, found 'toggleReportGroupingGroupWarning('
(1706,10): run-time error CSS1031: Expected selector, found 'toggleTrial('
(1706,10): run-time error CSS1025: Expected comma or open brace, found 'toggleTrial('
(1716,10): run-time error CSS1031: Expected selector, found 'toggleSendInvite('
(1716,10): run-time error CSS1025: Expected comma or open brace, found 'toggleSendInvite('
(1727,10): run-time error CSS1031: Expected selector, found 'toggleLoginSettings('
(1727,10): run-time error CSS1025: Expected comma or open brace, found 'toggleLoginSettings('
(1739,10): run-time error CSS1031: Expected selector, found 'toggleSubLimit('
(1739,10): run-time error CSS1025: Expected comma or open brace, found 'toggleSubLimit('
(1751,10): run-time error CSS1031: Expected selector, found 'editInLine('
(1751,10): run-time error CSS1025: Expected comma or open brace, found 'editInLine('
(1786,10): run-time error CSS1031: Expected selector, found 'showMenu('
(1786,10): run-time error CSS1025: Expected comma or open brace, found 'showMenu('
(1805,10): run-time error CSS1031: Expected selector, found 'showProfileMenu('
(1805,10): run-time error CSS1025: Expected comma or open brace, found 'showProfileMenu('
(1827,10): run-time error CSS1031: Expected selector, found 'loadAsync('
(1827,10): run-time error CSS1025: Expected comma or open brace, found 'loadAsync('
(1846,10): run-time error CSS1031: Expected selector, found 'launchPatientProgram('
(1846,10): run-time error CSS1025: Expected comma or open brace, found 'launchPatientProgram('
(1852,10): run-time error CSS1031: Expected selector, found 'actionAndReplace('
(1852,10): run-time error CSS1025: Expected comma or open brace, found 'actionAndReplace('
(1869,10): run-time error CSS1031: Expected selector, found 'highlightWarning('
(1869,10): run-time error CSS1025: Expected comma or open brace, found 'highlightWarning('
(1873,10): run-time error CSS1031: Expected selector, found 'reachedWaiverBottom('
(1873,10): run-time error CSS1025: Expected comma or open brace, found 'reachedWaiverBottom('
(1884,10): run-time error CSS1031: Expected selector, found 'reportSubscribeExpandDropdown('
(1884,10): run-time error CSS1025: Expected comma or open brace, found 'reportSubscribeExpandDropdown('
(1899,10): run-time error CSS1031: Expected selector, found 'reportUnsubscribeAll('
(1899,10): run-time error CSS1025: Expected comma or open brace, found 'reportUnsubscribeAll('
(1913,1): run-time error CSS1019: Unexpected token, found '$'
(1913,2): run-time error CSS1019: Unexpected token, found '('
(1913,12): run-time error CSS1031: Expected selector, found '('
(1913,12): run-time error CSS1025: Expected comma or open brace, found '('
(1922,2): run-time error CSS1019: Unexpected token, found ')'
(1924,10): run-time error CSS1031: Expected selector, found 'goBack('
(1924,10): run-time error CSS1025: Expected comma or open brace, found 'goBack('
(1929,10): run-time error CSS1031: Expected selector, found 'initNavigation('
(1929,10): run-time error CSS1025: Expected comma or open brace, found 'initNavigation('
(1949,10): run-time error CSS1031: Expected selector, found 'hashChange('
(1949,10): run-time error CSS1025: Expected comma or open brace, found 'hashChange('
(1959,10): run-time error CSS1031: Expected selector, found 'patientSectionClick('
(1959,10): run-time error CSS1025: Expected comma or open brace, found 'patientSectionClick('
(1968,10): run-time error CSS1031: Expected selector, found 'patientSectionNav('
(1968,10): run-time error CSS1025: Expected comma or open brace, found 'patientSectionNav('
(2013,10): run-time error CSS1031: Expected selector, found 'switchTabs('
(2013,10): run-time error CSS1025: Expected comma or open brace, found 'switchTabs('
(2027,24): run-time error CSS1031: Expected selector, found ';'
(2027,24): run-time error CSS1025: Expected comma or open brace, found ';'
(2028,23): run-time error CSS1031: Expected selector, found ';'
(2028,23): run-time error CSS1025: Expected comma or open brace, found ';'
(2030,10): run-time error CSS1031: Expected selector, found 'displayMessage('
(2030,10): run-time error CSS1025: Expected comma or open brace, found 'displayMessage('
(2100,10): run-time error CSS1031: Expected selector, found 'displayMessages('
(2100,10): run-time error CSS1025: Expected comma or open brace, found 'displayMessages('
(2118,10): run-time error CSS1031: Expected selector, found 'clearMessages('
(2118,10): run-time error CSS1025: Expected comma or open brace, found 'clearMessages('
(2135,10): run-time error CSS1031: Expected selector, found 'handleAjaxMessages('
(2135,10): run-time error CSS1025: Expected comma or open brace, found 'handleAjaxMessages('
(2141,10): run-time error CSS1031: Expected selector, found 'checkAndHandleMessageFromHeader('
(2141,10): run-time error CSS1025: Expected comma or open brace, found 'checkAndHandleMessageFromHeader('
(2152,1): run-time error CSS1019: Unexpected token, found '$'
(2152,2): run-time error CSS1019: Unexpected token, found '('
(2152,12): run-time error CSS1031: Expected selector, found '('
(2152,12): run-time error CSS1025: Expected comma or open brace, found '('
(2161,2): run-time error CSS1019: Unexpected token, found ')'
(2163,10): run-time error CSS1031: Expected selector, found 'jtxToggleSectionClick('
(2163,10): run-time error CSS1025: Expected comma or open brace, found 'jtxToggleSectionClick('
(2175,10): run-time error CSS1031: Expected selector, found 'jtxSearchBoxClose('
(2175,10): run-time error CSS1025: Expected comma or open brace, found 'jtxSearchBoxClose('
(2179,10): run-time error CSS1031: Expected selector, found 'jtxSearchBoxChange('
(2179,10): run-time error CSS1025: Expected comma or open brace, found 'jtxSearchBoxChange('
(2188,10): run-time error CSS1031: Expected selector, found 'toggleOptionBtnClick('
(2188,10): run-time error CSS1025: Expected comma or open brace, found 'toggleOptionBtnClick('
(2199,10): run-time error CSS1031: Expected selector, found 'jtxDropDownClick('
(2199,10): run-time error CSS1025: Expected comma or open brace, found 'jtxDropDownClick('
(2212,10): run-time error CSS1031: Expected selector, found 'jtxSelectListItemClick('
(2212,10): run-time error CSS1025: Expected comma or open brace, found 'jtxSelectListItemClick('
(2260,10): run-time error CSS1031: Expected selector, found 'jtxSimpleSelectListItemClick('
(2260,10): run-time error CSS1025: Expected comma or open brace, found 'jtxSimpleSelectListItemClick('
(2307,10): run-time error CSS1031: Expected selector, found 'jtxSelectListSelectAllClick('
(2307,10): run-time error CSS1025: Expected comma or open brace, found 'jtxSelectListSelectAllClick('
(2321,1): run-time error CSS1019: Unexpected token, found '$'
(2321,2): run-time error CSS1019: Unexpected token, found '('
(2321,12): run-time error CSS1031: Expected selector, found '('
(2321,12): run-time error CSS1025: Expected comma or open brace, found '('
(2334,2): run-time error CSS1019: Unexpected token, found ')'
(2336,10): run-time error CSS1031: Expected selector, found 'bootBackdropClick('
(2336,10): run-time error CSS1025: Expected comma or open brace, found 'bootBackdropClick('
(2344,10): run-time error CSS1031: Expected selector, found 'tableListElementPopForm('
(2344,10): run-time error CSS1025: Expected comma or open brace, found 'tableListElementPopForm('
(2352,10): run-time error CSS1031: Expected selector, found 'tableListFilterSubBarPopForm('
(2352,10): run-time error CSS1025: Expected comma or open brace, found 'tableListFilterSubBarPopForm('
(2361,10): run-time error CSS1031: Expected selector, found 'bootPopupHidden('
(2361,10): run-time error CSS1025: Expected comma or open brace, found 'bootPopupHidden('
(2366,10): run-time error CSS1031: Expected selector, found 'bootPopupVisible('
(2366,10): run-time error CSS1025: Expected comma or open brace, found 'bootPopupVisible('
(2379,10): run-time error CSS1031: Expected selector, found 'postActionLink('
(2379,10): run-time error CSS1025: Expected comma or open brace, found 'postActionLink('
(2456,10): run-time error CSS1031: Expected selector, found 'getBootPopupContentClick('
(2456,10): run-time error CSS1025: Expected comma or open brace, found 'getBootPopupContentClick('
(2462,10): run-time error CSS1031: Expected selector, found 'getBootPopupContent('
(2462,10): run-time error CSS1025: Expected comma or open brace, found 'getBootPopupContent('
(2494,10): run-time error CSS1031: Expected selector, found 'processBootPopupSubmitResponse('
(2494,10): run-time error CSS1025: Expected comma or open brace, found 'processBootPopupSubmitResponse('
(2620,10): run-time error CSS1031: Expected selector, found 'openBootPopup('
(2620,10): run-time error CSS1025: Expected comma or open brace, found 'openBootPopup('
(2820,10): run-time error CSS1031: Expected selector, found 'handlePopAjaxResponse('
(2820,10): run-time error CSS1025: Expected comma or open brace, found 'handlePopAjaxResponse('
(2874,10): run-time error CSS1031: Expected selector, found 'submitBootPopupForm('
(2874,10): run-time error CSS1025: Expected comma or open brace, found 'submitBootPopupForm('
(2938,10): run-time error CSS1031: Expected selector, found 'updateBootView('
(2938,10): run-time error CSS1025: Expected comma or open brace, found 'updateBootView('
(2980,10): run-time error CSS1031: Expected selector, found 'removeBlocById('
(2980,10): run-time error CSS1025: Expected comma or open brace, found 'removeBlocById('
(2985,10): run-time error CSS1031: Expected selector, found 'handleError('
(2985,10): run-time error CSS1025: Expected comma or open brace, found 'handleError('
 */
var appKeepalive = false;
var closeDialogOnComplete = false;

$(function () {
    //latest user submit
    $(document).on('click', ".loginForm form input:submit", function (event) {

        try {
            if (external.app) {
                //console.log($('#UserName').val());
                var shouldRemember = external.app.ShouldRemember($('#UserName').val());

                //set the field on the form
                $('#ShouldRemember').val(shouldRemember);

                if (shouldRemember) {
                    external.app.LatestCred(window.btoa($('#Password').val()));
                }
            } else if (external.shouldRemember) {
                var should = external.shouldRemember($('#UserName').val());

                //set the field on the form
                $('#ShouldRemember').val(should);

                if (should) {
                    external.latestCred(window.btoa($('#Password').val()));
                }
            }
        } catch (err) {
            return;
        }
    });
});

function appReallyQuit() {
    try {
        var url = $('#confirmLogout').attr('href');
        if (url) {
            return getBootPopupContent(url, { 'isQuit': true });
        }
    } catch (e) {
        //if problem, close
        return true;
    }
    return false;
}

function appQuit() {
    //console.log("QUIT")
    try {
        //awesomium
        if (external.app) {
            external.app.AppQuit();
            //CEF
        } else {
            //console.log("CEF")
            external.appQuit();
        }
    }
    catch (err) {
        //console.log(err)
        return;
    }
}

function launchElement(moduleId, programId, clientId, token, url, reloadOnClose) {

    try {

        //console.log("LAUNCH: module " + moduleId + " program " + programId + " client " + clientId + "reload " + reloadOnClose);

        if (clientId === undefined) {
            clientId = null;
        }

        if (programId === undefined) {
            programId = null;
        }

        if (moduleId === undefined) {
            moduleId = null;
        }

        if (external.app) {
            var success = external.app.Launch(moduleId, programId, clientId, token);
            if (success) {
                if (reloadOnClose) {
                    closeDialogOnComplete = true;
                }
                if (url) {
                    //need to offeset due to animation is usually closing the old popup right now
                    setTimeout(function () { getBootPopupContent(url); }, 750);
                }
            } else {
                displayMessage("Unable to launch", "Error");
            }
        } else if (external.launch) {
            var suc = external.launch(moduleId, programId, clientId, token);
            if (suc) {
                if (reloadOnClose) {
                    closeDialogOnComplete = true;
                }
                if (url) {
                    //need to offeset due to animation is usually closing the old popup right now
                    setTimeout(function () { getBootPopupContent(url); }, 750);
                }
            } else {
                displayMessage("Unable to launch", "Error");
            }
        } else {
            //if (reloadOnClose) {
            //    closeDialogOnComplete = true;
            //}
            displayMessage("Please use the Jintronix application to play", "Error");
            //setTimeout(function() { getBootPopupContent(url); }, 750);
        }
    } catch (err) {
        displayMessage("Please use the Jintronix application to play", "Error");
    }
}

function openPortal(url, token) {

    try {
        //awesomium
        if (external.app) {
            external.app.OpenPortal(url, token);
            //CEF
        } else {
            external.openPortal(url, token);
        }
    }
    catch (err) {
        window.location = url;
        return;
    }
}

function openUrl(url) {
    try {
        //awesomium
        if (external.app) {
            external.app.OpenUrl(url);
            //CEF
        } else {
            external.openUrl(url);
        }
    }
    catch (err) {
        window.location = url;
        return;
    }
}

function getCapsLock() {
    try {
        var caps = external.getCapsLock();

        return caps;
    }
    catch (err) {
        return false;
    }
}

function setCapsLock(value) {

    if (value) {
        capsOn();
    } else {
        capsOff();
    }
}


function getSavedUsers() {

    try {
        //return ['phil'];
        //awesomium
        if (external.app) {
            return external.app.GetSavedUsers();
            //CEF
        } else {
            return external.getSavedUsers();
        }
    }
    catch (err) {
        return "";
    }
}

function getPassword(username) {
    try {

        //awesomium
        if (external.app) {
            return window.atob(external.app.GetPassword(username));
            //CEF
        } else {
            return window.atob(external.getPassword(username));
        }

    } catch (err) {
        return "";
    }
}

function setUsername(username) {
    try {
        //console.log(username);
        //awesomium
        if (external.app) {
            external.app.SetUsername(username);
            //CEF
        } else {
            external.setUsername(username);
        }
    } catch (err) {
        return;
    }
}


function notifyLoggedIn() {
    //console.log('LoggedIn')
    try {
        //awesomium
        if (external.app) {
            external.app.NotifyLoggedIn();
            //CEF
        } else {
            if (external.notifyLoggedIn) {
                external.notifyLoggedIn();
            }
        }
    } catch (err) {
        //console.log(err);
        return;
    }
}

function notifyLoggedOut() {
    //console.log('LoggedOut')
    try {
        //awesomium
        if (external.app) {
            external.app.NotifyLoggedOut();
            //CEF
        } else {
            if (external.notifyLoggedOut) {
                external.notifyLoggedOut();
            }
        }
    } catch (err) {
        //console.log(err);
        return;
    }
}

function rememberCredentials(username) {
    try {
        //awesomium
        if (external.app) {
            external.app.RememberCredentials(username);
            //CEF
        } else {
            external.rememberCredentials(username);
        }
    } catch (err) {
        return;
    }
}

function neverRememberCredentials(username, email) {
    try {
        //awesomium
        if (external.app) {
            external.app.NeverRemember(username);
            //CEF
        } else {
            //console.log(username);
            //console.log(email);
            external.neverRemember(username, email);
        }

    } catch (err) {
        return;
    }
}

function removeUser(username) {
    try {
        //awesomium
        if (external.app) {
            return external.app.ForgetUser(username);
            //CEF
        } else {
            return external.forgetUser(username);
        }
    } catch (err) {
        return false;
    }
}

function setKeepAlive(busy) {

    try {

        console.log('Setting keepalive: ' + busy);
        appKeepalive = busy;
        sessionKeepAlive();

        //if we're closing the dialog when unity is donw
        if (!busy && closeDialogOnComplete) {
            //console.log('Close Pop');
            closeDialogOnComplete = false;
            $('#modal-holder button.close').click();
        }
    } catch (err) {
        return;
    }
}

function sessionKeepAlive() {

    try {

        if (appKeepalive) {
            $.ajax({
                url: '/heartbeat/keepalive',
                data: { timestamp: new Date().getTime() },
                complete: function () {
                    console.log('keepalive ping');
                    setTimeout(sessionKeepAlive, 60000);
                }
            });
        }
    } catch (err) {
        return;
    }
}




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();
        }
    });
}

$(function () {
    $(document).on('click', "#loginWrapper .indicationsOfUseBtn", indicationsOfUseClick);
    $(document).on('click', "#loginWrapper .loginSelection.select .users .entry", loginSelectionSelectClick);
    $(document).on('click', "#loginWrapper .loginSelection.select .btns .entry.different", loginSelectionSelectClick);
    $(document).on('click', "#loginWrapper .loginSelection.select .btns .entry.forget", loginForgetClick);
    $(document).on('click', "#loginWrapper .loginSelection.forget .users .entry", loginSelectionForgetClick);
    $(document).on('click', "#loginWrapper .loginSelection.forget .btns .entry.cancel", loginForgetCancelClick);
    $(document).on('click', '#loginWrapper .loginForm .btns .entry.cancel', loginCancelClick);
    $(document).on('click', '#loginWrapper .loginForm .links button.resend', cancelValidation);
    $(document).on('submit', '#loginWrapper .loginForm form', loginSubmit);
    $(document).on('keypress', '.loginbody input[type=text], .loginbody input[type=password]', loginKeyPress);
    $(document).on('keyup', '.loginbody input[type=password]', loginKeyUp);
    $(window).on('load', placeLogin); //place login centered vertically

    //focus initial
    $('.focused').focus();
});

function cancelValidation() {
    $(".loginForm form").validate().settings.ignore = "*";
    console.log('HI ')
}

//place login vertically
function placeLogin() {

    $('.loginbody.LudoFit .loginFormWrapper .login').each(function () {

        var target = $(this).parent();

        if (target.length > 0) {
            var top = (target.height() / 2) - ($(this).height() / 2);
            if (top < 0) {
                top = 0;
            }

            $(this).css({
                top: top
            });
        }
    });
}

function indicationsOfUseClick(event) {
    event.preventDefault();
    var indications = $(this).parent().children('.indicationsOfUse');
    if (!indications.is(":visible")) {
        $(this).addClass('selected');
        $(this).find('i').removeClass('fa-caret-right');
        $(this).find('i').addClass('fa-caret-down');
        indications.slideDown();
    } else {
        $(this).removeClass('selected');
        $(this).find('i').removeClass('fa-caret-down');
        $(this).find('i').addClass('fa-caret-right');
        indications.slideUp();
    }
}


function loginKeyPress(e) {

    var s = String.fromCharCode(e.which);
    if (s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey) {
        capsOn();
    } else {
        capsOff();
    }
}

function loginKeyUp(e) {
    if (e.which != 9 && e.which != 16) {
        $('.loginForm form').valid();
    }
}

function capsOn() {
    $(".capsWarning").removeClass("noDisplay");
}

function capsOff() {
    $(".capsWarning").addClass("noDisplay");
}


function loginSubmit(event) {
    console.log()
    $('.loginForm form')
    if ($('.loginForm form').valid()) {
        if ($(this).find("button[type=submit]:focus").length > 0) {
            $('.loginArea').mask("Resending...");
        } else {
            $('.loginArea').mask("Logging in...");
        }
    } else {
        event.preventDefault();
    }
}


function loginCancelClick(event) {
    event.preventDefault();

    $('.loginSelection').slideDown();
    $('.loginForm').slideUp();


    $('.loginSelection .entry.user:first').focus();

}

function loginForgetClick(event) {
    event.preventDefault();
    $('.loginSelection').removeClass('select');
    $('.loginSelection').addClass('forget');
    $('.loginSelection').hide();
    $('.loginSelection').fadeIn();

    $('.loginSelection .entry.user:first').focus();

}

function loginForgetCancelClick(event) {
    if (event) {
        event.preventDefault();
    }
    $('.loginSelection').addClass('select');
    $('.loginSelection').removeClass('forget');
    $('.loginSelection').hide();
    $('.loginSelection').fadeIn();

    $('.loginSelection .entry.user:first').focus();
}

function loginSelectionSelectClick(event) {
    event.preventDefault();

    //reset validation
    $('.loginForm form').find("[data-valmsg-replace]").removeClass("field-validation-error").addClass("field-validation-valid").empty();
    $('.loginForm form').trigger('reset');

    var username = $(this).children('.username').html();
    var pass = "";
    if (username) {
        pass = getPassword(username);
    }

    $("#UserName").val(username);
    if (pass != "") {
        $("#Password").val(pass);
    }
    $('.loginSelection').slideUp();
    $('.loginForm').slideDown();

    if (pass != "") {
        $('#WasRemembered').val(true);
        $('.loginForm form').submit();
    }

    if (username) {
        $("#Password").focus();
    } else {
        $("#UserName").focus();
    }

}

function loginSelectionForgetClick(event) {
    event.preventDefault();
    var username = $(this).children('.username').html();
    var url = $('#loginWrapper .loginSelection a.forget').attr('href');
    getBootPopupContent(url, { 'username': username });

}


function LoadUserList(forceLogin) {
    $('.loginArea').mask("Loading...");

    setTimeout(function () {
        var users = getSavedUsers();


        if (users.length > 0) {
            //clear list, leaving only the first one
            $('.loginSelection .users').html($('.loginSelection .entry.user:first').clone());
            $('.loginSelection .entry.user .username').html("");

            for (var index = 0; index < users.length; index++) {
                // first one just assign
                if (index == 0) {
                    $('.loginSelection .entry.user .username').html(users[index]);
                } else {
                    // clone and assign
                    $('.loginSelection .entry.user:first').clone().appendTo('.loginSelection .users').children('.username').html(users[index]);
                }
            }


            $('.loginArea').unmask();
            if (!forceLogin) {
                $('.loginSelection').slideDown();
                $('.loginForm').slideUp();
                $('.loginSelection .entry.user:first').focus();
                //clear textboxes
                $("#UserName").val("");
                $("#Password").val("");
            } else {
                //invalid password so focus there
                $("#Password").focus();
            }
            $('#loginWrapper .loginArea .loginForm .btn.cancel').fadeIn().css("display", "block");;


        } else {
            $('#loginWrapper .loginArea .loginForm .btn.cancel').hide();
            $('.loginArea').unmask();
            $('.loginSelection').slideUp();
            $('.loginForm').slideDown();
            $("#UserName").focus();
        }
    }, 400);
}


function ForgetUser(username) {
    removeUser(username);
    LoadUserList();
    loginForgetCancelClick();
}
//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', '#SendInvite', toggleSendInvite); //user create form show/hide invite remiders
    $(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', "a.showMenu", showMenu); //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', ".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

}


function tableListTopMenu(event) {
    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);
            }
        }, 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 toggleSendInvite() {
    if ($(this).val() == "True") {
        $(".email .tip").slideDown(200);
        $(".sendInviteReminders").slideDown(200);

    } else {
        $(".email .tip").slideUp(200);
        $(".sendInviteReminders").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() - 4);//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);
    if (waiver.scrollTop() + waiver.innerHeight() >= waiver[0].scrollHeight) {
        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 () {

    //listeners
    $(document).on('click', '.patientSectionNav .patientSectionButton', patientSectionClick);
    $(document).on('click', 'a.goBack', goBack);
    $(window).on('hashchange', hashChange);

    //initialize
    initNavigation();
});

function goBack(event) {
    event.preventDefault();
    window.history.back();
}

function initNavigation() {
    //console.log('init')
    //if on the patient index page
    if ($(".patientSectionNav").length > 0) {

        var tab = $.bbq.getState('navtab');

        var selected = $(".patientSectionNav .initial");

        // if already set in state, fire the handler, otherwise set the selected tab to the state (which fires handler)
        if (tab) {
            $(window).trigger('hashchange');
        } else {
            if (selected.length > 0) {
                $.bbq.pushState({ navtab: selected.data("navtab") });
            }
        }
    }
}

function hashChange() {
    //console.log('hashChange')

    var tab = $.bbq.getState('navtab');
    if (tab) {
        patientSectionNav(tab);
    }

}

function patientSectionClick(event) {

    event.preventDefault();

    //use mode 2 to clear any params that may be there now
    $.bbq.pushState({ navtab: $(this).data("navtab") }, 2);
    return false;
}

function patientSectionNav(tab) {
    var target = $('[data-navtab=' + tab + ']');
    var targetURL = target.attr("href");
    var targetForceReload = target.data("forcereload");
    var selectedUrl = $(".patientSectionNav .selected").attr("href");
    var targetDiv = $("#patientInfo").find('[data-target=' + tab + ']');
    var section = tab.split('-')[0];

    //if clicked on current tab [reload] or clicked on tab not yet loaded
    var load = targetForceReload || (targetURL && (targetURL == selectedUrl || (targetURL != selectedUrl && (!targetDiv.html() || targetDiv.hasClass('empty')))));

    //set selected nav buttons selected
    $('.patientSectionNav .patientSectionButton').removeClass('selected');
    target.addClass('selected');
    $('.patientSectionNav .patientSectionButton[data-navsection=' + section + ']').addClass('selected');

    if (load) {

        switchTabs(tab, section, targetDiv);

        $.ajax({
            url: targetURL,
            data: { timestamp: new Date().getTime() },
            success: function (data) {
                //fade out
                targetDiv.addClass('opacity0');
                //html and fade in
                setTimeout(function () {
                    targetDiv.html(data);
                    targetDiv.removeClass('opacity0');
                    targetDiv.find('.moduleList').removeClass('opacity0');
                }, 400);
                targetDiv.removeClass('empty');
                initModuleSort();
            },
            error: function () {
                displayMessage("Communication Error", "Error");
            }
        });
    }
    else {
        switchTabs(tab, section, targetDiv);
    }
}

function switchTabs(tab, section, targetDiv) {

    //hide all sections and tabs
    $('.patientTab').hide();

    //show section
    $('[data-sectiontarget=' + section + ']').show();

    ////fade in
    //targetDiv.fadeIn();

    targetDiv.show();

}
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'));
    }
}
/***    
    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();
        }
    }
}

$(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");
        }
    }
    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');
    }
}
