function displayPopup(event)
{
    $.ajax({
        url: $(this).attr('href'),
        beforeSend: function(xhr) {xhr.setRequestHeader('X-Popup', 'true'); },
        success: function(html) {
            $.modal($(html), {containerId: 'popup', close: false,
                onOpen: function () {
				    this.dialog.overlay.show();
                }
            });
	    if ($('div.popup-content input').length == 0) {
                $('div#modalOverlay').click($.modal.close);
                $('div#popup').click($.modal.close);
            } else {
                $('div.popup-content a.cancel').click(
                    function () {
                        $.modal.close();
                        return false;
                    }
                );
                $('div.popup-content input[name=cancel]').click(
                    function () {
                        $.modal.close();
                        return false;
                    }
                );
            }
            $('html').unbind('keypress').keypress(
                function (e) {
                    if (e.which == 27) { // escape
                        $.modal.close();
                        return false;
                   }
                }
            );

            var popup = $('div#popup');
            var overlay_height = $('#modalOverlay').height();
            // display the popup out of the screen, necessary to get its layout
            $('#modalOverlay').css('opacity', '1');
            popup.css('top', '-1000px').css('left', '-1000px').show();
            $('div.popup-content').show(); // insure content is shown
            var popup_height = $('div.popup-content').height();
            var popup_width = $('div.popup-content').width();
            popup.hide();
            if (popup_height < overlay_height) {
                popup.css('margin-top', - popup_height/2);
            } else {
	    	/* overflowing browser height -> redirecting to page */
		document.location.href = event.target.href;
	    	return;
	    }
            popup.css('margin-left', - popup_width/2);
            popup.css('top', '50%').css('left', '50%')
            popup.fadeIn('fast').focus();
	    $('div.popup-content input:visible')[0].focus();
        }
    });

    return false;
}

$(function() {
	$('a[rel=popup]').click(displayPopup);
});

