window.top.currentMcUrl = ''; window.top.addEventListener('popstate', function (event) { window.setTimeout(function () { hideMask(); hideMoeFormMask(); if (!event || (!event.state && event.state !== '')) { // console.error('ALIX No state!', event, event.state); return; } var state = event.state; if (state === '') state = '/'; if (state[0] !== '/') state = '/' + state; if (!!state) fastLoad(state, false, true); }, 0); }); $(document).ready(function () { var originalLocationPath = window.location.pathname; var params = window.location.search; // TODO make it so if param 'xy' is passed in, it doesn't go to parent var noMcStuffOnLoad = originalLocationPath.indexOf('notes') >= 0; if(!window.noMc){ if (window.location.pathname === window.top.location.pathname) { window.top.location.href = '/mc' + window.location.pathname + window.location.search; return; } } if(window.noMc) return; // window.top.ensureRHS(); $(document).on('click', '.stag_rhs_toggle', function () { var state = window.top.toggleRHS(), icon = $(this).find('i'); if (state === 'collapsed') { icon.removeClass().addClass('fa fa-arrow-left'); } else { icon.removeClass().addClass('fa fa-arrow-right'); } }); var body = $(window.top.document.body), icon = $('.stag_rhs_toggle i'); if (body.is('.stag_rhs_collapsed')) { icon.removeClass().addClass('fa fa-arrow-left'); } initCreateNote(); initQuillEdit(); initFastLoad(); initPrimaryForm(); initPatientPresenceIndicator(); runMCInitializers(); initFileInputs(); // if(typeof initializeCalendar !== 'undefined') { // initializeCalendar(); // } // if(typeof initIntakeEvents !== 'undefined') { // initIntakeEvents(); // } // populate history on fresh load var target = window.top.location.pathname + window.top.location.search; if (target.indexOf('/mc') === 0) { target = target.split('/mc')[1]; } if(noMcStuffOnLoad){ target = originalLocationPath; } if(!window.noMc){ fastLoad(target, true, false, true); } }); function enableTimeSpecificFields(_checked, _valueClass, _rangeClass) { if (_valueClass) $('.' + _valueClass).prop('disabled', _checked); if (_rangeClass) $('.' + _rangeClass).prop('disabled', !_checked); } function toggleDisabledAsNeeded(_el, _targetValue, _enableClass, _disableClass) { if (_el.value === _targetValue) { if (_enableClass) $('.' + _enableClass).prop('disabled', false); if (_disableClass) $('.' + _disableClass).prop('disabled', true); } else { if (_enableClass) $('.' + _enableClass).prop('disabled', true); if (_disableClass) $('.' + _disableClass).prop('disabled', false); } } function toggleVisibilityAsNeeded(_el, _targetValue, _visibleClass, _hiddenClass) { if (_el.value === _targetValue) { if (_visibleClass) $('.' + _visibleClass).removeClass('d-none'); if (_hiddenClass) $('.' + _hiddenClass).addClass('d-none'); } else { if (_visibleClass) $('.' + _visibleClass).addClass('d-none'); if (_hiddenClass) $('.' + _hiddenClass).removeClass('d-none'); } } var fastCache = {}; function initFastLoad(_parent = false) { var allAs = $('a[href]:not([onclick]):not([href="#"]):not([native]):not([open-in-stag-popup])'); if (_parent) { allAs = _parent.find('a[href]:not([onclick]):not([href="#"]):not([native]):not([open-in-stag-popup])'); } // clear cache if (!_parent) { fastCache = {}; } else { allAs.each(function () { if (typeof fastCache[this.href] !== 'undefined') { delete fastCache[this.href]; } }); } // find links without event handlers allAs.each(function () { if (!$(this).closest('[moe]').length) { if ($(this).closest('.dropdown-menu').length) { enableFastLoad(this, true); } else { // var handlers = findEventHandlers('click', this); // if (!handlers || !handlers.length) { enableFastLoad(this); // } } } }); function enableFastLoad(_a, _menuItem = false) { $(_a) .off('click.fast-load') .on('click.fast-load', function () { fastLoad(this.href, true, true); $('.dropdown-menu') .removeClass('show') .prev('.dropdown-toggle').attr('aria-expanded', 'false'); return false; }); // console.info('FastLoad enabled for ' + _a.innerText + ' [' + _a.href + ']'); } // fast cache // allAs = $('a[href]:not([onclick]):not([href="#"])'); // allAs.each(function () { // var a = this; // $.get(a.href, function (_data) { // fastCache[a.href] = _data; // }); // }); } function onFastLoaded(_data, _href, _history, _target = null) { if (!Number.isInteger(_data)) { _data = '
Error on page: ' + _href + '
'); hideMask(); hideMoeFormMask(); } appendRedirectUrl(); } else { // fallback let msg = 'Unable to open page: '; switch (_data) { case 403: msg = 'You do not have access to this page: '; break; case 404: msg = 'Page not found: '; break; case 500: msg = 'Error on page: '; break; case 0: // not logged in - refresh top level window to go to login window.top.location = '/'; break; } console.warn('MC: Target page failed: ' + _href); $('.stag-content').first().html('' + _data + ' - ' + msg + '' + _href + '
'); hideMask(); hideMoeFormMask(); appendRedirectUrl(); } $('html, body').removeClass('no-scroll'); } function appendRedirectUrl(_url) { let targetLocation = window.top.location.pathname + window.top.location.search; if(targetLocation.indexOf('/mc') === 0) { targetLocation = targetLocation.substr(3); } let form = $('.frm-back-to-admin'); if(form.length) { form.attr('action', form.attr('data-action') + '?redir=' + targetLocation); } } var fastReload = function(_target = null) { var targetLocation = window.top.location.pathname + window.top.location.search; if(targetLocation.indexOf('/mc') === 0) { targetLocation = targetLocation.substr(3); } if(targetLocation === '' || targetLocation[0] !== '/') targetLocation = '/' + targetLocation; fastLoad(targetLocation, false, false, false, _target); return false; } function fastLoad(_href, _history = true, _useCache = true, _replaceState = false, _target = null) { let domPro = $(window.top.document.body).attr('data-pro-uid'), lsPro = window.top.localStorage.currentProUid; if(lsPro && domPro && lsPro !== domPro) { console.warn('ALIX Looks like you have a session as another pro on another tab. Refreshing window.top...'); window.top.location.href = _href; return false; } showMask(); if (_href === '') _href = '/'; // push state if (_history && window.parent === window.top) { var target = _href; if (target.indexOf('//') !== -1) { target = target.split('//')[1]; if (target.indexOf('/') !== -1) { target = target.substr(target.indexOf('/') + 1); } } if (target[0] === '/') target = target.substr(1); if (_replaceState) { window.top.history.replaceState(target, null, '/mc/' + target); } else { window.top.history.pushState(target, null, '/mc/' + target); } } // dont show top nav if in iframe if(window !== window.top && window.parent !== window.top) { $('body').addClass('in-iframe'); } if (_useCache && !!fastCache[_href]) { onFastLoaded(fastCache[_href], _href, _history, _target); } else { let cleanedHREF = _href; if(cleanedHREF.length > 1 && cleanedHREF[cleanedHREF.length - 1] === '/') { cleanedHREF = cleanedHREF.substr(0, cleanedHREF.length - 1); } if(cleanedHREF.length > 2) { cleanedHREF = cleanedHREF.replace('/?', '?'); } if(cleanedHREF.length > 0 && cleanedHREF[0] === '?') cleanedHREF = '/' + cleanedHREF; $.get(cleanedHREF, function (_data) { onFastLoaded(_data, _href, _history, _target); }).fail(function (_jqXhr) { onFastLoaded(_jqXhr.status, _href, _history, _target); }); } } function initPrimaryForm(_form = false) { var primaryForm = _form ? _form : $('.primary-form:visible'); if (primaryForm.length) { primaryForm = primaryForm.first(); var rte = primaryForm.find('[contenteditable="true"]').first(); if (rte.length) { rte.focus().select(); } else { if (primaryForm.find('[autofocus]:visible').length) { primaryForm.find('[autofocus]:visible').first().focus().select(); } else { primaryForm.find('input:not([type="hidden"]):visible, textarea:visible, select:visible').first().focus().select(); } } } } function openInRHS(_url) { window.top.showRHS(); var icon = $('.stag_rhs_toggle i'); icon.removeClass().addClass('fa fa-arrow-right'); window.top.openInRHS(_url); return false; } function initCreateNote() { $(document) .off('click.create-note', '.create-auto-note-trigger') .on('click.create-note', '.create-auto-note-trigger', function () { createNewNote($(this).attr('data-patient-uid'), $(this).attr('data-hcp-uid'), $(this).attr('data-effective-date')); }); if ($('select[name="hasMcpDoneOnboardingVisit"]').length) { $('select[name="hasMcpDoneOnboardingVisit"]').trigger('change'); } } function createNewNote(_patientUid, _hcpUid, _date) { hideMoeFormMask(); showMask(); $.post('/api/note/createUsingFreeTextHtml', { clientUid: _patientUid, hcpProUid: _hcpUid, effectiveDateEST: _date, }, function (_data) { hideMask(); if (!_data.success) { toastr.error(_data.message); } else { fastLoad('/patients/view/' + _patientUid + '/notes/view/' + _data.data, true, false); } }, 'json'); } function initQuillEdit(_selector = '.note-content[auto-edit]') { $(document) .off('click.enable-edit', '.note-content:not([auto-edit]):not(.readonly)') .on('click.enable-edit', '.note-content:not([auto-edit]):not(.readonly)', function () { $(this).attr('auto-edit', 1); initQuillEdit(); initPrimaryForm(); initPatientPresenceIndicator(); }); if (!$(_selector).length) return; var noteUid = $(_selector).attr('data-note-uid'); var qe = new Quill(_selector, { theme: 'snow', modules: stagQuillConfig }); var toolbar = $(qe.container).prev('.ql-toolbar'); var saveButton = $(''); toolbar.append(saveButton); saveButton.on('click', function () { $.post('/api/note/putFreeTextHtml', { uid: noteUid, freeTextHtml: qe.root.innerHTML, }, function (_data) { if (!_data.success) { toastr.error(_data.message); } else { // toastr.success('Note saved'); // saveButton.prop('disabled', true); fastLoad(window.top.location.pathname.substr(3), false, false); } }, 'json'); }); // give a unique id to this editor instance var editorID = Math.ceil(Math.random() * 99999); // add button for new shortcut var newSCButton = $(''); toolbar.append(newSCButton); // qe.on('text-change', function() { // saveButton.prop('disabled', false); // }); $('.ql-editor[contenteditable]') .attr('data-editor-id', editorID) .attr('with-shortcuts', 1); } function initQuillRTE(_selector, _config = false, _shortcuts = false) { if(!_config) _config = stagQuillConfig; $(_selector).each(function() { $(this).wrap( $('') .attr('data-shortcuts', '') ); // give a unique id to this editor instance var editorID = Math.ceil(Math.random() * 99999), fieldName = this.name; var ti = $('') .val(this.value) .attr('name', this.name) .insertBefore(this); var ce = $('') .html(this.value) .insertBefore(this); $(this).remove(); var qe = new Quill('[data-editor-id="' + editorID + '"]', { theme: 'snow', modules: _config ? _config : stagQuillConfig }); var toolbar = $(qe.container).prev('.ql-toolbar'); // add button for new shortcut if(_shortcuts) { var newSCButton = $(''); toolbar.append(newSCButton); } qe.on('text-change', function() { ti.val(qe.root.innerHTML); }); $(qe.container) .find('.ql-editor[contenteditable]') .attr('data-field', fieldName) .attr('data-editor-id', editorID) .attr('with-shortcuts', 1); }); } var patientPresenceTimer = false; function initFileInputs() { $(document) .off('change', 'input[type="file"]') .on('change', 'input[type="file"]', function(_e) { if(_e.target.files && _e.target.files.length) { $(this).attr('selected-file', _e.target.files[0].name); } else { $(this).attr('selected-file', 'No file chosen'); } return false; }); $('input[type="file"]').attr('selected-file', 'No file chosen'); } function initPatientPresenceIndicator() { return false; if (patientPresenceTimer !== false) { window.clearInterval(patientPresenceTimer); patientPresenceTimer = false; console.log('Cancelled previous timer!'); } var elem = $('.patient-presence-indicator[data-patient-uid]'); if (elem.length) { var patientUid = elem.attr('data-patient-uid'); patientPresenceTimer = window.setInterval(function () { var elem = $('.patient-presence-indicator[data-patient-uid]'); if (elem.length) { var patientUid = elem.attr('data-patient-uid'); $.get('/patients/' + patientUid + '/presence', function (_data) { if (_data.online) { elem.addClass('online'); } else { elem.removeClass('online'); } }, 'json'); } }, 15000); // once in 15 seconds } } // not really the place for this! // find a better place to put this window.fillJsonDataField = function(form, field = "data") { // add [data-name] values to payload if(form.is('[data-field-name]')) { field = form.attr('data-field-name'); } let dataField = form.find('[name="' + field + '"]').first(); let parsed = null; if(dataField.val()) { parsed = JSON.parse(dataField.val()); } form.find('[data-name]').each(function() { if(!parsed) parsed = {}; let keys = $(this).attr('data-name').split('->'); let currentNode = parsed; for (let i = 0; i < keys.length; i++) { if(i !== keys.length - 1) { if(typeof currentNode[keys[i]] === 'undefined') { currentNode[keys[i]] = {}; } currentNode = currentNode[keys[i]]; } else { if($(this).is(':radio')) { if($(this).prop('checked')) { currentNode[keys[i]] = this.value; } } else if($(this).is(':checkbox')) { currentNode[keys[i]] = $(this).prop('checked'); } else { currentNode[keys[i]] = $(this).val(); } } } }); if(parsed) { dataField.val(JSON.stringify(parsed)); } return parsed; } window.saveVisitForm = function(_trigger, _silent = false, _close = false, _doneCallback = null) { let form = $(_trigger).closest('form'); if (!_silent && !form[0].checkValidity()) { form[0].reportValidity(); return false; } let parsed = fillJsonDataField(form); let closeOnSave = false, noteSection = form.closest('.note-section'); if($(_trigger).closest('[visit-moe]').is('[close-on-save]')) { closeOnSave = true; } // disallow-if-value-same-as let compareWith = false; if(form.find('.disallow-if-value-same-as')) { compareWith = $.trim(form.find('.disallow-if-value-same-as').text()); if(compareWith && parsed) { if(!parsed.value) { alert('Value cannot be empty!'); return false; } let newValue = $('').html(parsed.value).text().replace(/[^a-zA-Z0-9]/g, ''); if(newValue === '') { alert('Value cannot be empty!'); return false; } if(newValue === compareWith) { alert('New value should be different from the previous value!'); return false; } } } if(!_silent) showMask(); $.post(form.attr('url'), form.serialize(), _data => { if(!hasResponseError(_data)) { if(typeof window.updateAllSegmentsInResponse !== 'undefined') { window.updateAllSegmentsInResponse(_data, true, _silent); // if /api/visitPoint/upsertChildReview - refresh subjective_general_v2 // if /api/visitPoint/upsertChildPlan - refresh plan_free_text_v2 let parentPopup = form.closest('.stag-popup'); let eps = [ '/api/visitPoint/upsertChildReview', '/api/visitPoint/upsertChildPlan', '/api/visitPoint/destroyCurrentChildReview', '/api/visitPoint/destroyCurrentChildPlan', '/api/visitPoint/addTopLevelBulkPreExisting' ]; if(parentPopup.length && eps.indexOf(form.attr('url')) !== -1) { if(parentPopup.attr('stag-popup-key').indexOf('past_medical_history/edit') !== -1) { $('.visit-segment[data-segment-template-name="omega_history_past_medical"]').find('.refresh-segment').trigger('click'); } else if(parentPopup.attr('stag-popup-key').indexOf('history_family/edit') !== -1) { $('.visit-segment[data-segment-template-name="omega_history_family"]').find('.refresh-segment').trigger('click'); } else if(parentPopup.attr('stag-popup-key').indexOf('history_social/edit') !== -1) { $('.visit-segment[data-segment-template-name="omega_history_social"]').find('.refresh-segment').trigger('click'); } else if(parentPopup.attr('stag-popup-key').indexOf('history_surgical/edit') !== -1) { $('.visit-segment[data-segment-template-name="omega_history_surgical"]').find('.refresh-segment').trigger('click'); } else if(parentPopup.attr('stag-popup-key').indexOf('allergies-center') !== -1) { $('.visit-segment[data-segment-template-name="omega_allergies"]').find('.refresh-segment').trigger('click'); } else if(parentPopup.attr('stag-popup-key').indexOf('medications-center') !== -1) { $('.visit-segment[data-segment-template-name="omega_medications"]').find('.refresh-segment').trigger('click'); } else if(parentPopup.attr('stag-popup-key').indexOf('problems-center') !== -1) { $('.visit-segment[data-segment-template-name="omega_problems"]').find('.refresh-segment').trigger('click'); } else if(parentPopup.attr('stag-popup-key').indexOf('goals-center') !== -1) { $('.visit-segment[data-segment-template-name="omega_goals"]').find('.refresh-segment').trigger('click'); } else if(parentPopup.attr('stag-popup-key').indexOf('careteam-center') !== -1) { $('.visit-segment[data-segment-template-name="omega_care_team"]').find('.refresh-segment').trigger('click'); } } // refresh omega_xxx_system on ALL changes $('.visit-segment[data-segment-template-name="omega_subjective_system"]').find('.refresh-segment').trigger('click'); // $('.visit-segment[data-segment-template-name="omega_objective_system"]').find('.refresh-segment').trigger('click'); $('.visit-segment[data-segment-template-name="omega_assessment_system"]').find('.refresh-segment').trigger('click'); $('.visit-segment[data-segment-template-name="omega_plan_system"]').find('.refresh-segment').trigger('click'); } if(typeof window.refreshRHSSidebar !== 'undefined') { window.refreshRHSSidebar(); } if(!_silent) { hideMask(); if(noteSection.length) { if (closeOnSave) { noteSection.removeClass('edit'); let segmentUid = form.find('[name="segmentUid"]').first(); segmentUid = segmentUid.length ? segmentUid.val() : false; if (segmentUid) { window.setTimeout(() => { $('.note-tree-node>a[data-segment-uid="' + segmentUid + '"]').trigger('click'); }, 250); } } } if($(_trigger).closest('[visit-moe]').closest('.stag-popup').length) { refreshDynamicStagPopup(); } } if(_close) { closeStagPopup(); } if(!!_doneCallback) { _doneCallback(); } } }, 'json'); return false; }; window.initSegmentMoes = function(_parent) { $('body') .off('mousedown.visit-moe-outside-click') .on('mousedown.visit-moe-outside-click', function (e) { if ($(e.target).closest('[visit-moe]').length || $(e.target).closest('#create-shortcut-form').length || $(e.target).is('#create-shortcut-form') || $(e.target).is('.stag-shortcuts .sc') || $(e.target).closest('.ui-datepicker').length) { return; } $('[visit-moe] [url]:not([show])').hide(); }); _parent.find('[visit-moe] [submit]') .off('click.visit-moe-submit') .on('click.visit-moe-submit', function() { saveVisitForm(this); return false; }); _parent.find('[visit-moe]>a[start]') .off('click.visit-moe-show') .on('click.visit-moe-show', function () { $('[visit-moe] [url]:not([show])').hide(); let form = $(this).closest('[visit-moe]').find('form[url]'); form.show(); if(!form.is('[no-auto-focus]')) { setTimeout(() => { form.find('.ql-editor').first().focus(); }, 0); } return false; }); _parent.find('[visit-moe] [cancel]') .off('click.visit-moe-cancel') .on('click.visit-moe-cancel', function() { $(this).closest('[visit-moe]').find('[url]:not([show])').hide(); if($(this).closest('[visit-moe]').is('[close-on-cancel]')) { $(this).closest('.note-section').removeClass('edit'); } return false; }); $(document) .off('keydown.visit-moe-escape') .on('keydown.visit-moe-escape', function (e) { if(e.which === 27) { if(!isEventConsumed(e)) { let visibleMoes = $('[visit-moe] [url]:not([show]):visible'); if (visibleMoes.length) { visibleMoes.hide(); markEventAsConsumed(e); return false; } } } }); }; window.isEventConsumed = function(_e) { return _e && _e.originalEvent && _e.originalEvent.stagCosumed }; window.markEventAsConsumed = function(_e) { if(_e && _e.originalEvent) { _e.originalEvent.stagCosumed = true; } };