var popupStatus = false;
function getViewport() {
    return [$(window).width(), $(window).height(), $(document).scrollLeft(), $(document).scrollTop() ];
}

function linkForms(){
    var options={
        success: function(returnValue) {
            $('#popuphtml').html(returnValue);
            linkForms();
        },
        error: function(returnValue) {
            alert(returnValue);
        }
    }
    //$('#popuphtml form').ajaxForm(options);
    $('#popuphtml form').bind('submit', function() {
        $('#final').removeClass("highlight");
        $('#form_submit').attr('disabled', 'disabled');
        $(this).ajaxSubmit(options);
        return false; // <-- important!
    });
}

function openPopup() {
    if(popupStatus) return;
    var w = getViewport();
    var ow	= $("#popup_content").outerWidth();
    var oh	= $("#popup_content").outerHeight();

    $('#popup_background').css({
        "z-index": "1000"
    });
    $('#popup_content').css({
        "position": "absolute",
        "top": (oh > w[1] ? w[3] : w[3] + Math.round((w[1] - oh) * 0.5)),
        "left": (ow > w[0] ? w[2] : w[2] + Math.round((w[0] - ow) * 0.5)),
        "z-index": "1001"
    });
    $('#popup_content').animate({
        'opacity': 'show'
    }, 400);
    $('#popup_background').animate({
        'opacity': 'show'
    }, 400);
    popupStatus = true;
}

function closePopup() {

    if(!popupStatus) return;

    $('#popup_content').animate({
        'opacity': 'hide'
    }, 400);
    $('#popup_background').animate({
        'opacity': 'hide'
    }, 400);

    popupStatus = false;
    $('#popuphtml').html("");
}

$(document).ready(function() {

    $('#popup_content').hide();
    $('#popup_background').hide();
    $('#popup_content').css('visibility', 'visible');
    $('#popup_background').css('visibility', 'visible');

    $('#close_popup').click(function() {
        closePopup();
    });

    //    $('#popup_background').click(function() {
    //       closePopup();
    //   });

    $(document).keypress(function(e) {
        if(e.keyCode == 27) {
            closePopup();
        }
    });
    $('.pauls_popup').live("click", function() {       
        var urltext = $(this).attr('href');
        $.ajax({
            type: 'GET',
            url: urltext,
            success: function(returnValue) {
                $('#popuphtml').html(returnValue);
                linkForms();
            },
            error: function(returnValue) {
                alert(returnValue);
            }
        });
        openPopup();
        return false;
    });

});
