﻿var popupStatus = 0;
var shadowDeep = 11;

function setElementRect(element, left, top, width, height) {
    element.css({
        "left": left,
        "top" : top,
        "width" : width,
        "height" : height
    })
}

function getActivePopupElement(popupContainer, element) {
    return $("#" + popupContainer + " #" + element);
}

function showPopup(popup, popupBody, popupBackground, popupShadow) {
    placeOnTop(popup, popupBody, popupBackground, popupShadow);
    centerPopup(popup, popupBody, popupBackground, popupShadow);
    loadPopup(popup, popupBody, popupBackground, popupShadow);
}

function placeOnTop(popup, popupBody, popupBackground, popupShadow) {
    var topMostZIndex = getMaxZIndex() + 1;
    getActivePopupElement(popup, popupBackground).get(0).style.zIndex = topMostZIndex;
    getActivePopupElement(popup, popupShadow).get(0).style.zIndex = topMostZIndex + 1;
    getActivePopupElement(popup, popupBody).get(0).style.zIndex = topMostZIndex + 2;
}

function centerPopup(popup, popupBody, popupBackground, popupShadow) {
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    
    var popupContact = getActivePopupElement(popup, popupBody);
    var shadowPopup = getActivePopupElement(popup, popupShadow);
    
    var left = windowWidth / 2 - popupContact.width() / 2;
    var top = windowHeight / 2 - popupContact.height() / 2;
    
    setElementRect(popupContact, left, top, popupContact.width(), popupContact.height());
    setElementRect(shadowPopup, left + shadowDeep, top + shadowDeep, popupContact.width(), popupContact.height());
    
    getActivePopupElement(popup, popupBackground).css({
        "height": windowHeight
    });
}

function loadPopup(popup, popupBody, popupBackground, popupShadow) {
    if (popupStatus == 0) {
        getActivePopupElement(popup, popupBackground).css({
            "opacity": "0"
        });
        getActivePopupElement(popup, popupShadow).css({
            "opacity": "0.37"
        });
        getActivePopupElement(popup, popupBackground).fadeIn("fast");
        getActivePopupElement(popup, popupBody).fadeIn("fast");
        getActivePopupElement(popup, popupShadow).fadeIn("fast");
        popupStatus = 1;
    }
}

function disablePopup(popup, popupBody, popupBackground, popupShadow) {
    if (popupStatus == 1) {
        getActivePopupElement(popup, popupBackground).fadeOut("fast");
        getActivePopupElement(popup, popupBody).fadeOut("fast");
        getActivePopupElement(popup, popupShadow).fadeOut("fast");
        popupStatus = 0;
    }
}

function getMaxZIndex() {
    var maxZ = Math.max.apply(null, $.map($('body *'), function (e, n) {
        if ($(e).css('position') == 'absolute')
            return parseInt($(e).css('z-index')) || 1;
    }));
    return maxZ;
}

