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

		var options        = $.extend(defaults, options);
    var items          = new Array();
    var currentItem    = 0;
    var currentDomItem = 0;
    var timer          = null;
    var object         = $(this);
    var duringSlide   = 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).append(pagerItem);
      }

      ++ i;
		});

    if (options.pagerSelector)
    {
      $('a', options.pagerSelector).click(function()
      {
        goToItem(parseInt($(this).attr('rel')));
      })
    }

    function goToItem(newItem)
    {
      if (newItem == currentDomItem || duringSlide) return false;

      duringSlide = true;

      if (timer)
      {
        clearTimeout(timer);
      }

      var nbItemsToSlide = 0;

      if (newItem > currentDomItem)
      {
        nbItemsToSlide = newItem - currentDomItem;
      }
      else
      {
        nbItemsToSlide = items.length - currentDomItem + newItem;
      }

      itemWidth     = $(items[0]).width();
      slidePosition = (itemWidth * -1) * nbItemsToSlide;

      $('ul.slide', object).animate(
        { 'left' : slidePosition +'px' },
        options.slideDuration,
        'linear',
        function () { domSwitchAtEnd(nbItemsToSlide); }
      );

      currentDomItem = newItem;
    }

    function slide()
    {
      if (duringSlide) return false;
      
      duringSlide = true;

      itemWidth     = $(items[0]).width();
      slidePosition = (itemWidth * -1);

      $('ul.slide', object).animate(
        { 'left' : slidePosition +'px' },
        options.slideDuration,
        'linear',
        function () { domSwitchAtEnd(1) }
      );

      currentDomItem ++;
      if (currentDomItem > (items.length - 1))
        currentDomItem = 0;
    }

    function domSwitchAtEnd(nbItems)
    {
      var switchItem;
      var itemsArray = $('ul.slide li', object);
      for (j = 0; j < nbItems; ++j)
      {
        switchItem = $(itemsArray[j]).clone();
        $(itemsArray[j]).remove();
        $('ul.slide', object).append(switchItem);
      }
      items = $('ul.slide li', object);

      $('ul.slide', object).css('left', '0');
      duringSlide = false;

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

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