jQuery(function($) {
    // main gallery function, shows larger image when thumbnail is clicked
    var preload;
    $('ul.items a').click(function() {
        // fixes bizarre IE bug where the picture never reappears
        // when clicking on the active thumbnail
        if ($(this).parent().hasClass('active'))
            return false;

        var activeImage = $(this).attr('href');
        var activeTitle = $(this).attr('title');
        $('.activeImage img').fadeOut(100, function() {
            $('.activeImage').addClass('imgLoading'); // show loading .gif while we wait
            preload = new Image(); // for cacheing
            preload.onload = function() {
                $('.activeImage').removeClass('imgLoading');
                
                var pic = $('.activeImage img');
                pic.attr({
                    src: preload.src,
                    alt: preload.alt
                }).fadeIn(400);

                // set proper width and height
                var maxWidth = 375;
                var maxHeight = 240;
                var ratio = 0;
                var width = pic.width();
                var height = pic.height();
                if (width > maxWidth) {
                    ratio = maxWidth / width;
                    pic.css("width", maxWidth);
                    pic.css("height", height * ratio);
                    height = height * ratio;
                    width = width * ratio;
                }
                if (height > maxHeight) {
                    ratio = maxHeight / height;
                    pic.css("height", maxHeight);
                    pic.css("width", width * ratio);
                    width = width * ratio;
                }
            }
            // setting src must come AFTER onload definition
            // onload is called immediately upon setting src if image is cached
            preload.alt = activeTitle;
            preload.src = activeImage;
        });

        $(this).parent().click(); // activate li behind link for scrolling

        return false;
    });
    // initialize with first link
    $('ul.items li:first a').click();

    // set up scrolling filmstrip, relies on jQuery Tools
    $('ul.items').wrap('<div class="scrollable"></div>');
    $('div.scrollable').scrollable();
});
