(function($)
{
	$.fn.carrousel = function(options)
  {
		// default configuration properties
		var defaults = 
    {
      delay:         5000,
      slideDuration: 500,
      pagerSelector: null
    };

		var options     = $.extend(defaults, options);
    var items       = new Array();
    var currentItem = 0;
    var timer       = null;
    var object      = $(this);

    // nothing if not enough items
    if ($('ul.slide li', this).length <= 1)
    {
      return false;
    }

    // each carrousel items
    var i = 0;
		$('ul.slide li', this).each(function()
    {
      items[i] = $(this);

      if (options.pagerSelector)
      {
        pagerItem = $('<li><a href="#" rel="'+ i +'">' + (i + 1) +'</a></li>');
        $(options.pagerSelector, object).append(pagerItem);
      }
      ++ i;
		});

    if (options.pagerSelector)
    {
      $('a[rel=0]', object).addClass('current');
      $('a', options.pagerSelector).click(function(e)
      {
        e.preventDefault();
        goToItem(parseInt($(this).attr('rel')));
      })
    }

    function slide()
    {
      var nextItem = currentItem + 1;
      if (nextItem > (items.length -1))
      {
        nextItem = 0;
      }
      goToItem(nextItem);
    }

    function goToItem(newItem)
    {
      if (timer)
      {
        clearTimeout(timer);
      }

      itemWidth = $(items[currentItem])[0].offsetWidth;
      finalLeft = itemWidth * newItem * -1;

      minFinalLeft = (items.length - 1) * itemWidth * -1;
      if (finalLeft < minFinalLeft)
      {
        finalLeft = 0;
      }

      $('ul.slide', object).animate({
        left: finalLeft +'px'
      });//, options.slideDuration, 'linear');

      $('a[rel='+ currentItem +']', object).removeClass('current');
      currentItem = newItem;
      $('a[rel='+ currentItem +']', object).addClass('current');

      timer = setTimeout(function() { slide(); }, options.delay);
    }

    timer = setTimeout(function() { slide(); }, options.delay);
    
  }
})(jQuery);
