﻿/*
    Uses Slides (see http://slidesjs.com/) to provide two types of carousel:
    
     A carousel with one big image
     
     - or -
     
     A carousel with one big image and three thumbnail images to the right
*/
$(function() {

    $("div.highlight-carousel").each(function() {
        var hightlightCarousel = $(this);
        var slidesContainer = $(".slides_container", hightlightCarousel);
        var numberOfSlides = slidesContainer.children().length;

        var thumbsControl = $(".thumbs_container .thumbs_control", hightlightCarousel);
        var hasThumbs = thumbsControl.length == 1;
        var thumbsHeight = 0;
        var thumbsControlBottom = null;
        var visibleThumbs = 3;
        var numberOfThumbs = 0;

        // If we have thumbnails on the right they'll need positioning
        if (hasThumbs) {
            thumbsHeight = thumbsControl.children().first().height();
            numberOfThumbs = thumbsControl.children().length;
            thumbsControlBottom = (numberOfThumbs - visibleThumbs) * thumbsHeight;
            thumbsControl.css("bottom", thumbsControlBottom)

            var last = thumbsControl.children().last();
            for (var i = (numberOfThumbs - 2); i > 0; i--) {
                var next = thumbsControl.children().eq(i);
                next.insertAfter(last);
                last = next;
            }
        }

        // Only create a carousel if we have more than one slide
        if (numberOfSlides > 1) {
            hightlightCarousel.slides({
                preload: true,
                preloadImage: "/images/loading.gif",
                effect: hasThumbs ? "fade" : "fade",
                crossfade: true,
                play: 5000,
                fadeSpeed: 1500,
                slideSpeed: 500,
                generateNextPrev: false,
                generatePagination: true,

                animationStart: function() {
                    if (hasThumbs) {
                        thumbsControl.animate({
                            bottom: parseInt(thumbsControl.css("bottom")) - thumbsHeight
                        },
                            500,
                            function() {
                                // Move last item to first position in list
                                var first = thumbsControl.children().first();
                                var last = thumbsControl.children().last();
                                last.insertBefore(first);

                                // Reset the position
                                thumbsControl.css("bottom", thumbsControlBottom);
                            });
                    }
                }
            });
        }
        else {
            slidesContainer.show();
        }
    });

}) 

