﻿(function () {

    $.widget('ui.LDD_contentCarousel', {
        options: {
            autoPlay: true,
            delay: 5000,
            fadeDuration: 400,
            startIndex: 0
        },

        _animationInterval: null,
        _animating: false,
        _currentIndex: 0,
        _nextIndex: 0,
        _slides: null,

        _create: function () {
            var self = this;
            var el = this.element;

            this._slides = $(el).find('.slide').toArray();

            if (this._slides.length > 1) {
                for (var i = 0; i < this._slides.length; i++) {
                    var slide = this._slides[i];
                    $(slide).css('position', 'absolute');
                    if (i > 0) {
                        $(slide).css('display', 'none');
                    }
                    $(slide).detach();
                }

                $(el).empty();

                $(el).append(this._slides[this.options.startIndex]);




                if (this.options.autoPlay) {
                    this._play();
                }
            }
        },

        _play: function () {
            this._initInterval();
        },

        _initInterval: function () {
            this._animationInterval = window.setInterval($.proxy(this._tick, this), this.options.delay);
        },

        _tick: function () {
            this._next();
        },

        _next: function () {
            this._nextIndex = this._currentIndex + 1;

            if (this._nextIndex >= this._slides.length) {
                this._nextIndex = 0;
            }

            this._showSlide(this._slides[this._nextIndex]);
        },

        next: function () {
            this._next();
        },

        _previous: function () {
        },

        previous: function () {
            this._previous();
        },

        _showSlide: function (s) {
            $(this.element).append(s);
            $(s).css('top', 0);
            $(s).css('z-index', '20');
            $(s).fadeIn(this.options.fadeDuration, $.proxy(this._onFadeComplete, this));
        },

        _onFadeComplete: function () {
            $(this._slides[this._currentIndex]).detach();
            $(this._slides[this._currentIndex]).css('display', 'none');
            $(this._slides[this._nextIndex]).css('z-index', '0');

            this._currentIndex = this._nextIndex;
        },

        destroy: function () {

        }
    });
})(jQuery);
