﻿var visiblePopup = null;

function showPopup(what) {
    if (what === null) {
        hidePopup();
        return;
    }

    what = $(what);
    if (visiblePopup !== null) {
        if (visiblePopup === what) {
            return;
        }
        visiblePopup.fadeOut('fast');
    } else {
        $('#backgroundPopup').css({
            "opacity": "0.7"
        }).fadeIn('fast');
    }
    visiblePopup = what;
    visiblePopup.fadeIn();

    visiblePopup.find('.popup-body').attr('tabindex', -1);

    window.setTimeout(function() {
        var focusThis = $(visiblePopup).find('.focus-this:visible:first');
        if (focusThis.length === 0) {
            focusThis = $(visiblePopup).find(':input:text:visible:first');
        }
        if (focusThis.length === 0) {
            focusThis = $(visiblePopup).find('button:enabled:visible:first');
        }
        if (focusThis.length === 0) {
            focusThis = $(visiblePopup).find('*[tabindex][tabindex!=-1]:first');
        }
        if (focusThis.length === 0) {
            focusThis = $(visiblePopup);
        }
        $(focusThis).focus();
    }, 10);
}

function getVisiblePopup() {
    if (visiblePopup === null || visiblePopup.length === 0) {
        return null;
    } else {
        return visiblePopup;
    }
}

function hidePopup() {
    if (visiblePopup !== null) {
        visiblePopup.fadeOut('fast');
        $('#backgroundPopup').fadeOut('fast');
        visiblePopup = null;
    }
}

$(document).ready(function() {  
    $('body').keydown(function(e) {
        if (visiblePopup !== null) {
            switch (e.which) {
                case 27: 
                    { // escape
                        var closeButton = $(visiblePopup).find('.popup-cancel, .popup-close');
                        if (closeButton.length !== 0) {
                            $(closeButton[0]).click();

                            e.stopPropagation();
                            e.preventDefault();
                        }
                        break;
                    }
                case 13: 
                    { // return
                        var acceptButton = $(visiblePopup).find('.popup-accept');
                        if (acceptButton.length !== 0) {
                            $(acceptButton[0]).click();

                            e.stopPropagation();
                            e.preventDefault();
                        }
                        break;
                    }
            }
        }
    });
});
