(function ($) {

$.fn.juvoSlideshow = function (options) {
    var options = $.extend({}, $.fn.juvoSlideshow.defaults, options),
        images = options.images,
        gallery = $('<ul>', {
            id: 'home-image-slideshow',
            'class': 'juvo-slideshow'
        }),
        index = $('<div>', {
            id: 'home-image-slideshow-index',
            'class': 'juvo-slideshow-index',
            css: { display: 'none' }
        }),
        indexContainer = $('<div>', {
            id: 'home-image-slideshow-index-container',
            'class': 'juvo-slideshow-index-container'
        }),
        imageLinks = {},
        currentImage = 0,
        numImages = images.length,
        changeImage,
        changeImmediate,
        mainTimer = null,
        indexTimer = null,
        paused = false,
        stopped = false,
        animatingElements = [],
        indexVisible = false,
        indexHidePending = false;

    this.addClass('juvo-slideshow-container')
        .append(gallery)
        .append(indexContainer);

    indexContainer.append(index);

    this.hover(
        function () {
            if (indexVisible) {
                return;
            }
            
            if (indexHidePending) {
                clearTimeout(indexHidePending);
                indexHidePending = false;
            } else {
                index.fadeIn(500);
            }
            
            indexVisible = true;
        },
        function () {
            if (!indexVisible || indexHidePending) {
                return;
            }
            
            indexVisible = false;
            
            indexHidePending = setTimeout(function () {
                indexHidePending = false;
                index.fadeOut(500);
            }, 800);
        }
    );

    $.each(images, function (i, val) {
        var link = $('<a>', { href: val.urls.large, 'class': 'juvo-slideshow-item' }),
            img = $('<img>', { src: val.urls.home }),
            listItem = $('<li>');

        listItem.appendTo(gallery);
        img.appendTo(link);
        link.appendTo(listItem).hide();

        link.bind({
            click: function (e) {
                e.preventDefault();

                var overlay = $('#jOverlayContent'),
                    lightbox = $('#dynamicPhotoLightbox'),
                    container = lightbox.find('.imageContainer'),
                    caption = '';

                paused = true;

                lightbox.jOverlay({
                    url: val.urls.large,
                    bgClickToClose: true,
                    imageContainer: container,
                    imgLoading: '/vendor/images/ajax-loader.gif',
                    opacity: .75,
                    animate: true
                });

                lightbox.one({
                    click: function (e) {
                        $(this).jOverlay('close');
                    },
                    jOverlayLoad: function () {
                        var img = container.find('img');

                        $('#jOverlayContent').css({
                            width: img.width(),
                            height: img.height()
                        });
                    }
                });

                $('#jOverlay').one('jOverlayClose', function () {
                    paused = false;
                });
            }
        });

        if (0 === i) {
            link.show();
        }

        imageLinks[i] = link;
    });

    var prevLink = $('<a>', {
            href: '#',
            html: '<span class="ui-icon ui-icon-circle-triangle-w" /><span class="juvo-text">Prev</span>',
            'class': 'juvo-slideshow-button juvo-slideshow-prevBtn',
            click: function (e) {
                e.stopPropagation();
                changeImmediate(-1);
            }
        }),
        nextLink = $('<a>', {
            href: '#',
            html: '<span class="juvo-text">Next</span><span class="ui-icon ui-icon-circle-triangle-e" />',
            'class': 'juvo-slideshow-button juvo-slideshow-nextBtn',
            click: function (e) {
                e.stopPropagation();
                changeImmediate(1);
            }
        }),
        allLink = $('<a>', {
            html: '<span class="juvo-text">View All</span><span class="ui-icon ui-icon-circle-arrow-e" />',
            'class': 'juvo-slideshow-button juvo-slideshow-viewAllBtn',
            href: options.viewAllUrl
        });

    $([prevLink.get(0), nextLink.get(0), allLink.get(0)]).appendTo(index);

    var setupTimer = function () {
        mainTimer = setTimeout(function () {
            mainTimer = null;
            changeImage();
        }, options.slideInterval);
    };

    changeImmediate = function (delta) {
        newIndex = (currentImage + numImages + delta) % numImages;
        
        clearTimeout(mainTimer);
        stopped = true;
        
        $.each(animatingElements, function (i, val) {
            val.stop(true, true);
        });

        gallery.find('.juvo-slideshow-item:visible').not(imageLinks[newIndex]).fadeOut(options.forcedTransitionSpeed);
        imageLinks[newIndex].not(':visible').fadeIn(options.forcedTransitionSpeed);
        currentImage = newIndex;
    };

    changeImage = function () {
        if (stopped || paused) {
            stopped || setupTimer();
            return;
        }

        var nextImage = (currentImage + 1) % numImages;

        animatingElements = [imageLinks[currentImage], imageLinks[nextImage]];

        imageLinks[currentImage].fadeOut(options.transitionSpeed);
        imageLinks[nextImage].fadeIn(options.transitionSpeed, function (e) {
            currentImage = nextImage;
            stopped || setupTimer();
        });
    };

    setupTimer();
    
};

$.fn.juvoSlideshow.defaults = {
    images: [],
    viewAllUrl: false,
    slideInterval: 15000,
    transitionSpeed: 3000,
    forcedTransitionSpeed: 250
};

})(jQuery);
