﻿jQuery.fn.gallerize = function (config) {
    $(this).addClass('gallerize');
    var $mainGalleryList = $('.fullsize', this);
    var $mainGalleryListItems = $('li', $mainGalleryList);
    var $thumbnailsList = $('.thumbnails', this);
    var currentIndex = 0;
    var autoPlayTimeout = null;
    var transitionTime = 1000;
    var autoPlayDelay = 10000;

    var hideItem = function ($item) {
        $item.hide();
    };

    var showItem = function ($item) {
        $item.show();
    };

    var transitionEffect = function ($currentItem, $nextItem) {
        hideItem($currentItem);
        showItem($nextItem);
    };

    var setup = function () {
    };

    var switchTo = function (index) {
        if (index == currentIndex) return;
        clearTimeout(autoPlayTimeout);
        var $currentItem = $($mainGalleryListItems[currentIndex]);
        var $nextItem = $($mainGalleryListItems[index]);


        transitionEffect($currentItem, $nextItem);
        setAutoPlayTimeout(index);
        setSelectedThumbnail(index);

        currentIndex = index;
    };

    var fadeToThruBlack = function ($currentItem, $nextItem) {

        $currentItem.fadeOut(transitionTime, function () {

            $nextItem.fadeIn(transitionTime);
        });

    };

    var fade = function ($currentItem, $nextItem) {

        $currentItem.fadeOut(transitionTime);
        $nextItem.fadeIn(transitionTime);
    };

    var setAutoPlayTimeout = function (index) {
        var destinationIndex = index + 1;
        if (destinationIndex >= $mainGalleryListItems.length) destinationIndex = 0;

        autoPlayTimeout = setTimeout(function () { switchTo(destinationIndex); }, autoPlayDelay);
    };

    var setSelectedThumbnail = function (index) {
        $('li.selected', $thumbnailsList).removeClass('selected');
        $($('li', $thumbnailsList)[index]).addClass('selected');
    };

    var createThumbnails = function () {
        var $thumbnailTemplate = $('<li class=""><img src="" alt="" /></li>');
        $('li', $mainGalleryList).each(function (index) {
            var $thumbnail = $thumbnailTemplate.clone();
            var $img = $('img', this);
            $('img', $thumbnail)
                .attr('src', $img.attr('src'))
                .attr('alt', $img.attr('alt'));
            $thumbnail
                .attr('class', $(this).attr('class'))
                .click(function () { switchTo(index); })
                .appendTo($thumbnailsList);
        });
    };

    var prepare = function () {
        createThumbnails();
        hideItem($mainGalleryListItems);
        showItem($($mainGalleryListItems[currentIndex]));
        setSelectedThumbnail(currentIndex);
        setAutoPlayTimeout(currentIndex);
    };

    var configure = function () {
        transitionEffect = fade;

        setup();
    }

    configure();
    prepare();
    return this;
};


