<script>
    // <input type="hidden" name="~(JSFieldParam;[pref]idmx_tdyStatus)" />
    // <input type="hidden" name="~(JSFieldParam;[pref]idmx_tdyExp)" />
    var idmxTdyPlus = false
    var idmxTdyAuthMode = false
    var idmxTdyAuth = idmxTdyAuth || (() => {
        const idmAuthUrl = "https://autotardy-auth.azurewebsites.net/at/auth"
        const idmAuthObj = {
            "Customer": window.location.hostname,
            "SchoolId": "~(curschoolid)"
        }

        const opts = {
            api_domain: "ez.mba-link.com",
            plugin_name: "idM AutoTardy",
            pref_count_path: "/admin/idm_AutoTardy/checkAuthPrefs.json",
            status_name: "idmx_tdyStatus",
            exp_name: "idmx_tdyExp",
            status: JSON.parse(`~[displaypref:idmx_tdyStatus]` || null),
            exp: Number("~[displaypref:idmx_tdyExp]"),
            status_field: "~(JSFieldParam;[pref]idmx_tdyStatus)",
            exp_field: "~(JSFieldParam;[pref]idmx_tdyExp)"
        }

        const CACHE_EXP = 30 * 60000; // 30 minutes
        const GRACE_PERIOD = 14 * 24 * 60 * 60000; // 14 days
        const TIMEOUT = 3000;

        async function checkEZApi() {
            return $j.ajax(`https://${opts.api_domain}/api/plugin/authCheck`, {
                timeout: TIMEOUT,
                data: { pluginName: opts.plugin_name },
                headers: { "X-Mba-DN": "~[displaypref:districtnumber]" }
            });
        }

        async function updatePrefs(data) {
            if(typeof window[opts.status_name] !== 'undefined') return;
            window[opts.status_name] = true;
            await $j.post('/admin/changesrecorded.white.html', {
                "ac": "prim",
                [opts.status_field]: JSON.stringify(data),
                [opts.exp_field]: new Date().getTime() + CACHE_EXP
            });
            cleanPrefs();
        }

        async function cleanPrefs() {
            const prefNames = {status: opts.status_name, exp: opts.exp_name};
            const prefIds = await $j.getJSON(opts.pref_count_path, prefNames);
            prefIds.pop();
            prefIds.forEach(deletePref);
        }

        function deletePref(recordDcid) {
            $j('body').append($j('<div>').attr('id','idmxTdyFormTarget').css('display','none'));
            $j('#idmxTdyFormTarget').load(`/admin/idm_AutoTardy/deletePref.html?frn=009${recordDcid}`,function(data){
                $j.post('/admin/changesrecorded.white.html', $j('#idmxTdyFormTarget form').serialize());
            });
        }

        const isAuthed = d => d && d.authorized && ('~(curschoolid)' == '0' || d['~(curschoolid)']);

        return async function () {
            return $j.ajax({
                url: idmAuthUrl,
                method: "POST",
                data: JSON.stringify(idmAuthObj),
                headers: {
                    "Accept": "*/*",
                    "Content-Type": "application/json"
                }
            }).then(function(response) {
                if (response) {
                    if (response.authCode == "1") {
                        idmxTdyAuthMode = "idM"
                        return true
                    } else {
                        if (response.authCode == "2") {
                            idmxTdyAuthMode = "idM"
                            return false
                        } else {
                            idmxTdyAuthMode = "MBA"
                            return async function () {
                                if (opts.exp && new Date().getTime() < opts.exp && "~(gpv.ez;encodejsstring)" != 'true') {
                                    return isAuthed(opts.status);
                                }
    
                                if('~[directory]' != 'admin'){
                                    return opts.status ? isAuthed(opts.status) : false;
                                }
    
                                try {
                                    const apiResp = await checkEZApi();
                                    updatePrefs(apiResp);
                                    return isAuthed(apiResp);
                                } catch (e) {
                                    if (e.status != 401 && opts.exp && new Date() < new Date(opts.exp + GRACE_PERIOD)) {
                                        return isAuthed(opts.status);
                                    }
                                    return false;
                                }
                            }()
                        }
                    }
                }
            })
        }
    })();
</script>
<!-- <input type="hidden" name="ac" value="prim" />-->
~[wc:idM_autoTardyPlus_auth]