(function($) {

	// plugin definition
	$.fn.scrollControl = function(options) {
		
		var opts = $.extend( {}, $.fn.scrollControl.defaults, options );

		return this.each(function() {
		
			var animating = false;
			var currentPaging = 1;
			var iWatch = 0;
			
			var items = $(this).find(".scroll-group .item");
			var numItems = items.size();
			var numPerGroup = opts.controlColumns * opts.controlRows;
			var numGroups = Math.ceil(numItems/numPerGroup);
			var itemWidth = Math.floor(opts.controlWidth/opts.controlColumns);
			var numItemsLastGroup = numPerGroup - ((numGroups*numPerGroup) % numItems);
			
			var scrollControl = $('<div class="scroll_control" />');
			var scrollPaging = $('<div class="scroll_paging" />');
			var previousButton = $('<a class="btn_previous" href="#">Previous</a>');
			var nextButton = $('<a class="btn_next" href="#">Next</a>');
			var scrollPages = $('<span class="scroll_pages" />');
			var scrollControlWrap = $('<div class="scroll_control_wrap" />');
			var scroll = $('<div class="scroll" />');
			var scrollWrap = $('<div class="scroll_wrap" />');

			var pagingTag = $('<a href="javascript:void(0);">1</a>');
			var pagingArray = [];

			var scrollGroup = $('<div class="scroll_group" />');					
			var scrollGroupArray = [];
			
			// Adjust variables if the number of items is not enough to populate one group
			if ( numItems < (opts.controlColumns * opts.controlRows) )
			{
				for (var x=1; x<opts.controlRows; x++)
				{
					if (numItems < (opts.controlColumns * x))
					{
						opts.controlHeight = (opts.controlHeight / opts.controlRows) * x;
						opts.controlRows = x;
						break;
					}
				}
			}
			
			// Create the requisite HTML for the control
			$(this).append(scrollControl);
			scrollControl.append(scrollControlWrap);			
			scrollControl.append(scrollPaging);
			scrollPaging.append(previousButton);
			scrollPaging.append(scrollPages);
			scrollPaging.append(nextButton);
			scrollControlWrap.append(scroll);
			scroll.append(scrollWrap);
			
			// Populate each of the groups with the items in the list
			for ( var i=0; i<numGroups; i++ )
			{
				pagingArray[i] = pagingTag.clone();
				pagingArray[i].html(i+1);
			
				scrollGroupArray[i] = scrollGroup.clone();
			
				scrollWrap.append(scrollGroupArray[i]);
				for ( var j=0; j<numPerGroup; j++ )
				{
					if ( ((i)*(numPerGroup))+(j+1) <= numItems )
					{
						scrollGroupArray[i].append( items[((i)*(numPerGroup))+(j)] );
					}
					else
					{
						break;
					}
				}
				
				scrollPages.append(pagingArray[i]);
				
				if (i < numGroups - 1)
				{
					scrollPages.append('|');
				}
				
			}

			// Set up dynamic styles for each scroller
			scrollControl.css({ width: opts.controlWidth + "px", height: opts.controlHeight + "px" });					
			scrollPaging.css("width", opts.controlWidth + "px");										
			scrollControlWrap.css({ width: opts.controlWidth + "px", height: opts.controlHeight + "px" });
			scrollWrap.css({ width: numGroups*opts.controlWidth + "px", height: opts.controlHeight + "px" });					
			scroll.css({ width: opts.controlWidth + "px", height: opts.controlHeight + "px" });
			
			$(this).find(".scroll_group").css({ width: opts.controlWidth + "px", height: opts.controlHeight + "px" });
			//$(this).find(".scroll_wrap .item").css({ padding: "7px 9px 9px 9px", width: (opts.controlWidth/opts.controlColumns) - 18 + "px", height: (opts.controlHeight/opts.controlRows) - 16 + "px" });
			$(this).find(".scroll_wrap .item").css({ width: itemWidth + "px", height: Math.floor(opts.controlHeight/opts.controlRows) + "px" });
			
			// Hide the original data
			$(this).children(".scroll-group").css("display", "none");
		
			// Add the paging functionality if there is more than 1 "group"
			if (numGroups > 1 && opts.paging)
			{
				pagingArray[0].addClass("current");
				
				$(pagingArray).each(function(i){
					$(this).click(function(e){
						goToPage(i + 1)
					});
				});
				
			}
			else
			{
				if (opts.singleScroll)
				{
					scrollPaging.children(".scroll_pages").css("display", "none");						
				}
				else
				{
					scrollPaging.css("display", "none");
					scrollControl.addClass("scroll_control_no_paging");						
				}

			}

			// Set up event handler for "next" button
			nextButton.bind("click", this, function(e){
				
				if (!opts.singleScroll)
				{
					if ( scrollWrap.position().left != Math.ceil( -(numGroups*opts.controlWidth - opts.controlWidth)) )
					{
						goToPage(currentPaging + 1);
					}
				}
				else
				{
					if ( numItemsLastGroup >= opts.controlColumns )
					{
						if ( scrollWrap.position().left != Math.ceil( -(numGroups*opts.controlWidth - opts.controlWidth)) )
						{
							goToPage(currentPaging + 1);								
						}
					}
					else
					{
						if ( scrollWrap.position().left != Math.ceil( -((numGroups-1) * opts.controlWidth) + (opts.controlColumns-numItemsLastGroup)*itemWidth ) )
						{								
							goToPage(currentPaging + 1);								
						}
					}
				}
				return false;
				
			});
		
			// Set up event handler for "previous" button
			previousButton.bind("click", this, function(e){
				if ( scrollWrap.position().left != 0 )
				{
					goToPage(currentPaging - 1);
				}
				return false;
			});

			function goToPage(i) {

				if ( animating || i == currentPaging ) return;

				i--;

				animating = true;
				
				if (opts.singleScroll)
				{
					scrollWrap.animate({ left: i * -itemWidth + "px" }, opts.scrollSpeed, "swing", endAnimation );						
				}
				else
				{
					pagingArray[currentPaging - 1].removeClass("current");
					pagingArray[i].addClass("current");
					
					scrollWrap.animate({ left: ( i * -opts.controlWidth ) + "px" }, opts.scrollSpeed, "swing", endAnimation );
				}
				
				currentPaging = i + 1;						
			}
			
			function endAnimation() {
				animating = false;
				
				if (!opts.singleScroll)
				{
					if ( Math.abs( Math.ceil( -(numGroups*opts.controlWidth - opts.controlWidth)) - scrollWrap.position().left) > 5 )
					{
						nextButton.css("display", "block");
					}
					else
					{
						nextButton.css("display", "none");						
					}
				}
				else
				{
					if ( numItemsLastGroup >= opts.controlColumns )
					{
						if ( Math.abs( Math.ceil( -(numGroups*opts.controlWidth - opts.controlWidth)) - scrollWrap.position().left) > 5 )
						{
							nextButton.css("display", "block");
						}
						else
						{
							nextButton.css("display", "none");
						}
					}
					else
					{
						if ( Math.abs(Math.ceil( -((numGroups-1) * opts.controlWidth) + (opts.controlColumns-numItemsLastGroup)*itemWidth ) - scrollWrap.position().left) > 5 )
						{								
							nextButton.css("display", "block");
						}
						else
						{
							nextButton.css("display", "none");							
						}
					}
				}
				
				if ( scrollWrap.position().left != 0 )
				{
					previousButton.css("display", "block");
				}
				else
				{
					previousButton.css("display", "none");					
				}
			}
		
			endAnimation();
		
		});
		
	};
	
	$.fn.scrollControl.defaults = {
		controlWidth: 887,
		controlHeight: 127,
		controlColumns: 3,
		controlRows: 3,
		scrollSpeed: 600,
		paging: true,
		singleScroll: false
	};
	
})(jQuery);