﻿
(function ($) {
    var Slideshow = function (element, options) {
        var elem = $(element);
        var obj = this;
        var settings = $.extend({
            duration: 5000
        }, options || {});

        var currentIndex = 0;
        var completed = 0;
        var id = 0;

        var nextIndex = function () {
            var length = elem.children().length;
            if (length == currentIndex + 1) {
                return 0;
            } else {
                return currentIndex + 1;
            }
        };

        var checkIfReady = function () {
            completed++;
            if (completed == 2) {
                completed = 0;
                elem.oneTime(settings.duration, nextId(), nextFade);
            }
        };

        var nextId = function () {
            id++;
            return id;
        };

        var nextFade = function () {
            var child = null;

            // Fade out
            child = $(elem.children()[currentIndex]);
            child.css({ display: "block" });
            child.fadeTo('slow', 0, function () {
                $(this).css({ display: "none" });
                checkIfReady();
            });

            currentIndex = nextIndex();

            // Fade in
            child = $(elem.children()[currentIndex]);
            child.css({
                opacity: 0,
                display: "block"
            });
            child.fadeTo('slow', 1.0, function () {
                checkIfReady();
            });
        };

        elem.oneTime(settings.duration, nextId(), nextFade);
    };

    $.fn.slideshow = function (options) {
        return this.each(function () {
            var element = $(this);
            if (element.data('slideshow')) return;
            var slideshow = new Slideshow(this, options);
            element.data('slideshow', slideshow);
        });
    };
})(jQuery);

