var slideshow = (function($) {
    /*
    ** Slideshow based on code found at http://jonraasch.com/blog/a-simple-jquery-slideshow
    **
    ** Navigation derived from http://tympanus.net/Tutorials/SweetThumbnails
    */

    var ps_nav = $('.ps_nav');
    var $tooltip = $('.ps_preview'); // why is this a class and not an id?
    var $ps_preview_wrapper = $('.ps_preview_wrapper');
    var $links;
    var currentHovered = -1;
    var current = 0;
    var shortInterval;
    var slideshowInterval;
    var standardDisplayTimes = {fadeTime: 1300, showTime: 1700};
    var selectedDisplayTimes = {fadeTime: 50, showTime: 70};

    $tooltip.css({opacity: 0}).show();

    function slideSwitch() {
        var $active = $('#slideshow div.active');
        var $activeDot = $('#slider_control ul li.active');

        if ( $active.length == 0 ) $active = $('#slideshow div:last');
        if ( $activeDot.length == 0 ) $activeDot = $('#slider_control ul li:last');

        // Find the next div containing an image to display.  If not found, go back to the beginning
        var $next = $active.next().length
                        ? $active.next()
                        : $('#slideshow div:first');
        var $nextDot = $activeDot.next(':not(.ps_preview)').length
                        ? $activeDot.next()
                        : $('#slider_control ul li:first');
        switchImage($active, $activeDot, $next, $nextDot, standardDisplayTimes);
    }

    function switchImage($currentImage, $activeControl, $nextImage, $nextControl, delay) {
        if ($currentImage == $nextImage) return;
        $currentImage.addClass('last-active').animate({opacity : 0.0}, delay.fadeTime);

        $nextImage.css({opacity: 0.0})
                .addClass('active')
                .animate({opacity: 1.0}, delay.showTime, function() {
                            $currentImage.removeClass('active last-active');
                            });
        $activeControl.removeClass('active');
        $nextControl.addClass('active');
    }


    function runSlideshow() {

        $links = $('.ps_nav li').not($tooltip);
        $('#slider_control ul li:first').addClass('active');
        $('#slideshow').fadeIn(1700);
        startSlideshow(0);
        $('.ps_nav').hover(
                pauseSlideshow,
                function() {
                    startSlideshow(1000);
                }
        )
        $('#slider_control a').each(function(index) {
            $(this).hover(showTooltip, hideTooltip).click(function() {
                // switch the view to the nth item.  fade current item
                // to the new item
                var newImage = $('#slideshow div')[index];
                var $activeImage = $('#slideshow div.active');

                if (index != $activeImage.index()) {
                    var $activeDot = $('#slider_control ul li.active');
                    switchImage($activeImage, $activeDot, $(newImage), $(this).parent(), selectedDisplayTimes);
                    hideTooltip();
                }
            })
        })
    }

    function pauseSlideshow() {
        if (shortInterval) {
            clearTimeout(shortInterval);
        }
        clearInterval(slideshowInterval);
    }

    function startSlideshow(initialDelay) {
        if (initialDelay) {
            shortInterval = setTimeout(slideSwitch, initialDelay);
        }
        slideshowInterval = setInterval(slideSwitch, 5000);
    }

    function showTooltip() {
        pauseSlideshow();
        var $link = $(this).parent();
        var index = $link.index();
        var linkOuterWidth = $link.outerWidth();
        var left = parseFloat(index * linkOuterWidth) - $tooltip.width()/2 + linkOuterWidth/2 - 5;
        var imageLeft;
        var thumb = $(this).attr('rel');

        // could we check for a class instead?
        if (currentHovered != index) {
            if (currentHovered != -1) {
                if (currentHovered < index) {
                    imageLeft = 75;  // based on size of display box
                }
                else {
                    imageLeft = -75;
                }
            }

            currentHovered = index;

            var $newImage = $('<img/>').css('left', '0px').attr('src', thumb).attr('width', 75).attr('height', 75);

            if ($ps_preview_wrapper.children().length > 1) {
                $ps_preview_wrapper.children(':last').remove();
            }

            $ps_preview_wrapper.prepend($newImage);

            var $tooltip_images = $ps_preview_wrapper.children();
            var tooltip_images_count = $tooltip_images.length;

            if(tooltip_images_count > 1) {
                $tooltip_images.eq(tooltip_images_count - 1)
                                .stop()
                                .animate({left: -imageLeft+'px'}, 150, function() { $(this).remove(); });
                $tooltip_images.eq(0)
                                .css('left', imageLeft + 'px')
                                .stop()
                                .animate({left:'0px'}, 150);
            }
        }

        $tooltip.stop()
                .css('z-index', 1000)
                .animate({left: left + 'px', opacity: 1}, 150);
    }

    function hideTooltip() {
        $tooltip.stop()
                .animate({opacity: 0}, 150);
    }

    return {
        runSlideshow: runSlideshow
    }
})(jQuery);

/* Initial setup */

jQuery(document).ready(function($) {
    var $loading = $('#loading');
    $('#slideshow div:first').addClass('active');
    $loading.fadeIn(1000);

    // Add dots whenever a new image is loaded

    var $controlList = $('#slider_control li.ps_preview');
    var loadCounter = 0;
    var $images = $('#slideshow div img');
    $('#slideshow div img').load(function() {
        if (loadCounter < $images.length) {
            $controlList.before('<li><a href="#">Image ' + loadCounter + '</a></li>');
        }
        ++loadCounter;
    }).each(function() {
        if (this.complete) $(this).trigger('load');
    });


    // When the window load event fires it means all image assets have been loaded, fade our placeholder and start the slide show.
    $(window).load(function() {
        var $links = $('.ps_nav a');
        $('#slideshow div img').each(function(index){
            var $link = $links.get(index).rel = $(this).attr('src');
        });
        $loading.fadeOut(1000, slideshow.runSlideshow)
    });
})
