// JavaScript Document
// resize admin body height based on window height and document height
function resize(elmtId) {

    // get window height
    var windowHeight = window.innerHeight - 60;

    // set the element to the window height
    $("#" + elmtId).css('height', windowHeight);

    // get document height AFTER the reset
    var documentHeight = $(document).height() - 60;

    // after reseting to window height, if the document height is still greater,
    // reset to the document height
    if (documentHeight > windowHeight)
        $("#" + elmtId).css('height', documentHeight);

    // hide time window
    hideTimeWindow();
}

// show OR hide page content edit buttons in Pages->Detail
function togglePageContentButton(dropdownId, buttonId) {

    var dropdown = document.getElementById(dropdownId);
    var button = document.getElementById(buttonId);

    if (dropdown != null && button != null) {
        var selectedText = dropdown.options[dropdown.selectedIndex].text;

        button.style.visibility = (selectedText == "Content")
            ? "visible"
            : "hidden";
    }
}

// show OR hide time window
function toggleTimeWindow() {

    // update button status, and show/hide window
    if ($(".timeWindow").is(":hidden")) {

        displayBlankTime();
        loadTimeFromServer();

        $(".timeButton").find("#TimeArrow").html("&#9650;");
        $('.timeWindow').show();
    }
    else {
        hideTimeWindow();
    }
}

function hideTimeWindow() {

    clearAllTimers();

    $(".timeButton").find("#TimeArrow").html("&#9660;");
    $('.timeWindow').hide();
}

function loadTimeFromServer() {
    // capture time before submitting the request to server
    var preClientDate = new Date();

    $.ajax({
        type: "POST",
        url: "../Default.aspx/GetDate",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (time) {

            // clear all timer operation to start from fresh
            clearAllTimers();

            // reset seconds counter
            window.serverDate = null;
            window.clientDateTime = null;
            window.millisecondsFromStoredDate = 0;

            // capture time after the data has been recieved
            var postClientDate = new Date();

            // store captured client date into window.clientDateTime
            window.clientDateTime = postClientDate.getTime();

            // calculate difference between times to get
            // duration it took to process
            var processDelayInMilliseconds = Math.round((postClientDate.getTime() - preClientDate.getTime()) / 2);

            if (processDelayInMilliseconds > 500) {
                displayBlankTime();
            } else {

                var dates = time.d.split(".");
                if (dates.length == 7) {
                    var year = dates[0];
                    var month = dates[1];
                    var day = dates[2];
                    var hour = dates[3];
                    var minute = dates[4];
                    var second = dates[5];
                    var millisecond = dates[6];

                    // get server date
                    window.serverDate = new Date(year, month, day, hour, minute, second, millisecond);
                    window.serverDate.setMilliseconds(window.serverDate.getMilliseconds() + processDelayInMilliseconds);

                    // get clock
                    displayTime();

                    // set interval of 0.2 seconds to update clock display
                    setTimeTickInterval();
                }
            }
        }
    });
}

function timeTick(increament) {
    window.millisecondsFromStoredDate += increament;
    displayTime();

    if (window.millisecondsFromStoredDate == 10000) {
        loadTimeFromServer();
    }
}

function displayBlankTime() {
    // clear all timer operation to start from fresh
    clearAllTimers();

    // reset seconds counter
    window.serverDate = null;
    window.clientDateTime = null;
    window.millisecondsFromStoredDate = 0;

    $(".timeWindow").html("--:--:-- --");

    setServerCheckTimeout();
}

function displayTime() {

    var serverDate = new Date(window.serverDate);
    serverDate.setMilliseconds(serverDate.getMilliseconds() + window.millisecondsFromStoredDate);

    var clientDateTime = window.clientDateTime + window.millisecondsFromStoredDate;

    // For any reason javascript was paused (due to scrolling, minimized window, etc)
    // display time should detect if the client clock is out of sync, and hide the window
    // if the syncy is greater than 0.25 second
    var now = new Date().getTime();
    var min = now - 250;
    var max = now + 250;
    if (clientDateTime < min || clientDateTime > max) {

        displayBlankTime();
        //alert(min + " < " + clientDateTime + " < " + max);
    } else {
        var h = serverDate.getHours();
        var m = serverDate.getMinutes();
        var s = serverDate.getSeconds();
        var t = (h >= 12) ? "PM" : "AM";

        // add a zero in front of numbers<10
        h = (h % 12 == 0) ? 12 : h % 12;
        m = (m < 10) ? "0" + m : m;
        s = (s < 10) ? "0" + s : s;

        $(".timeWindow").html(h + ":" + m + ":" + s + " " + t);
    }
}

function clearAllTimers() {
    clearTimeTickInterval();
    clearServerCheckTimeout();
}

function setTimeTickInterval() {
    // set interval to display
    var interval = 200;
    window.updateTimeInterval = setInterval(function () { timeTick(interval); }, interval);
}

function clearTimeTickInterval() {
    if (typeof window.updateTimeInterval !== "undefined")
        clearInterval(window.updateTimeInterval);
}

function setServerCheckTimeout() {
    // if blank time is displayed, need to re-establish after 5 seconds
    window.serverDateCheckTimeout = setTimeout(function () {
        loadTimeFromServer();
    }, 5000);
}

function clearServerCheckTimeout() {
    if (typeof window.serverDateCheckTimeout !== "undefined")
        clearTimeout(window.serverDateCheckTimeout);
}

function scrollStart() {
    hideTimeWindow();
}

function scroll() {
    hideTimeWindow();
}

function MediumWindow(url, name, id, fileType, isNew) {
    var newWindow = window.open(url + "?id=" + id + "&fileType=" + fileType + "&isNew=" + isNew, name, "width=750, height=680, scrollbars=1,location=0,toolbar=0");
    return newWindow;
}

function SmallWindow(url, name) {
    var newWindow = window.open(url, name, "width=330, height=75, scrollbars=1,location=0,toolbar=0");
    return newWindow;
}

function gup(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

function ExportRedirect(id, type) {
    window.location = "/PatientAccess/PAAdmin/Handler/FileExportHandler.ashx?id=" + id + "&type=" + type;
}


function confirmResetAllPasswords() {
    var alertWindow = $('#resetAllAlert');
    alertWindow.jqm({ modal: true });
    alertWindow.jqmShow();
    $('a.resetCancel').on("click", function (e) {      // AX-24898.24919.2 use on() instead of live()
        e.preventDefault();
        alertWindow.jqmHide();
        $('a.resetYes').off("click");
        $('a.resetCancel').off("click");
    });
    

    $('form').on("click", 'a.resetYes', function (e) {        // AX-24898.24919.2 use on() instead of live()
        e.preventDefault();
        $('.hdnResetPasswordsBtn').trigger('click');	// AX-24898.24919.2 $('.hdnResetPasswordsBtn').click();
        alertWindow.jqmHide();
        $('a.resetYes').die("click");
        $('a.resetCancel').die("click");
    });
}

function confirmSwitchPA2() {
    var alertWindow = $('#switchPA2Alert');
    alertWindow.jqm({ modal: true });
    alertWindow.jqmShow();
    $('a.switchCancel').on("click", function (e) {
        e.preventDefault();
        alertWindow.jqmHide();
        $('a.switchYes').off("click");
        $('a.switchCancel').off("click");
    });

    $('a.switchYes').on("click", function (e) {
        e.preventDefault();
        $('.hdnSwitchPA2Btn').trigger('click');
        alertWindow.jqmHide();
        $('a.switchYes').off("click");
        $('a.switchCancel').off("click");
    });
}

function confirmResetEmailsTemplatesToDefault() {
    const alertWindow = $('#resetEmailsTemplatesToDefaultAlert');
    alertWindow.jqm({ modal: true });
    alertWindow.jqmShow();

    const resetYes = alertWindow.find('a.resetYes');
    const resetCancel = alertWindow.find('a.resetCancel');

    const cancelTriggers = () => {
        alertWindow.jqmHide();
        resetYes.off("click");
        resetCancel.off("click");
    }

    resetCancel.on("click", function (e) {
        e.preventDefault();
        cancelTriggers();
    });

    resetYes.on("click", function (e) {
        e.preventDefault();
        cancelTriggers();
        $('.hdnResetResetEmailTemplatesToDefaultBtn').trigger('click');
    });
}