// Need to create common popup window for warning/confirm/error
// examples:
// 1. logout countdown windowm
// 2. validation failed message window
// 3. form successfully submitted message window
// 4. form submit with blank answers confirmation window

var redirectTo = '/PatientAccess/TransferLogout.aspx'; // URL to relocate the user to once they have timed out
var keepAliveURL = '/PatientAccess/keepAlive.aspx'; // URL to call to keep the session alive
var countdownId = 'secondsToBoom';

var running = false; // var to check if the countdown is running
var timer; // reference to the setInterval timer so it can be stopped

$(document).ready(function () {

    // create the warning window and set autoOpen to false
    var dialogWindow = $("#sessionTimeoutWarning");

    var idleTime = $('#expiryTime', dialogWindow).val(); //28640695
    var countdownTime = $('#countdownInSecond', dialogWindow).val(); //28640695
    var header = $('#alertHeader', dialogWindow).html();
    var message = $('#alertMessage', dialogWindow).html();
    var cancelText = $('#cancelLinkText', dialogWindow).html();
    var cancelTool = $('#cancelLinkToolTip', dialogWindow).html();
    var confirmText = $('#logoutLinkText', dialogWindow).html();
    var confirmTool = $('#logoutLinkToolTip', dialogWindow).html();

    createCountdownWindow(dialogWindow, header, message, cancelText, cancelTool, confirmText, confirmTool, idleTime, countdownTime);
});

$(window).on('resize', function () {        // AX-24898.24919.2
    var dialogWindow = $("#sessionTimeoutWarning");
    $(dialogWindow).dialog("option", "position", { my: "center", at: "top+20%", of: window }); // AX-24898.24919.4 ['middle', 50]);
});

function createCountdownWindow(dialogWindow, header, message, cancelText, cancelTool, confirmText, confirmTool, idleTime, countdownTime) {
    $(dialogWindow).html(message);
   $(dialogWindow).dialog({
        classes: { "ui-dialog": "dialogSessionTimeout" },
        title: header,
        autoOpen: false, // set this to false so we can manually open it
        closeOnEscape: false,
        draggable: false,
        resizable: false,
        width: 460,
        minHeight: 50,
        modal: true, // defines current window to be modal (disables all previous layers)
       position: { my: "center", at: "top+18%", of: window }, // AX-24898.24919.4 ['middle', 50],
       beforeClose: function () { // bind to beforeclose so if the user clicks on the "X" or escape to close the dialog, it will work too // AX-25090 - Needs to be upercase 'C' beforeClose
            clearInterval(timer); // stop the timer
            running = false; // stop countdown
            $.ajax({
                url: keepAliveURL,
                async: false
            }); // ajax call to keep the server-side session alive
        },
        buttons:
        [
            {
                text: cancelText,
                "class": "normalBtn",
                click: function () {
                    $(this).dialog("close");
                },
                title: cancelTool
            },
            {
                text: confirmText,
                "class": "mainBtn",
                click: function () {
                    $(dialogWindow).dialog('disable');
                    window.location = redirectTo;
                },
                title: confirmTool
            }
        ],
        open: function () {

            // IE fix for scroll bar issue
            // ---
            // May 17, 2013 - could not produce issue with the scroll bar on IE 9 + compatibility mode
            // We found an issue with dropdown list appearing in offset position after opening/closing a modal window.
            // ---
            // This can be reproduced with:
            // 1. Partially scroll a page in FireFox 20.0
            // 2. Trigger open a modal window
            // 3. Close the modal window
            // 4. Select a dropdown list (IMPORTANT: do not scroll after closing the modal window )
            // OBSERVE: the list selction panel is displayed in incorrect location
            // ---
            // $('body').css('overflow', 'hidden');

            $('.ui-widget-overlay').css('width', '100%');
            $('.ui-widget-overlay').css('height', '100%');      // AX-24898.24919.4
            $('.ui-widget-overlay').css('z-index', '1010');     // AX-24898.24919.4
            $(".dialogSessionTimeout").css('z-index', '1020');  // AX-24898.24919.4
            $('.ui-dialog-titlebar-close').hide();              // AX-24898.24919.4
        },
        close: function () {

            // Pairing operation for IE scroll bar issue
            // ---
            // May 17, 2013 - Error found in FireFox 20.0 with dropdown list
            // modal window will no longer trigger a scroll lock
            // ---
            // $('body').css('overflow', 'auto');
        }
    }); // end of dialog

    $.ajax({
        type: "POST",
        url: "/PatientAccess/Services/AutoLogout.asmx/RefreshFormsAuthentication",
        data: "{}",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (msg) {
            if (msg.d) {
                $.idleTimer(parseInt(idleTime)); // start the idle timer
            }
        }
    });

    // bind to idleTimer's idle.idleTimer event
    $(document).on("idle.idleTimer", function () {      // AX-24898.24919.2
        // if the user is idle and a countdown isn't already running
        var isIdle = $(document).idleTimer("isIdle");       // AXX-25090
        if (isIdle && !running) {   // AX-25090 if ($.data(document, 'idleTimer') === 'idle' && !running) {        
            var counter = countdownTime;
            running = true;

            // intialisze timer
            $('#' + countdownId).html(countdownTime);

            // open dialog
            $(dialogWindow).dialog('open');

            // create a timer that runs every second
            timer = setInterval(function () {
                counter -= 1;

                // if the counter is 0, redirect the user
                if (counter <= 0) {
                    $(dialogWindow).dialog('disable');
                    window.location = redirectTo;
                } else {
                    $('#' + countdownId).html(counter);
                };
            }, 1000);
        };
    });
}