(function($) {
	$.fn.paginate = function(options){
		var defaults = {
			'caption': '#teaser-desc-box div.captions div.caption',
			'delay': 6000,
			'fadeSpeed': 2000,
        	'animationType': 'fade'
		}; 
		var options = $.extend(defaults, options); 
		var visuals = this.children('img');
		var captions = this.find(options.caption);
		var count = visuals.length;
		var currentPage = 1;
		var lastPage = 0;
		var clicked = false;
		var timeout;
		
		if (count > 1) {
			var ul = $('<ul class="pagination"></ul>').appendTo(this);
			for(var i=1;i<=count;i++){
				$(captions[i-1]).css('z-index', String(captions.length-i-1)).css('position', 'absolute').hide();
				$(visuals[i-1]).css('z-index', String(visuals.length-i-1)).css('position', 'absolute').hide();
				$('<li data-index="'+ i +'"><a href="#">'+ i +'</a></li>')
					.appendTo(ul)
					.click(function(){	
						clicked = true;
						currentPage = $(this).attr('data-index') -1;
						next();
						return false;
					});					
			};
			$('li[data-index="1"]','.pagination').addClass('active');
	
	        timeout = setTimeout(function() {
	            next();
	        }, options.delay);
	        $(visuals[0]).show();
			$(captions[0]).show();
		}
		
		function next() {
			clearTimeout(timeout);
			$('li','.pagination').removeClass('active');
			$('li[data-index="'+(currentPage+1)+'"]','.pagination').addClass('active');
            $(captions[lastPage]).hide();
            $(captions[currentPage]).show();
			if (options.animationType == 'slide') {
				$(visuals[lastPage]).slideUp(settings.speed);
				$(visuals[currentPage]).slideDown(settings.speed);
			} else if (options.animationType == 'fade') {
	            $(visuals[lastPage]).stop(true, true).fadeOut(options.fadeSpeed);
	            $(visuals[currentPage]).stop(true, true).fadeIn(options.fadeSpeed, function() {
					removeFilter($(this)[0]);
				});
			}
            if ((currentPage + 1) < visuals.length) {
                currentPage = currentPage + 1;
                lastPage = currentPage - 1;
            } else {
                currentPage = 0;
                lastPage = count - 1;
            }
            if (!clicked) {
		        timeout = setTimeout((function() {
		            next();
		        }), options.delay);
            }
		};
		function removeFilter(element) {
			if(element.style.removeAttribute){
				element.style.removeAttribute('filter');
			}
		};		
/*
		function _show(){
			clearTimeout(timeout);
			$(visuals).each(function(i){
				var child = $(this);
				child.fadeOut('slow');
				if(i==page-1){ setTimeout(function(){ child.fadeIn('slow') }, 1000 ); }
			});	
			$('li','.pagination').removeClass('active');
			$('li[data-index="'+page+'"]','.pagination').addClass('active');
		};
		show();
*/
	};
})(jQuery);

