﻿var popup = document.getElementById("popupId");

function getPopupHeight() {

    return popup.offsetHeight;
}

function getPopupWidth() {

    return popup.offsetWidth;
}

function openPopup(id) {
    document.getElementById("popupId").className = "openedPopup";
    document.getElementById("windowId").className = "openedWindow";
    $get('modalWindow').src = "/" + id + ".aspx?target=_top";
    var height = Math.max(
        Math.min(document.body.offsetHeight, document.documentElement.offsetHeight),
        Math.min(document.body.clientHeight, document.documentElement.clientHeight)
    );

    $get('modalWindow').style.height = Math.min($get('modalWindow').offsetHeight, height - 60) + "px"

    wrapperId = document.getElementById('wrapper');
    
    heightWindow = Math.ceil(wrapperId.offsetHeight) + 'px';
    document.getElementById("windowId").style.height = heightWindow;

    widthWindow = Math.ceil(wrapperId.offsetWidth) + 'px';
    document.getElementById("windowId").style.width = widthWindow;
    
    popup.style.top = (document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop) + (height - getPopupHeight()) / 2 + "px";
    popup.style.left = (document.body.clientWidth - getPopupWidth()) / 2 + "px";
}

function alignPopup() {
    var scrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
    var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft : document.documentElement.scrollLeft;

    var height = Math.max(
        Math.min(document.body.offsetHeight, document.documentElement.offsetHeight),
        Math.min(document.body.clientHeight, document.documentElement.clientHeight)
    );

    popup.style.top = (scrollTop + height / 2 - getPopupHeight() / 2) + 'px';
    popup.style.left = (scrollLeft + document.body.clientWidth / 2 - getPopupWidth() / 2) + 'px';
}

function closePopup() {
    if (document.getElementById("popupId")) {
        document.getElementById("popupId").className = "closedPopup";
    }
    if (document.getElementById("windowId")) {
        document.getElementById("windowId").className = "closedWindow";
    }
}

if(popup!=null)
{
    $addHandler(window, 'scroll', function(e) {
        alignPopup();
    });
    $addHandler(document, 'keydown', function(e) {
        if (e.keyCode == 27) {
            closePopup();
        }
    });
} // if
