(function($){
  $.fn.heroCarousel = function(trail){
    return this.each(function(){
      
      var container = $(this),
          ul = container.find('ul'),
          image = ul.find('li').find('img')[0],
          image_width = image.width,
          image_height = image.height,
          image_count = ul.find('li').length;
      if(image_count > 1) {
        container.css({
          position: 'relative',
          height: image_height + 24
        });
        ul.width(image_width * image_count);
        ul.css({
          position:'absolute'
        });
      
        addNavigation();
      }
      else {
        ul.height(image_height);
      }
      
      container.everyTime(6000, function(){
        if($(container).find('a.active+a').length > 0) {
          advance($(container).find('div.hero_carousel_nav a.active+a'));
        }
        else {
          advance($(container).find('div.hero_carousel_nav a')[0]);
        }
      });
      
      
      function addNavigation() {
        var navigation = $('<div></div>', {
          "class": 'hero_carousel_nav',
          css: {
            position: 'absolute',
            bottom: 0,
            left: 0
          }
        }).appendTo(container);
        
        for(var index = 0; index < image_count; index++) {
          $('<a></a>',{
            text: index,
            css: {
              cursor: 'pointer'
            },
            click: function() {
              container.stopTime();
              advance(this);
            }
          }).appendTo(navigation);
        }
        navigation.find('a:first-child').addClass('active');
      };
      
      function advance(link) {
        $(link).parent('div').find('a').removeClass('active');
        $(link).addClass('active');
        ul.animate({
          left: -container.width() * $(link).text()
        });
        
      }
      
    });
  };
})(jQuery);
