/*-----------------------------------------------------------------------------------------------
 * Unobtrusive popup links
 * 
 *      Usage:  Add this script to the head of your HTML file.  Then, add a 
 *              rel="popup" to any anchor you want to open in a new window. 
 *
 *   Requires:  prototype.js version 1.6+
 * Created by:  Mark Adams
 *-----------------------------------------------------------------------------------------------*/

var Popup = Class.create({
    /*
     * Function: initialize()
     *
     * Initializes our class.  This binds an Ajax responder to catch
     * AJAX introduced popups.  This also calls the necessary functions
     * to start the popups running.
     */
    initialize: function() {
        // When an ajax call is complete, re-register the popups (in case one was loaded by ajax)
        var ajaxPopupHandler = {
            onComplete: function(response){
                this.activatePopups();
            }.bind(this)
        };
        Ajax.Responders.register(ajaxPopupHandler);

        // Run the popups
        this.activatePopups();
    },

    /*
     * Function: activatePopups()
     *
     * This function adds the event listeners to the links we've identified
     * as being popups.
     */
    activatePopups: function() {
        popups = $$('a:([rel~=popup])');
        for (var i=0, il=popups.length; i<il; i++) {
            popups[i].observe('click', this.respondToClick);
        }
    },

    /*
     * Function: respondToClick(event)
     *
     * This is the function that is bound to our popup links.  This does
     * the actual popup functionality.
     *
     * Input: event - the javascript event
     */
    respondToClick: function(event) {
        var el = event.element();
        if (el.tagName == 'IMG') {
            if (el.parentNode.tagName == 'A') {
                el = el.parentNode;
            } else {
                return false;
            }
        }
        window.open(el.href);
        Event.stop(event);
        return false;
    }

});

// Initialization
function initPopup(){
    var myPopup = new Popup();
}
Event.observe(window, 'load', initPopup, false);