// optionally accepts autoadvance in milliseconds
// if not specified, items will only advance manually

(function( $ ){
	$.fn.pageItems = function(options) {
		
		var settings = {
			'autoadvance':	0
		}
		
		return this.each(function(){
			var $this = $(this);
			
			if ( options ) { 
				$.extend( settings, options );
			}

			// set up a container and previous / next buttons
			$this.wrap('<div class="listcontainer" />').parent().append('<p class="pagecontrols"><a href="#" class="prev">Prev</a> <a href="#" class="next">Next</a></p>');
			items = $this.children();
			controls = $this.siblings('.pagecontrols:last');

			// show only the first item
			$this.children().hide();
			$this.children(':first').fadeIn('fast').addClass('shown');
			
			controls.children('.next').click(function(){
				nextitem();
				return false;
			});
			
			controls.children('.prev').click(function(){
				previtem();
				return false;
			});
			
			// functions to move forward and back
			var nextitem = function() {
				if (items.filter('.shown').next().length != 0){ // if not last show previous
					items.filter('.shown').hide().removeClass('shown').next().fadeIn('fast').addClass('shown');
				}
				else {
					items.filter('.shown').hide().removeClass('shown')
					items.filter(':first').fadeIn('fast').addClass('shown');
				}
			}
			var previtem = function() {
				if (items.filter('.shown').prev().length != 0){ // if not first show previous
					items.filter('.shown').hide().removeClass('shown').prev().fadeIn('fast').addClass('shown');
				}
				else {
					items.filter('.shown').hide().removeClass('shown')
					items.filter(':last').fadeIn('fast').addClass('shown');
				}
			}
			
			// autorotation
			if (settings.autoadvance > 0) {
				setInterval(nextitem,settings.autoadvance
				);
			}
		});
	};
})( jQuery );
