$(function() {
    var logout = $('#logoutAlert');
    if (!logout.length)
        alert('Auto logout script is misconfigured.');

    var initialTimerCount = $('#initialTimerCount', logout).html();
    var finalTimerCount = $('#finalTimerCount', logout).html();

    var secondsToBoom = $("#secondsToBoom", logout);

    secondsToBoom.html(finalTimerCount);

    logout.jqm({ modal: true });

    setInitialLogoutTimer(logout);

    $('form').on("click", 'a.logoutCancel', function (e) {       // AX-24898.24919.2 use on() instead of live()
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "/PatientAccess/Services/AutoLogout.asmx/RefreshSessionAuthentication",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                logout.stopTime();
                secondsToBoom.stopTime();

                if (msg.d == true) {
                    logout.jqmHide();
                    secondsToBoom.html(finalTimerCount);
                    setInitialLogoutTimer(logout);
                }
                else {
                    $('h3', logout).html('Already logged out.');
                    $('div.jqmAlertContent', logout).html('Unfortunately, the system has already logged you out. Under normal circumstances, this should not occur. Please refresh the page in order to login again.');
                    $('div.jqmAlert .logoutCancel').hide();
                }

                return false;
            },
            error: function(xhr, msg) {
                alert('Error refreshing authentication timeout. Please refresh the page.');
            }
        });
    });

    function setInitialLogoutTimer(logout) {
        logout.oneTime(initialTimerCount + 's', function(i) {
            logout.jqmShow();
            setAlertCountdown(logout);
        });
    }

    function setAlertCountdown(logout) {
        logout.oneTime(finalTimerCount + 's', function(i) {
            secondsToBoom.stopTime();
            top.location = '/PatientAccess/PAAdmin/Logout.aspx';
        });

        // Increment the message of seconds until logout
        secondsToBoom.everyTime('1s', function(i) {
            const currentCount = finalTimerCount - i;
            $(this).html(`${currentCount}`);
        });
    }

    // Close Button Highlighting. IE doesn't support :hover.
    /* AX-24898.24919.2 don't use jquery.browser if ($.browser.msie) {
        $('div.jqmAlert .logoutCancel').hover(
                function() { $(this).addClass('jqmCloseHover'); },
                function() { $(this).removeClass('jqmCloseHover'); });
    } */
});