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 () {


    if(!window.noMc){
        if (window.location.pathname === window.top.location.pathname) {
            window.top.location.href = '/mc' + window.location.pathname;
            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();

    // if(typeof initializeCalendar !== 'undefined') {
    //     initializeCalendar();
    // }
    // if(typeof initIntakeEvents !== 'undefined') {
    //     initIntakeEvents();
    // }

    // populate history on fresh load
    var target = window.top.location.pathname;
    if (target.indexOf('/mc') === 0) {
        target = target.split('/mc')[1];
    }
    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])');
    if (_parent) {
        allAs = _parent.find('a[href]:not([onclick]):not([href="#"]):not([native])');
    }

    // 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[aria-labelledby="practice-management"]').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[aria-labelledby="practice-management"]')
                    .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) {
    var targetParent = $('.stag-content');
    _data = '<div>' + _data + '</div>';
    var content = $(_data).find('.stag-content');
    if (content && content.length) {

        targetParent.html(content.html());
        hideMask();
        hideMoeFormMask();
        targetParent.append('<script src="/js/yemi.js?_=7"></script>');
        window.setTimeout(function() {
            initCreateNote();
            initQuillEdit();
            initFastLoad(targetParent);
            initPrimaryForm();
            initPatientPresenceIndicator();
            runMCInitializers();
            $(window).scrollTop(0);
        }, 50);
        // if(typeof initializeCalendar !== 'undefined') {
        //     initializeCalendar();
        // }
        // if(typeof initIntakeEvents !== 'undefined') {
        //     initIntakeEvents();
        // }
    } else {
        // fallback
        console.warn('MC: Target page failed: ' + _href);
        targetParent.html('<p class="text-danger p-3 small">Target page not found or returned error: <b>' + _href + '</b></p>');
        hideMask();
        hideMoeFormMask();
    }
    $('html, body').removeClass('no-scroll');
}
function fastLoad(_href, _history = true, _useCache = true, _replaceState = false) {

    showMask();

    if (_href === '') _href = '/';

    // push state
    if (_history) {
        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);
            // console.log('ALIX replaceState: [' + target + ']');
        }
        else {
            window.top.history.pushState(target, null, '/mc/' + target);
            // console.log('ALIX pushState: [' + target + ']');
        }
    }

    if (_useCache && !!fastCache[_href]) {
        onFastLoaded(fastCache[_href], _href, _history);
    } else {
        $.get(_href, function (_data) {
            onFastLoaded(_data, _href, _history);
        }).fail(function () {
            onFastLoaded('error', _href, _history);
        });
    }
}

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 = $('<button class="btn btn-sm btn-primary w-auto px-3 py-0 text-sm text-white save-note-content">Save</button>');
    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 = $('<button class="btn btn-sm btn-default w-auto px-2 ml-2 border py-0 ' +
        'text-sm add-shortcut" data-editor-id="' + editorID + '">+ Shortcut</button>');
    toolbar.append(newSCButton);

    // qe.on('text-change', function() {
    //     saveButton.prop('disabled', false);
    // });
    $('.ql-editor[contenteditable]')
        .attr('data-editor-id', editorID)
        .attr('with-shortcuts', 1);
}

var patientPresenceTimer = false;
function initPatientPresenceIndicator() {
    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
    }
}
