var Global = Global || {};

(function () {
    
    Global.MediaCarousel = function (slides, ui, options) {
        var C = {
            options: {
                "delay": 5000,
                "useIndicators": true,
                "activate": function (el) {
                    return el.addClass("active")
                },
                "deactivate": function (el) {
                    return el.removeClass("active")
                }
            },
            init: function () {
                this.slideWrapper = $(slides);
                this.uiWrapper = $(ui);
                this.slides = this.slideWrapper.children();
                this.indicators = [];
                this.setup();
                return this;
            },
            
            setup: function () {
                if (this.options.useIndicators) {
                    this.buildIndicators();
                }
                
                this.currentSlide = 0;
                this.showSlide(this.currentSlide);
                
                if (this.options.delay) {
                    this.runTimer(this);
                }
            },
            
            showSlide: function (i) {
                var _self = this;
                $(_self.slides).each(function (i) {
                    _self.options.deactivate($(_self.slides[i]));
                    $(_self.indicators[i]).removeClass("active");
                });
                _self.options.activate($(_self.slides[i]));
                $(_self.indicators[i]).addClass("active");
                _self.currentSlide = i;
            },
            
            buildIndicators: function () {
                var _self = this;
                for (var i = 0; i < _self.slides.length; i++) {
                    var indicator = $('<a href="#">'+i+'</a>');
                    indicator.bind('click', {key: i}, function(e) {
                        e.preventDefault();
                        _self.showSlide(e.data.key);
                        clearTimeout(_self.timer);
                    });
                    $(_self.uiWrapper).append(indicator);
                    _self.indicators.push(indicator);
                }
            },
            runTimer: function (_self) {
                if (_self.slides.length-1 === _self.currentSlide) {
                    _self.currentSlide = 0;
                } else {
                    _self.currentSlide++;
                }
                
                _self.timer = setTimeout(function () {
                    _self.showSlide(_self.currentSlide);
                    _self.runTimer(_self);
                } , _self.options.delay);
            }
        };
        
        $.extend(true, C.options, options);
        
        return C.init();
    };
})();
