if (typeof focusOn == 'undefined') {
    var focusOn = 'globalSearch';
}

var ajaxGoing = false;

var showMask = function (_text = '') {
    $('body').css('opacity', 0.6);
    $('#mask').show();
    if(!!_text) {
        $('<div class="mask-text-addition" />').text('Initializing note. Please wait...').appendTo('body');
    }
}

var hideMask = function () {
    $('body').css('opacity', 1);
    $('#mask').hide();
    $('.mask-text-addition').remove();
}

var showMoeFormMask = function (_additionalClass = false) {
    if(_additionalClass) {
        $('#moe-form-mask').addClass(_additionalClass);
    }
    $('#moe-form-mask').show();
}

var hideMoeFormMask = function () {
    if($('body').is('.blocking-mode')) return false;
    $('#moe-form-mask').hide().removeClass();
    $('#create-shortcut-form').hide();
}

$(document).ready(function () {
    hideMask();
});

$(document).ready(function () {
    $("input[type=number]").keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
            // Allow: Ctrl+A, Command+A
            (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) ||
            // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
            // let it happen, don't do anything
            return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });
});

$(function () {
    $('input[type=checkbox][forceCb]').on('click', function () {
        var name = $(this).attr('forceCb');
        var code = $(this).attr('code');
        var form = $(this).closest('form');
        var hiddenField = $(form).find('input[code=\'' + code + '\']');
        var value = $(this).prop('checked') ? 'on' : 'off';
        console.log('name', name, 'code', code, 'value', value);
        $(hiddenField).val(value);
    });
});

var doAjax = function (url, data, pre, post, onSuccess, onFailure, suppressErrorMessage, onHttpFailure, shouldHideMask, immediatelyHideMaskOnReply) {
    console.log(data);
    if (ajaxGoing) {
        console.log('ajax stopped!');
        //return; TODO: fix and re-enable return
    }
    ajaxGoing = true;
    if (!shouldHideMask) {
        showMask();
    }
    jQuery.ajax(url, {
            dataType: 'json',
            data: data,
            type: 'POST',
            beforeSend: function () {
                if (pre) {
                    pre();
                }
            }
        })
        .done(function (response, b) {
			console.log(response);
            var success = response.success;
            if (success) {
                if (onSuccess) {
                    onSuccess(response.data);
                }
            } else {
                if (onFailure) {
                    onFailure(response.message);
                }
                if (!suppressErrorMessage) {
                    //toast the error message
                    //alert(response.message);
                    toastr.error(response.message); // , toastr.success("message") ... .warning(), .error()
                }
                hideMask();
            }
            if (immediatelyHideMaskOnReply) {
                hideMask();
            }
            ajaxGoing = false;
        })
        .fail(function (jqXHR, textStatus) {
            hideMask();
            toastr.error('Unable to process');
            if (onHttpFailure) {
                onHttpFailure(textStatus);
            }
            ajaxGoing = false;
        })
        .always(function () {
            if (post) {
                post();
            }
            ajaxGoing = false;
        });
};

var justLog = false; //THIS IS FOR TEST MODE, FORMS WILL NOT TRIGGER REFRESH/REDIR

var pageReload = function () {
    setTimeout(function () {
        hideMoeFormMask();
        fastReload();
    }, 500);
};

var fastReload = function() {
    var targetLocation = window.top.location.pathname;
    if(targetLocation.indexOf('/mc') === 0) {
        targetLocation = targetLocation.substr(3);
    }
    if(targetLocation === '' || targetLocation[0] !== '/') targetLocation = '/' + targetLocation;
    fastLoad(targetLocation, false, false);
}

if (typeof String.prototype.startsWith != 'function') {
    // see below for better implementation!
    String.prototype.startsWith = function (str) {
        return this.indexOf(str) === 0;
    };
}

$(function () {
    $('[addressLine1]').each(function () {
        var moe = $(this).closest('[moe]');
        var a = {};
        a.addressLine1 = $(this);
        a.addressLine2 = $(moe).find('[addressLine2]');
        a.addressCity = $(moe).find('[addressCity]');
        a.addressState = $(moe).find('[addressState]');
        a.addressPostcode = $(moe).find('[addressPostcode]');
        var getAddress = function () {
            var address = {};
            for (var prop in a) {
                var val = $(a[prop]).val();
                address[prop] = val;
            }
            return address;
        }
        var getFormattedAddress = function (address) {
            var x = '<p>';
            x += address.addressLine1 + (address.addressLine2 ? ', ' + address.addressLine2 : '') + '<br/>' + address.addressCity + ', ' + address.addressState + ' ' + address.addressPostcode;
            x += '</p>';
            return x;
        }
        var suggestAddress = function () {
            var address = getAddress();
            //var doAjax = function (url, data, pre, post, onSuccess, onFailure, suppressErrorMessage, onHttpFailure, shouldHideMask)
            var onSuccess = function (data) {
                console.log('SUCCESS!!!', data);
            }
            var onFailure = function (message) {
                if (message.startsWith('Invalid:: INVALID ADDRESS - SUGGESTED:')) {
                    var suggestionText = message.substring(message.indexOf('{'));
                    var suggestion = JSON.parse(suggestionText);
                    console.log('SUGGESTION!!!', suggestion);
                    $('#myModal').attr('title', 'Address suggestion');
                    $('#myModal').html('<h3>Currently set address:</h3>' + getFormattedAddress(address) + '<h3>Suggestion:</h3>' + getFormattedAddress(suggestion));
                    $('#myModal').dialog({
                        height: 400,
                        width: 500,
                        modal: true,
                        buttons: [{
                                text: 'Use suggestion',
                                click: function () {
                                    for (var prop in a) {
                                        $(a[prop]).val(suggestion[prop]);
                                    }
                                    $(this).dialog('close');
                                }
                            },
                            {
                                text: 'Keep original',
                                click: function () {
                                    $(this).dialog('close');
                                }
                            }
                        ]
                    });
                } else if (message.startsWith('Invalid:: INVALID ADDRESS')) {
                    console.log('NO SUGGESTION!!!');
                    $('#myModal').attr('title', 'No address found');
                    $('#myModal').html('<h3>Currently set address:</h3>' + getFormattedAddress(address) + '<h3>No suggestion!</h3>');
                    $('#myModal').dialog({
                        height: 400,
                        width: 500,
                        modal: true,
                        buttons: [{
                                text: 'Erase address fields',
                                click: function () {
                                    for (var prop in a) {
                                        $(a[prop]).val('');
                                    }
                                    $(this).dialog('close');
                                }
                            },
                            {
                                text: 'Keep original',
                                click: function () {
                                    $(this).dialog('close');
                                }
                            }
                        ]
                    });
                }
            }
            doAjax('/api/service/verifyAddress', address, null, null, onSuccess, onFailure, true, null, false, true);
        }
        var isAddressComplete = function () {
            var address = getAddress();
            return address.addressLine1 && ((address.addressCity && address.addressState) || address.addressPostcode) ? true : false;
        }
        for (var prop in a) {
            var part = a[prop];
            $(part).on('change', function () {
                console.log(getAddress());
                var isComplete = isAddressComplete();
                if (isComplete) {
                    suggestAddress();
                }
            });
            $(part).attr('autocomplete', 'off');
        }
    });
});

var initMoes = function() {
    $('[moe]').each(function () {

        if($(this).is('[initialized]')) { // skip to next moe
            return true;
        }

        var moe = $(this);
        moe.isProcessing = false;
        var info = moe.find('[info]')[0]; // OPTIONAL
        var start = moe.find('[start]')[0]; // OPTIONAL
        var form = moe.find('[url]')[0]; // REQUIRED
        var url = $(form).attr('url'); // REQUIRED
        var redir = $(form).attr('redir'); // OPTIONAL
        var submit = moe.find('[submit]'); // REQUIRED
        var cancel = moe.find('[cancel]')[0]; // OPTIONAL

        // ajax load - OPTIONAL
        var moeParent = $(form).closest('[moe-parent][url]');

        if ($(this).attr('formOff') != null) {
            $(form).find(':input').attr('disabled', true);
            var formOn = $(this).find('[formOn]');
            $(formOn).attr('disabled', false);
            $(submit).hide();
            $(formOn).click(function () {
                $(form).find(':input').attr('disabled', false);
                $(submit).show();
                $(formOn).hide();
                return false;
            });
        }

        var realForm = form;

        //init set display inline so toggle remembers inline state
        var formToggle = false;
        var infoToggle = false;

        if (start) {
            $(start).off('click.moe');
            $(start).on('click.moe', function () {

                // if any div based moes are visible, hide first
                $('[moe]>div[url]:visible').hide();

                $('.dropdown-menu[aria-labelledby="practice-management"]')
                    .removeClass('show')
                    .prev('.dropdown-toggle').attr('aria-expanded', 'false');
                if ($(realForm).attr('show') == null) {
                    if (!formToggle && $(realForm).attr('liner') != null) {
                        $(realForm).css('display', 'inline');
                        formToggle = true;
                    } else {
                        var isRealFormVisible = $(realForm).is(':visible');
                        if(isRealFormVisible){
                            hideMoeFormMask();
                            $(realForm).toggle(100);
                        }else{
                            // keep data in moes, don't force reset
                            // if($(realForm).is('form')) $(realForm)[0].reset();
                            if(!$(realForm).closest('[moe]').is('[no-mask]')) {
                                showMoeFormMask();
                            }
                            setTimeout(function() {
                                $('[moe]>[url]:not([show]):visible').hide();
                                $(realForm).toggle(100);
                                initPrimaryForm($(realForm));
                                setTimeout(function() {
                                    let submitButton = $(realForm).find('[submit]');
                                    if(submitButton.length) submitButton[0].scrollIntoView({behavior : "smooth", block: "nearest"});

                                    // if any callback, trigger it
                                    if($(realForm).is('[onshow]')) {
                                        window[$(realForm).attr('onshow')].call($(realForm)[0]);
                                    }

                                }, 150);
                            }, 100);
                        }
                    }
                }
                if (!infoToggle && info && $(info).attr('show') == null) {
                    if ($(info).attr('liner') != null) {
                        $(info).css('display', 'inline');
                        infoToggle = true;
                    } else {
                        $(info).toggle(100);
                    }
                }
                if ($(start).attr('show') == null) {
                    $(start).toggle(100);
                }
                var focusOnStart = $(realForm).find('[focusOnStart]');
                if (focusOnStart) {
                    $(focusOnStart).focus();
                }
                return false;
            });
            $(start).attr('href', '#');
        }
        if (cancel) {
            $(cancel).off('click.moe');
            $(cancel).on('click.moe', function (e) {
                e.preventDefault();
                e.stopImmediatePropagation();
                if ($(realForm).attr('show') == null) {
                    $(realForm).hide(100);
                }
                if (info && $(info).attr('show') == null) {
                    $(info).show(100);
                }
                if (start && $(start).attr('show') == null) {
                    $(start).show(100);
                }
                hideMoeFormMask();
            });
        }
        $(submit).off('click.moe');
        $(submit).on('click.moe', function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            if (moe.isProcessing) {
                return false;
            }
            if ($(submit).attr('confirm')) {
                var question = $(submit).attr('confirm');
                var cont = confirm(question);
                if (cont) {} else {
                    console.log("ABORTED!");
                    return;
                }
            }

            if($(form).is('form')) {

                // trigger validation
                if (!$(form)[0].checkValidity()) {
                    $(form)[0].reportValidity();
                    return;
                }

                // check and trigger onbeforesubmit
                if($(form).is('[onbeforesubmit]')) {
                    window[$(form).attr('onbeforesubmit')].call($(realForm)[0]);
                }

                // submit
                moe.isProcessing = true;
                var data = {};
                var formData = $(form).serializeArray();
                formData.forEach(function (field) {
                    if (data[field.name]) {
                        if (data[field.name] instanceof Array) {
                            data[field.name].push(field.value);
                        } else {
                            var arr = [];
                            arr.push(data[field.name]);
                            arr.push(field.value);
                            data[field.name] = arr;
                        }
                    } else {
                        data[field.name] = field.value;
                    }
                });
                console.log(data);
                //var doAjax = function (url, data, pre, post, onSuccess, onFailure, suppressErrorMessage, onHttpFailure, shouldHideMask, immediatelyHideMaskOnReply)
                doAjax(url, data, null, function () {
                    moe.isProcessing = false;
                }, function (data) {
                    if (justLog) { // this is to test!
                        console.log('RETURNED', data);
                    } else if (redir) {
                        if (redir == "back") {
                            window.top.history.back();
                        } else {
                            if (redir.indexOf('[data]') > -1) {
                                redir = redir.replace('[data]', data);
                            }
                            fastLoad(redir, true, false);
                        }
                    } else if (moeParent.length) {
                        showMask();
                        $.get(moeParent.attr('url'), function (_data) {
                            moeParent.html(_data);
                            hideMask();
                            hideMoeFormMask();
                            initMoes();
                            initFastLoad(moeParent);
                            initAutoRxAndICDComplete();
                        });
                    } else {
                        pageReload();
                    }
                }, function (errorMessage) {

                }, false);
            }
        });

        moe.attr('initialized', 1); // mark as initialized

    });
}

jQuery(document).ready(function () {
    var $ = jQuery;
    $('body').mousedown(function(e){
        if($(e.target).closest('[moe]').length ||
            $(e.target).closest('#create-shortcut-form').length ||
            $(e.target).is('#create-shortcut-form') ||
            $(e.target).is('.stag-shortcuts .sc')){
            return;
        }
        $('[moe] [url]:not([show])').hide();
        hideMoeFormMask();
    });

    initMoes();

    $('table[info] input').each(function () {
        $(this).prop('readonly', true);
    });

    //...for checkboxes readonly
    $('input[type=checkbox][readonly],input[type=radio][readonly]').each(function () {
        var x = this;
        var isChecked = $(x).attr('checked');
        $(x).change(function () {
            $(x).attr('checked', isChecked);
        });
    });

    $('[show-if]').each(function () { //TODO show-if="isOpen"    show-if="isTimeSpecific"    show-if="refillFrequency=MONTH"
        var x = this;
        var sel = $(x).attr('show-if');
        var selParts = sel.split('=');
        var selName = selParts[0];
        var selValue = selParts[1];
        var useOpposite = selName[0] == '!';
        if (useOpposite) {
            selName = selName.slice(1);
        }
        var form = $(x).closest('form');
        var conditionFields = $(form).find('[name=' + selName + ']');

        function hideX() {
            $(x).hide();
        }

        function showX() {
            $(x).show();
        }
        var go = function () {
            if (selValue) {
                var value = $(conditionFields).val();
                if (value == selValue) {
                    if (useOpposite) {
                        hideX()
                    } else {
                        showX()
                    }
                } else {
                    if (useOpposite) {
                        showX()
                    } else {
                        hideX()
                    }
                }
            } else {
                var isChecked = $(conditionFields).prop('checked');
                if (isChecked) {
                    if (useOpposite) {
                        hideX()
                    } else {
                        showX()
                    }
                } else {
                    if (useOpposite) {
                        showX()
                    } else {
                        hideX()
                    }
                }
            }
        };
        go();
        $(conditionFields).change(function () {
            go();
        });
    });

});

//now goTo is a plugin...
(function ($) {
    $.fn.goTo = function (x) {
        $('html, body').animate({
            scrollTop: ($(this).offset().top - x) + 'px'
        }, 1);
        return this; // for chaining...
    };
})(jQuery);

$(document).ready(function () {
    $(".expander").on("click", function () {
        var expandedID = $(this).attr("id");
        if ($(this).text() == "-") {
            $(this).text("+");
        } else {
            $(this).text("-");
        }
        $("." + expandedID).toggle();
        return false;
    });
});



$(document).ready(function () {
    $('[showMap]').each(function () {
        var mapper = $(this);
        var adr = mapper.attr('showMap');
        mapper.on('click', function () {
            showAddr(adr);
            return false;
        });
    });
});


$(document).ready(function () {
    $('[dateRanger]').each(function () {
        var dr = $(this);
        var rangeTypeSelect = dr.find('select')[0];
        var date1Input = dr.find('[date1]')[0];
        var date2Input = dr.find('[date2]')[0];
        var d1Val = '';
        var d2Val = '';
        var d1 = function (enable) {
            if (enable) {
                var hasVal = $(date1Input).val();
                if (!hasVal) {
                    $(date1Input).val(d1Val);
                }
                $(date1Input).show();
            } else {
                d1Val = $(date1Input).val();
                $(date1Input).val('');
                $(date1Input).hide();
            }
        };
        var d2 = function (enable) {
            if (enable) {
                var hasVal = $(date2Input).val();
                if (!hasVal) {
                    $(date2Input).val(d2Val);
                }
                $(date2Input).show();
            } else {
                d2Val = $(date2Input).val();
                $(date2Input).val('');
                $(date2Input).hide();
            }
        };
        var adjustFields = function () {
            var rangeType = $(rangeTypeSelect).val();
            if (rangeType == 'all') {
                d1();
                d2();
            } else if (rangeType == 'on-or-before') {
                d1(true);
                d2();
            } else if (rangeType == 'on-or-after') {
                d1(true);
                d2();
            } else if (rangeType == 'between') {
                d1(true);
                d2(true);
            } else if (rangeType == 'on') {
                d1(true);
                d2();
            } else if (rangeType == 'not-on') {
                d1(true);
                d2();
            } else if (rangeType == 'not-in-between') {
                d1(true);
                d2(true);
            }
        };
        adjustFields();
        $(rangeTypeSelect).change(function () {
            adjustFields();
        });
    });
    $('[numRanger]').each(function () {
        var nr = $(this);
        var rangeTypeSelect = nr.find('select')[0];
        var num1Input = nr.find('[num1]')[0];
        var num2Input = nr.find('[num2]')[0];
        var n1 = function (enable) {
            if (enable) {
                $(num1Input).show();
            } else {
                $(num1Input).hide();
            }
        };
        var n2 = function (enable) {
            if (enable) {
                $(num2Input).show();
            } else {
                $(num2Input).hide();
            }
        };
        var adjustFields = function () {
            var rangeType = $(rangeTypeSelect).val();
            if (rangeType == 'all') {
                n1();
                n2();
            } else if (rangeType == 'less-than') {
                n1(true);
                n2();
            } else if (rangeType == 'greater-than') {
                n1(true);
                n2();
            } else if (rangeType == 'equal-to') {
                n1(true);
                n2();
            } else if (rangeType == 'between') {
                n1(true);
                n2(true);
            } else if (rangeType == 'not-equal-to') {
                n1(true);
                n2();
            } else if (rangeType == 'not-in-between') {
                n1(true);
                n2(true);
            }
        };
        adjustFields('all');
        $(rangeTypeSelect).change(function () {
            adjustFields();
        });
    });
});
$(document).ready(function () {
    $('[minzero]').on('change', function () {
        var val = $(this).val();
        val = parseFloat(val);
        if (val < 0) {
            alert('This number cannot be less than zero.');
            $(this).val('');
            $(this).focus();
        }
    });
});

var showAddr = function (adr) {
    window.open('http://192.241.155.210/geo.php?adr=' + adr, new Date().getTime(), "height=400,width=520");
};

$(document).ready(function () {
    var globalSearch = function () {
        var substring = $('#globalSearch').val();
        console.log("SUBSTRING", substring);
        if (substring.length > 2) {
            $("#results").show();
            $("#results").load("/global-search?substring=" + encodeURIComponent(substring));
        } else {
            $("#results").hide();
        }
    };
    $("#globalSearch").on('keyup', function (evnt) {
        globalSearch();
    });
    $("#globalSearch").on('focus', function (evnt) {
        globalSearch();
    });
    $("#globalSearch").on('blur', function (evt) {
        setTimeout(function () {
            $("#results").hide();
        }, 500);
    });
});

$('a[aller]').attr('href', '#');
var selectAll = true;
$('a[aller]').click(function () {
    $('input[type=checkbox][aller]').each(function () {
        if (!$(this).is(':disabled')) {
            $(this).prop('checked', selectAll);
        }
    });
    selectAll = !selectAll;
    return false;
});

$(function () {
    $('.showOnLoad').show();
});

$(function () {
    var i = 0;
    function pulsate() {
        $(".urgentIndicator").
        animate({
            opacity: 0.2
        }, 200, 'linear').
        animate({
            opacity: 1
        }, 200, 'linear', pulsate);
    }
    pulsate();
});

$(function () {
    $('[remote-searcher]').each(function () {

        var me = this;

        $(me).hide();

        var selections = [];

        var isMulti = typeof $(me).attr('multiple') == 'string';

        $(me).find('[rid]').each(function () {
            selections.push({
                id: $(this).attr('rid'),
                display: $(this).attr('display')
            });
        });

        if (!isMulti && selections[0]) {
            selections = [selections[0]];
        }

        $(me).html('');

        var url = $(me).attr('remote-searcher');
        var charMin = $(me).attr('char-min');
        var name = $(me).attr('name');

        $(me).append('<select multiple style="display:none;" name="' + name + '"></select><span choices></span><input type="text" style="border:none;margin:5px;width:100%;outline:none;display:none;"/></span>');
        $(me).append('<div style="margin-top:2px;background:white;border:1px lightgray solid;display:none;width:99%;position:absolute;z-index:999"></div>');

        var choices = $(me).find('span[choices]');

        var selectField = $(me).find('select');
        var textField = $(me).find('input[type=text]');
        var resultDiv = $(me).find('div');

        var setResultMask = function () {
            $(resultDiv).html('<div style="background-image: url(/icons/vanillaspin.gif); background-repeat: no-repeat; width:100%; height:60px;background-position: center;"></div>');
        }

        var fillSelected = function (selected) {
            $(selectField).html('');
            $(choices).html('');
            selected.forEach(function (choice, index) {
                if (isMulti || (!isMulti && index == 0)) {
                    $(selectField).append('<option selected value="' + choice.id + '">' + choice.display + '</option>');
                    $(choices).append('<button style="margin:2px;" rid="' + choice.id + '" index="' + index + '">' + choice.display + ' x</button>');
                }
            });
            $(choices).find('button').on('click', function () {
                var btn = this;
                var rid = $(btn).attr('rid');
                var index = $(btn).attr('index');
                selections.splice(index, 1);
                fillSelected(selected);
                return false;
            });
        }

        fillSelected(selections);

        var setValue = function (val, display) {
            if (!isMulti) {
                selections = [];
            }
            // get rid of earliers
            for (var i = 0; i < selections.length; i++) {
                var sel = selections[i];
                if (sel.id == parseInt(val)) {
                    selections.splice(i, 1);
                }
            }
            selections.push({
                id: val,
                display: display
            });
            fillSelected(selections);
            $(textField).val('');
            $(textField).hide();
        }

        var getMatches = function () {
            var substring = $(textField).val();
            if (charMin > substring.length) {
                return;
            }
            setResultMask();
            $(resultDiv).show();
            //url, data, pre, post, onSuccess, onFailure, suppressErrorMessage, onHttpFailure, shouldHideMask
            doAjax(url, {
                substring: substring
            }, null, null, function (matches) {
                $(resultDiv).find('[rid]').each(function () {
                    $(this).off()
                });
                $(resultDiv).html('');
                matches.forEach(function (match) {
                    if (typeof match == 'string') {
                        match = {
                            id: match,
                            display: match
                        }
                    }
                    if (typeof match == 'object' && !match.id) {
                        match.id = match.display;
                    }
                    $(resultDiv).append('<a href="#" class="searcher-result" display="' + match.display + '" rid="' + match.id + '">' + match.display + '</a>');
                });
                $(resultDiv).find('[rid]').each(function () {
                    var result = this;
                    $(result).mousedown('click', function () {
                        var val = $(result).attr('rid');
                        var display = $(result).attr('display');
                        setValue(val, display);
                        //$(textField).hide();
                        return false;
                    });
                });
            }, null, true, null, true);
        };

        $(textField).on('keyup', function () {
            getMatches();
        });

        $(textField).on('blur', function () {
            $(textField).val('');
            $(textField).hide();
            if ($(resultDiv).is(':visible')) {
                $(resultDiv).hide();
            };
        });

        $(textField).on('focus', function () {
            getMatches();
        });

        $(me).on('click', function () {
            $(textField).show();
            $(textField).focus();
        });

        $(me).show();
    });
});

$(document).ready(function () {
    // setInterval(function () {
    //     doAjax('/api/session/test', null, null, null, null, function () {
    //         window.location.reload(true);
    //     }, true, null, true);
    // }, 10000);
});

$(document).ready(function () {
    if (focusOn) {
        $('#' + focusOn).focus();
    }
});

$(function () {
    $('[setMaskOnClick]').click(function () {
        showMask();
    });
});

$(function () {
    $('input[type=file][ajaxload]').each(function () {
        var me = this;
        var name = $(me).attr('ajaxload');
        $(me).wrap('<span class="ajaxload"></span>');
        $(me).closest('span').append('<input type="hidden" name="' + name + '"/>');
        $(me).on('change', function (event) {
            console.log("file received.");
            var fileField = me;
            var files = event.target.files;
            var data = new FormData();
            $.each(files, function (key, value) {
                data.append(key, value);
            });
            $.ajax({
                url: '/api/systemFile/upload',
                type: 'POST',
                data: data,
                cache: false,
                dataType: 'json',
                processData: false, // Don't process the files
                contentType: false, // Set content type to false as jQuery will tell the server its a query string request
                success: function (data, textStatus, jqXHR) {
                    var systemFileID = data.data;
                    console.log("UPLOAD WORKED::", data);
                    $(me).closest('span').find('input[type=hidden]').val(systemFileID);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log('ERRORS: ' + textStatus);
                }
            });
        });
    });
});

// catch ESC and discard any visible moes
$(document).ready(function () {
    $(document)
        .off('keydown.moe-escape')
        .on('keydown.moe-escape', function (e) {
            if(e.which === 27) {
                let visibleMoes = $('[moe] [url]:not([show]):visible');
                if (visibleMoes.length) {
                    hideMoeFormMask();
                    visibleMoes.hide();
                    return false;
                }
            }
        });
});
