jQuery.fn.jPromoScroller = function(options) {
    var defaults = {
        speed: 8000,
        reverse: true,
		navClass: 'jPromoScroller_nav',
		nav: true
    };
    
    var options = $.extend(defaults, options);
    
    return this.each(function() {
        var promoEl = $(this);
        var listEl = promoEl.find('ul.promoScroller');
       	var navEl = null;
		var elementWidth = promoEl.width();
        
        listEl.find('li').css({
            width: elementWidth,
            height: promoEl.height()
        });
        
		var numChildren = listEl.find('li').length;

		if (options.nav) {
	        var navEl = $('<ul class="' + options.navClass + '"></ul>').appendTo(this);
        
	        for (var i = 0; i < numChildren; i++) {
	            var link = $('<a href="#">' + (i + 1) + '</a>').click(function() {
					goTo(parseInt($(this).text()) - 1);
	                return false;
	            });
            
	            if (options.reverse) {
	                $('<li></li>').prependTo(navEl).append(link);
	            } else {
	                $('<li></li>').appendTo(navEl).append(link);
	            }
	        }
		}

        listEl.css({
			width: listEl.find('li').length * promoEl.width(),
			height: promoEl.height(),
			left: 0,
			position: 'relative'
		});

		var currentIndex = 0;
		var timerId = null;
		var animating = false;
		
		goTo(0);

		function goTo(index) {
			if (!animating) {
				animating = true;
				
				listEl.animate({left: (index * elementWidth * -1) + 'px'}, function() { 
					currentIndex = index; 
					animating = false;
					
					if (navEl != null) {
						navEl.find('li').removeClass('active');
						navEl.find('li:contains(' + (currentIndex + 1) + ')').addClass('active');
					}
				});
				
				if (timerId != null) {
					clearTimeout(timerId);
				}

				timerId = setTimeout(function() { next(); }, options.speed);
			}
		}
		
		function next() {
			goTo((currentIndex + 1) % numChildren);
		}
    });
};