$(document).ready(function() {
    // Hide all the image thumbnails and fade them in once loaded
    // also bind the mouseover event handlers while we're at it!
    $('.image-grid-img').hide();
    // Images that are returned from the browser cache before the $(document).ready event do not get displayed
    // this trick comes from JQuery.com
    $('.image-grid-img').one('load', function() {
        $(this).fadeTo(500, 0.7);
    }).each(function() {
        if(this.complete)
            $(this).trigger("load");
    });
    $('.image-grid-img').bind({
        mouseenter : function() {
            $(this).fadeTo(300, 1);
        },
        mouseleave : function() {
            $(this).fadeTo(300, 0.7);
        }
    });

    // Bind a click handler to the div containing our grid
    $('#image-grid-1').bind('click', function(event) {
        // Stop the HREF from firing
        event.preventDefault();
        // Change the info text while we load the selected image
        $('#info').text('loading, please wait...');
        var eventTarget = $(event.target);
        var animTarget = $('#image-grid-1');
        if($('#lightbox').length == 0) {
            var lightbox = $('<div id="lightbox"></div>');
            lightbox.css({
                width : eventTarget.css('width'),
                height : eventTarget.css('height'),
                top : eventTarget.offset().top,
                left : eventTarget.offset().left,
                opacity : 0.7
            });
            animTarget.append(lightbox);
            lightbox.append('<img id="lightbox-loading" src="css/loader.gif" />');
            lightboxImg = $('<img id="lightbox-image" />');
            lightboxImg.hide();
            lightboxImg.bind("load", function() {
                // Wait for the image to load before animating
                lightbox.animate({
                    width : animTarget.width(),
                    height : animTarget.height(),
                    top : animTarget.offset().top,
                    left : animTarget.offset().left,
                    opacity : 1
                }, 600, function() {
                    $('#lightbox-loading').remove();
                    $('#lightbox').append(lightboxImg);
                    lightboxImg.fadeIn();
                    $(document).bind('click', function(event) {
                        $(document).unbind();
                        if($('#lightbox').length > 0) {
                            lightbox.fadeOut(600, function() {
                                $('#lightbox').remove();
                                $('#info').text('click on an image to zoom in');
                            });
                        }
                    });
                    $('#info').text('click again to zoom out');
                });
            });
            lightboxImg.attr('src', eventTarget.parent().attr('href'));
        }
    })
});

