(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,
    arrows: false,
    pages: true,
    delay: 5000
  };

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

    if (opts.randomize) {
      this.list.sort(function() { return 0.5 - Math.random(); });
    }
    
    if (opts.pages) {
      this.build_pagination();
    }
    if (opts.arrows) {
      this.build_arrows();
    }
    
    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 flechas de atras/adelante */
      build_arrows: function() {
        this.arrows = $('<div class="arrows"></div>');
        
        var self = this;
        
        $('<a href="#" class="prev">Anterior</a>').click(function() {
          self.prev();
        }).appendTo(this.arrows);
        
        $('<a href="#" class="next">Siguiente</a>').click(function() {
          self.next();
        }).appendTo(this.arrows);
        
        
        
        this.arrows.appendTo(this.el);
        
        
      },
      
      
      /* Metemos la paginación en el carrusel */
      build_pagination: function() {

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

        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);
        }
      },
      
      /* Helper para pasar a la página anterior */
      prev: function() {
        if (this.current_page == 1) {
          this.show_page(this.list.length);
        } else {
          this.show_page(this.current_page - 1);
        }
      }
      
      
    });
    })(jQuery);
