﻿/*
OLD GALLERY

function startGalleryRotation(selector, delay) {
    var i = 0;
    var layers = $$(selector);
    delay = (delay == undefined) ? 6000 : delay;
    setInterval(function() {
        layers[i].fade('out');
        i = (i == layers.length - 1) ? 0 : i + 1;
        layers[i].fade('in');
    }, delay);
}
*/

//
// Scales an horizontally centers an image within it's parent container
// NOTE: this must be called AFTER the image had loaded or it's hight
//  and width with be inaccurate
//
function imgScaleToFit(img) {
    img = $(img);
    target = img.parent();

    // Get the dimentions
    var imgWidth = img.outerWidth(true); // outer gets border, margins, and padding
    var imgHeight = img.outerHeight(true);
    var targetWidth = target.width();
    var targetHeight = target.height();

    // Find out how the image is sized relative to the parent
    var imgWidthRatio = (imgWidth / targetHeight) / (targetWidth / targetHeight);
    var imgHeightRatio = (imgHeight / targetWidth) / (targetHeight / targetWidth);

    // Only scale down (if the image is to large), don't scale up (don't stretch)
    if (imgHeightRatio > 1 || imgWidthRatio > 1) {
        if (imgHeightRatio > imgWidthRatio)
            img.height(targetHeight);
        else
            img.width(targetWidth);
    }

    // Once the image has been sized, evaluate it's height to be vertically centered
    var imgTopOffset = (((targetHeight - img.height()) / 2));

    // Return the object when finished (for chaining)
    return img

    // Center the picture horizontally
    .parent().css({
        'display': 'inline-block',
        'text-align': 'center'
    })
    // Return the current selection to the image element
    .end()
    // Center the picture vertically
    .css({
        'display': 'inline-block',
        'position': 'relative',
        'top': imgTopOffset + 'px'
    });
}

function thumbnailImageGallery(selector) {

    // Constants
    mainWidth = 320;
    largeImageHeight = 225;
    largeImageWidth = 300;
    autoscrollDelay = 7500;

    // Get all thumbnail images
    var div = $(selector);
    window.images = $(selector + ' img');

    // Setup auto scroller variables (must be global)
    window.autoPos = 0;
    window.autoUserInterrupted = false;
    window.autoIntervalID;
    window.autoRestartDelay = 5000;

    // ----
    // Create the main image switch method if it doesn't exist already
    // ----
    if (!window.thumbnailImageGallerySelect) {
        window.thumbnailImageGallerySelect = function(newSrc, isUserInterrupt) {

            // Set the global user interrupt flag if the user changes the image
            if (isUserInterrupt)
                window.autoUserInterrupted = true;

            // Pause the auto scroller if the user clicks an image
            if (window.autoUserInterrupted)
                if (!isUserInterrupt) {
                    clearInterval(window.autoIntervalID);

                    /* This code can be implemented if the user wants to reset the auto scroller at some time
                    after the user has interrupted it. Setting window.autoUserInterrupted must be set to false
                    or non-user-interrupt commands will not trigger the image (so this can be set
                    in another command to trigger the user lock on the scroller)
                         
                    window.autoUserInterrupted = false;

                    // Only reset the auto scroller if there is a delay set for more than 0 milliseconds
                    // NOTE: THIS CAUSES A MEMORY LEAK, fix before using
                    if (window.autoRestartDelay > 0)
                    setInterval('window.autoIntervalID = setInterval(\'window.thumbnailImageGalleryAuto()\', 1500);',
                    window.autoRestartDelay);
                    
                    */

                    // Don't load up the next auto image, and return info to state that the action didn't happen
                    return false;
                }

            // Save the current image location
            window.galleryImage = $('#imgGallery');
            // Save the new image
            window.newGalleryImage = newSrc;
            // ^(both variables must be global because the fade command is asyncronous)^

            // Fade the current image out
            window.galleryImage.fadeTo(500, 0, function() {
                // Replace the image when it's invisible
                window.galleryImage
                // TODO : The Math.random()*99999 is an IE only fix because load doesn't issue a call back if the
                //  image is cached.
                .attr('src', newGalleryImage + Math.random() * 99999)

                .load(function() {
                    // Adjust the image (if neccessary) by shrinking the proportion
                    //  that is too large by the largest ratio
                    // TODO: doesn't work correctly for some reason
                    //window.imgScaleToFit(this);

                    // Fade the new one back in (a load isn't neccessary since
                    //  all the images are loaded at page load time)
                    window.galleryImage.fadeTo(500, 1);
                });
            });

            // Return information to state that the image was changed
            return true;
        }
    }

    // ---
    // Create the auto scroll method if it doesn't exist already
    // ---
    if (!window.thumbnailImageGalleryAuto)
        window.thumbnailImageGalleryAuto = function() {

            // Set the new image
            if (window.thumbnailImageGallerySelect(window.images.eq(window.autoPos).attr('src'))) {
                // Only increment the auto scroller if the image was changed
                window.autoPos++;
                if (window.autoPos >= window.images.length)
                    window.autoPos = 0;
            }
        }

    // ---
    // Create the display
    // ---
    div.html('<table id="tblGallery" style="width:' + mainWidth + 'px; position:absolute;">' +
            '<tr><td>' +
            '   <div style="width:' + largeImageWidth + 'px; height: ' + largeImageHeight + 'px; text-align: center; margin: 0 0 5px 0; display: inline-block;">' +
            '       <img id="imgGallery" style="padding: 1px; border: solid 1px gray;" />' +
            '   </div>' +
            '<tr><td>' +
            '   <div id="divThumbnailWindow" style="height:46px; position: relative; overflow: hidden;">' +
            '       <div id="divThumbnails" style="overflow: visible; position: relative;">' + div.html() + '</div>' +
            '   </div>' +
            '</table>');

    // Get the thumbnails in their new dom layout
    window.images = $(selector).find('#divThumbnails img');

    // If the list doesn't have more than 1 image,
    //  don't display a thumbnail and don't setup the automatic scroll
    if (window.images.length <= 1) {
        // Hide the thumbnails
        window.images.parents('tr').first().css({
            'display': 'none'
        });

        // Fade in the 1 image normally
        window.thumbnailImageGalleryAuto();

        // Leave the function
        return;
    }

    // Wrap the images in a span tag to allow a static size container
    window.images.wrap('<span></span>').parent('span').css({
        'border': 'solid 1px lightgray',
        'display': 'inline-block',
        'height': '40px',
        'width': '53px',
        'padding': '2px',
        'vertical-align': 'top'
    })

    // Create and map the + and - navigation
    .filter(':not(:last):nth-child(5n)')
    .after('<span style="height: 46px; position: relative; display: inline-block; vertical-align: bottom;">\n' +
        '   <img src="/images/next.jpg" style="position: relative; top: 7px" />\n' +
        '</span>\n')
        .next('span')
        .bind('mouseenter', function() {
            var parent = $(this).parent();

            if (parent.queue().length == 0)
                parent.animate({ top: '-=46' }, 1000);
        })
    .after('<br><span style="height: 46px; position: relative; display: inline-block; vertical-align: bottom;">' +
        '   <img src="images/prev.jpg" style="position: relative; top: 7px" />' +
        '</span>')
        .next('br').next('span')
        .bind('mouseenter', function() {
            var parent = $(this).parent();

            if (parent.queue().length == 0)
                parent.animate({ top: '+=46' }, 1000);
        });

    // Scale the images to fit in the container
    window.images.load(function() {
        imgScaleToFit(this);
    })

    // Map each image to an onclick event to change the main image
    .bind('click', function() {
        // Call the managed switch image command
        window.thumbnailImageGallerySelect(this.src, true);
    })

    // Start the gallery and make it automatically scroll until an image is selected
    window.thumbnailImageGalleryAuto();
    window.autoIntervalID = setInterval('window.thumbnailImageGalleryAuto()', autoscrollDelay);
}
