/*
jQuery cycling slider
*/

(function( $ ){

	$.fn.cycle = function( options )
	{
		var o = {
			itemsVisible:1,
			duration:300,
			autoNext:8000
		}
		$.extend(o, options);
		return this.each(function(){

			var itemsVisible = o.itemsVisible;
			var duration = o.duration; // milliseconds for animation

			var pt = $(this);
			pt.children().clone().appendTo(pt); // duplicate the list

			var items = pt.children('li');
			var count = items.length;
			var w = items.eq(0).width(); // grab the width of the first item
			var current = count /2;

			pt.width( w * itemsVisible ); // set the container to the width of the first item times the number of items
			pt.height( items.eq(0).height() ); // set the container to the height of the first item

			items.each(function(idx){
				$(this).css({'position':'absolute', 'top':'0', 'left':w * idx});
			});

			$.scrollTo.defaults.axis = 'x';
			pt.scrollTo( w * current );//reset the screen to (0,0)



			var offsetWidth = pt[0].offsetWidth;
			if(o.prev)
			{
				$(o.prev).click(function(){
					clearInterval(timer);
					function after (){
						current--;
						if(current == 0)
						{
							current += count/2;
							pt.scrollTo( w * current );
						}
						timer = startTimer();
					}

					pt.scrollTo('-=' + (w) + 'px', duration, {onAfter:after});
					return false;
				});
			}

			if(o.next)
			{
				$(o.next).click(gotoNext);
			}

			function gotoNext()
			{
				clearInterval(timer);
				function after (){

					current++;
					if(current == (count - itemsVisible))
					{
						current -= count/2;
						pt.scrollTo( w * current );

					}
					timer = startTimer();
				}

				pt.scrollTo('+=' + (w) + 'px', duration, {onAfter:after});
				return false;
			}

			function startTimer()
			{
				return setInterval(gotoNext, o.autoNext);
			}

			var timer = startTimer(); // timer

			// if a play AND pause button are specified, set up separate handlers
			if(o.play && o.pause)
			{
				$(o.play).click(gotoNext);

				$(o.pause).click(function(){
					clearInterval(timer);
					return false;
				})
			}

			// if a play button is specified with no pause button, create a toggle
			if(o.play && !o.pause)
			{
				$(o.play).click(function()
				{

					if(timer)
					{
						clearInterval(timer);
						timer = null;
					}else{
						gotoNext();
					}
					return false;
				});
			}

		});

	}

})( jQuery );
