(function($) {

    $.fn.carrusel = function(options) {
        var opts = $.extend({}, $.fn.carrusel.defaults, options);
        return this.each(function() {
            new Carrusel(this, opts);
        });
    };

    $.fn.carrusel.defaults = {
        autoplay: false,
        randomize: false,
        delay: 5000
    };

    var Carrusel = function(el, opts) {
        this.el = $(el);
        this.opts = opts;
        this.list = this.el.find('li');

        this.list.hide();

        if (opts.randomize) {
            this.list.sort(function() {return 0.5 - Math.random()});
        }

        this.build_pagination();
        this.current_page = 1;
        this.show_page(1, true);

        if (this.opts.autoplay) {
            var self = this;
            this.timer = setInterval(function() {
                self.next();
            }, this.opts.delay);

            // Vamos a meter videos e interactuar con ellos.
            // Si se dispara un click en una pestaña detenemos el autoplay
            this.list.one('click', function() {
                if (self.timer) {
                    clearInterval(self.timer);
                }
            });

        }

    };

    Carrusel.prototype.extend = $.extend;
    Carrusel.prototype.extend({
        /* Metemos la paginación en el carrusel */
        build_pagination: function() {

            this.paginator = $('<ul id="paginas-carrusel">');

            var self = this;
            this.paginator.delegate('a', 'click', function(e) {
                e.preventDefault();
                if (self.timer) {
                    clearInterval(self.timer);
                }
                self.show_page(parseInt(this.innerHTML, 10));
            });

            var total = this.list.length;

            for (var i = 1; i<=total; i++) {
                this.paginator.append('<li><a href="#">' + i + '</a></li>');
            }

            this.pages = this.paginator.children();
            this.paginator.appendTo(this.el);
        },

        /**
         * Muestra una ficha del carrusel
         * OJO! Lás páginas empiezan en 1
         */

        show_page: function(page, dont_animate) {


            this.list.eq(this.current_page-1).hide();
            if (dont_animate) {
                this.list.eq(page-1).show();
            } else {
                this.list.eq(page-1).fadeIn('fast');
            }

            this.pages.eq(this.current_page-1).removeClass('active');
            this.pages.eq(page-1).addClass('active');

            this.current_page = page;
        },
        /**
         * Helper para pasar a la siguiente página usando el autoplay
         */
        next: function() {
            if (this.current_page == this.list.length) {
                this.show_page(1);
            } else {
                this.show_page(this.current_page+1);
            }
        }
    });
})(jQuery);
