/* requires jquery.timers.js plugin */

(function($){
	/* check for jQuery presence */
	if (!jQuery) return alert('Warning: jQuery framework failed to load');
	
	$.fn.conveyor = function(options) {
		var self = $(this);
		
		//dom node of source data must be specified, or we cannot continue
		if (!options) return self;
		
		
		

		
		//entire table
		self.html('<table cellspacing="0" cellpadding="0"><tr><td colspan="3"><div class="main"></main></td></tr><tr class="navigation"><td class="left"></td><td class="paging" valign="middle"></td><td class="right" align="right"></td></tr>');
		
		//# holder of individual items (the "belt")
		var show = $("<div></div>").appendTo(".main")
		.end()
		.addClass('showholder');
		
		
		//# left & right nav arrows 
		$('img[name=left]')
		.clone()
			.prependTo($('td.left'))
				.end()
			.attr('id','left')
			.end()
		.remove();
		
		$('img[name=right]')
		.clone()
			.appendTo($('td.right'))
				.end()
			.attr('id','right')
			.end()
		.remove();
		
		//default settings (needs overhaul)
		var settings = {
			selection : '.scrollmenu',
			itemwidth : show.width(),
			itemheight : show.height(),
			spacer : 28,
			cssOverride : true,
			removeOriginal : true
		};
		
		//if second argument is a selector string, turn it into an object for the merge
		if(typeof(options) === "string") options = {selection:options};
		
		//custom settings override default settings
		$.extend(settings, options);	
		
		
		//if (settings.cssOverride) {
		//self.width(settings.buttonwidth*2 + settings.itemwidth);
		//show.width(settings.itemwidth).height(settings.itemheight);
		//}
		
		//Width in pixels between each scrolling item. 
		//This variable is a bridge for determining which item is currently in view 
		//(css-left / interval = our array position: 0, 1, 2...)
		var interval = settings.itemwidth + settings.spacer,
		
		
		//$s = DOM node of source data, wrapped in jQuery
		make = function($s){
			
			//////////////////////////////////////////////////////
			//# structure
			
			//# inner holder of item divs 
			$("<div></div>").appendTo(".showholder")
			.end()
			.addClass('items')
			.css('left','0px');
			
			//# generate item divs from list (supports div, ul, ol, span, etc)
			$s.children().each(function(i){			
				return $("<div></div>")
				.addClass('scrollitem')
				.appendTo(".showholder .items")
					.end()
				.css("left",((interval*i) + "px"))	
				.append("<h1>"+($(".title",this).html())+'</h1><p style="color:#68696C;">'+($(".description",this).html())+"</p>");
			});
			
			//# remove original unordered list -- it has served its purpose
			if (settings.removeOriginal) $s.remove();
			
			
			//# iphone-style page buttons
			//# they're not really circles--they're squares. A bg image can be added to ".circle" in the css file
			$("<div id='pager'></div>").appendTo('td.paging');
			var pager = "<table><tr>";
			$(".scrollitem").each(function(i){
				pager += "<td><div class='circle'></div></td>";
			});
			pager += "</tr></table>";
			$('#pager').html(pager);
			
			
			
			//# light up the circle indicator of the current page 
			//# getindex() determines the index number of the item in view
			$('.circle:eq('+getindex()+')').addClass('active');
			
			
			//////////////////////////////////////////////////////
			// wiring 
			
			//# hook up the navi buttons 
			$("#left,#right").click(function(){
				//# ((true=left, false=right),interval) 
				return animate(($(this).attr('id') === 'left'),interval);	
			});
			
			//# hook up the circles 
			$('.circle').click(function(){
				var $self = $(this);
				if ($self.hasClass('active')) return false;
				
				var $all = $('.circle'),
				current = $all.index($('.active')),
				destination = $all.index($self);
				
				//# (isleft, distance, interval) 
				return animate((destination < current),(Math.abs(destination - current))*interval,interval);
			});
			
			//# div mouseover stops timed automation 
			self.mouseenter(function(){
				return $(document).stopTime('scrollthru');			 
			}).mouseleave(function(){
				return scrollthru();
			});
			
			//# fire up the scrolling 
			return scrollthru();
		},
		
		/////////////////////////////////////////////////
		//# determine index of current item
		getindex = function(){
			return parseInt($('.items').css('left'))/-interval;
		},
		
		/////////////////////////////////////////////////
		//# timed automation 
		//# loop event (requires "jquery.timers.js" plugin) 
		//# syntax: everyTime(duration[ms] between loops, name of this function, function itself, iterations [0 = endless])
		
		scrollthru = function(){
			return $(document).everyTime(settings.scrolltime,'scrollthru',function(){
				return animate(false,interval);
			},0);
		},
		
		/////////////////////////////////////////////////
		//# scroll to another item 
		//# (isleft,distance,interval) 
		//# (isleft,interval) 
		
		animate = function(x,d,i){
		
			//# second argument is both distance and interval if interval is not specified
			var i = i || d,
			
			//# determine left/right border status 
			c = getindex(),
			si = $(".scrollitem").length-1;
			
			//# If we're at the first item (c >= si), and scrolling left (!x), instead of going off the page,
			//# go all the way to the last item on the page. (and vice versa).
			//#
			//# si = number of items in film strip
			//# -d = distance (inverted, because we want to go the opposite of the direction that was clicked
			if ( (c >= si && !x) || (c <= 0 && x) ) d = si * -d;
			
			//# animate setup is {'left' : (+ or -)=###px} 
			return $(".items").animate({'left': ((x)?"+":"-") +"="+d+"px"}, 'slow', 'linear',function(){
			   
				//# update page indicator 
				$('.circle').removeClass('active')
				.eq(getindex())
				.addClass('active');
				
			});
		}
		
		//////////////////////////////////////////////
		// execute
		make($(settings.selection));
		
		return(self);
	}
})(jQuery);

