/**
 * General javascript for all pages.
 *
 * Defines the popup link class "popup-link", which works when added to
 * an anchor tag that links to an image.  The anchor tag should have an id
 * that ends in "-link". The id of the popup be the same as that id without
 * the -link suffix.
 *
 * Also places focus on the first form field on page load.
 *
 * Requires jQuery
 * @author Zachary Chavez <zpchavez@gmail.com>
 */

$(document).ready(function() {
    $('.popup-link').live('click', function() {
        popupLinkId = $(this).attr('id');        
        popupId = popupLinkId.substring(0, popupLinkId.lastIndexOf('-')); // e.g. remove "-link" from id "etc-link""
        // Close other popups first
        $('.popup').each(function() {
            if ($(this).attr('id') != popupId && $(this).css('display') == 'block') {
                $(this).click();
            }
        });
        // Generate popup if it doesn't exist
        if ($('#' + popupId).length == 0) {            
            imageSrc = $('#' + popupLinkId).attr('href');            
            $('#popup-container').prepend('<div class="popup" id="'+popupId+'">\n\
                               <h3>Click to Close</h3>\n\
                               <img width="500" src="'+imageSrc+'"/>\n\
                               </div>');
            $('#' + popupId).live('click', function() {                
               $(this).toggle();
            });            
        } else { // Else just trigger its click event
            $('#' + popupId).click();
        }
        return false;
    });

    // Put focus on first non-hidden, non-submit element.
    $fields = $('input[type!="hidden"][type!="submit"]');
    if ($fields.size() > 0) {
        $fields[0].focus();
    }
});