/*
 *
*/
( function ( $ ) {
	$.fn.slider = function( options ) {
		var defaults = {
			showNumbers	: true,
			delay		: 4000
		};

		//extend default options
		var opts = $.extend( defaults, options );

		var currentItem;
		var nextItem;
		var totalItems;
		var childrenLI;
		var intervalID;
		Init( this );

		// Private functions
		function Init( elem ) {

			//hide everything except the height and width of the ul
			elem.css({'overflow':'hidden'});
			totalItems = elem.children( 'li' ).length;
			childrenLI = elem.children( 'li' );
			currentItem = 0;
			nextItem = 1;

			if ( opts.showNumbers ) { AddNumbers( elem ); }

			// start the slideshow
			intervalID = setInterval( function(){ ShowNext(); }, opts.delay);
			//ShowNext( 0 );
		}
		function ShowThis( nextID ) {
			// get rid of the interval
			clearInterval( intervalID );
			// fade out all the li elements. This way, you dont have to know which particular
			// element is being shown
			$( childrenLI ).fadeOut('slow');
			$('#sliderNumbers a' ).removeClass('numbersHover');
			if ( nextID == 0 ) {
				currentItem = totalItems - 1;
			}
			else {
				currentItem = nextID - 1;
			}
			nextItem = nextID;
			Animate();
		}

		function ShowNext() {
			Animate();
			currentItem = nextItem;
			if ( nextItem == totalItems - 1)
			{
				nextItem = 0;
			}
			else {
				nextItem += 1;
			}
		}

		function Animate() {

			$( childrenLI[currentItem] ).fadeOut('slow');
			$('#sliderNumbers a#' + currentItem ).removeClass('numbersHover');

			$( childrenLI[nextItem] ).fadeIn('slow');
			$('#sliderNumbers a#' + nextItem ).addClass('numbersHover');

		}
		function AddNumbers( elem ) {
			// wrap the slider with a div
			elem.wrap('<div id="sliderWrapper" style="position:relative"></div>');

			// sliderWrapper width is the same as the UL width
			$( '#sliderWrapper').css( 'width', elem.width() ).append('<div id="sliderNumbers"></div>');

			var paraWidth = $( childrenLI[0] ).children('p').width();
			var numbersCSS = {
				'position'	: 'absolute',
				'width'		: paraWidth,
				'bottom'	: 10,
				'right'		: 0
			};
			$('#sliderNumbers').css( numbersCSS );

			// add the numbers
			for( var i=0; i<totalItems; i++) {
				var link = '<a href="#" class="numbers" id="' + i + '">' + (i + 1) + '</a>';
				$('#sliderNumbers').append( link );
			}
			$('#sliderNumbers a').click( function() {
				ShowThis( $(this).attr("id") );
				return false;
			});

			// set the first one to highlighted
			$('#sliderNumbers a#0' ).addClass('numbersHover');
		}

		function Debug ( txt ){
			if ( window.console && window.console.log )
			{
				window.console.log ( txt );
			}
		}

	}
})( jQuery );