/*
  The Special Popup Functions
*/

// Create a new XMLHttpRequest, handling the various kinds.
function createRequest() {
    try {
        request = new XMLHttpRequest();
    } catch (trymicrosoft) {
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (othermicrosoft) {
            try {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (failed) {
                request = false;
            }
        }
    }

    if (!request)
        alert("Error initializing XMLHttpRequest!");
};

// popupLink() makes a HEAD request for the given url, checking on if the requested
// resource is a binary object.  If it is, open it up in a new window.  Otherwise,
// update the popup with the content of the request.
function popupLink(url) {
    showLoadingImageInPopup();
    positionAndShowPopup();
    createRequest();
    request.open("HEAD", url, true);
    request.onreadystatechange = function () {
        if (request.readyState == 4) {
            if (request.getResponseHeader("Content-Transfer-Encoding") == 'binary') {
                $('popup').hide();
                window.open(url);
            } else {
                updatePopupWith(url);
            }
        }
    };
    request.send(null);
};

function positionAndShowPopup() {
    var top_offset  = Math.abs(($('popup').viewportOffset()[1] * -1) + ($('popup').positionedOffset()[1]) + 50);
    var left_offset = Math.abs((document.viewport.getWidth() - $('popup').getWidth()) / 2);

    $('popup').setStyle({
            position: 'absolute',
                top: top_offset + 'px',
                left: left_offset + 'px'
                });

    $('popup').show();
    $('popup').scrollTo();
};

// Request the url and put its contents into the popup and show it.
function updatePopupWith(url) {
    new Ajax.Request(url, {
            method: 'get',
                onComplete: function(transport) {
                $('popup_content').update(transport.responseText);
                positionAndShowPopup();
            }
    });
};

// Put the spinner in the popup
function showLoadingImageInPopup() {
  $('popup_content').update('<p style="text-align:center"><img src="/ajax-loader.gif" alt="Loading..." /></p>');
};

