jQuery.fn.extend({
		'rotator': function (timeout){
			try
			{
				return initRotator(this,timeout);
			}
			catch(e)
			{
				
			}
		}
	});

function initRotator(elms,timeout)
{
	var second = 1;
	elms.each(function(){

		var id = $(this).attr('id');
		
		if (id==undefined) {
			id = '_randid_'+ Math.floor(Math.random()*100000);
			$(this).attr('id',id);
		}

		items = $('#'+id+' .rotatorItem').length;
		var paging = $('<ul class="rotatorPaging rotatorPaging-'+id+'"></ul>');
		
		var currentItem = 1;
		var ZIndexMax = 99;
		var ZIndexMin = 50;

		paging.css('z-index',ZIndexMax+1);
		
		i = 0;
		$(this).append(paging);
		$('#'+id+' .rotatorItem').each(function(){
			i++;
			
			$(this).addClass('rotatorItem-'+i);

			if (i==1) {
				$(this).show();
				$(this).addClass('current');
			}
			else {
				$(this).hide();
			}

			pagingItemLi = $('<li></li>');

			pagingItem = $('<a href="#" class="jumpTo-'+i+'"></a>');
			pagingItemLi.append(pagingItem);
			paging.append(pagingItemLi);
			
			if (i==1) {
				pagingItem.addClass('current');
			}
			
			$('#'+id+' a.jumpTo-'+i).click(function(){

				currentI = $(this).attr('class').replace('jumpTo-','').replace(' current','');
				$(this).addClass('current');

				rotateTo(currentI);
				
				return false;
			})
		});

		function rotateTo(item)
		{
			if (item == currentItem)
			{
				return false;
			}
			
			currentItemElm = $('#'+id+' .rotatorItem-'+currentItem);
			nextItemElm = $('#'+id+' .rotatorItem-'+item);

			$('#'+id+' .rotatorItem').css('z-index',ZIndexMin);
			
			currentItemElm.css('z-index',ZIndexMax).show();
			nextItemElm.css('z-index',ZIndexMax-1).show();

			$('.rotatorPaging-'+id+' li a').removeClass('current');
			$('.rotatorPaging-'+id+' li a.jumpTo-'+item).addClass('current');
			
			currentItemElm.fadeOut('slow',function(){
				currentItemElm.hide();
				
	
				currentItem = item;
				second = 1;
				return true;
			});
		}

		function rotateNext()
		{
			nextItem = currentItem+1;
			if (nextItem > items)
			{
				nextItem = 1;
			}
			rotateTo(nextItem);
		}

		window.setInterval(function() 
		{
			if (second*1000 >= timeout)
			{
				rotateNext();
				second = 0;
			}
			second++;
		}, 1000);
	})
	
}
