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 = '<div>' + _data + '</div>';

        // do for each element in _target
        let responseError = false;
        let originalTarget = _target;
        _target = _target ? _target : '.stag-content';
        _target = _target.split(',').map(_x => $.trim(_x));
        for (let i = 0; i < _target.length; i++) {
            let t = _target[i];
            let targetElement = $(t).first();
            if(targetElement.length) {
                let sourceElement = $(_data).find(t).first();
                if (sourceElement && sourceElement.length) {
                    targetElement.html(sourceElement.html());
                    initFastLoad(targetElement);
                    console.log('ALIX loaded element: ' + t);
                }
                else {
                    responseError = true;
                }
            }
            else {
                responseError = true;
            }
        }

        if (!responseError) {
            hideMask();
            hideMoeFormMask();
            window.setTimeout(function () {
                initCreateNote();
                initQuillEdit();
                initPrimaryForm();
                initPatientPresenceIndicator();
                initFileInputs();
                initMoes();
                runMCInitializers(originalTarget);
                if (window.top.currentMcUrl.split('?')[0] !== window.top.location.href.split('?')[0]) {
                    $(window).scrollTop(0);
                }
                window.top.currentMcUrl = window.top.location.href;
            }, 0);
        }
        else {
            $('.stag-content').first().html('<p class="text-danger p-3 small">Error on page: <b>' + _href + '</b></p>');
            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('<p class="text-danger p-3 small"><b>' + _data + '</b> - ' + msg + '<b>' + _href + '</b></p>');
        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 = $('<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);
}

function initQuillRTE(_selector, _config = false, _shortcuts = false) {
    if(!_config) _config = stagQuillConfig;
    $(_selector).each(function() {

        $(this).wrap(
            $('<div class="border-left border-right rte-holder"/>')
                .attr('data-shortcuts', '')
        );

        // give a unique id to this editor instance
        var editorID = Math.ceil(Math.random() * 99999),
            fieldName = this.name;

        var ti = $('<input type="hidden" />')
            .val(this.value)
            .attr('name', this.name)
            .insertBefore(this);
        var ce = $('<div data-editor-id="' + editorID + '" data-field="' + this.name + '"/>')
            .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 = $('<button class="btn bg-white btn-sm btn-default text-primary w-auto px-2 border py-0 ' +
                'text-sm add-shortcut" data-editor-id="' + editorID + '">+ Shortcut</button>');
            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.refreshSegment = function(_segment) {
    $('.visit-segment[data-segment-template-name="' + _segment + '"]').find('.refresh-segment').trigger('click');
};
window.refreshAffectedSegmentsByType = function(_type) {
    if(!_type) {
        console.error('refreshAffectedSegmentsByType: _type cannot be empty!');
        return;
    }
    let segments = window.segmentRefreshConfig.typeToSegments[_type];
    if(segments && segments.length) {
        for (let i = 0; i < segments.length; i++) {
            refreshSegment(segments[i]);
        }
    }
    else {
        if(!_type) {
            console.error('refreshAffectedSegmentsByType: no segments to refresh for type:', _type);
        }
    }
};
window.refreshAffectedSegmentsByPopupKey = function(_key) {
    let types = [];
    for(let x in window.segmentRefreshConfig.wizardToTypes) {
        if(window.segmentRefreshConfig.wizardToTypes.hasOwnProperty(x) && _key.indexOf(x) !== -1) {
            types.push(window.segmentRefreshConfig.wizardToTypes[x]);
            break;
        }
    }
    for (let i = 0; i < types.length; i++) {
        refreshAffectedSegmentsByType(types[i]);
    }
    let segments = [];
    for(let x in window.segmentRefreshConfig.wizardToSegments) {
        if(window.segmentRefreshConfig.wizardToSegments.hasOwnProperty(x) && _key.indexOf(x) !== -1) {
            segments = window.segmentRefreshConfig.wizardToSegments[x];
            break;
        }
    }
    for (let i = 0; i < segments.length; i++) {
        refreshSegment(segments[i]);
    }
};
window.saveVisitForm = function(_trigger, _silent = false, _close = false, _doneCallback = null) {
    console.info("saveVisitForm");
    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 = $('<div/>').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);
            }
            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) {
                refreshAffectedSegmentsByPopupKey(parentPopup.attr('stag-popup-key'));
            }
            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;
    }
};