/*
 * Autoscroll jQuery Plugin
 * http://www.dirnonline.com/
 *
 * Copyright 2010, dirnonline
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Version: 1.0.0 (05/20/2010)
 * Requires: jQuery v1.4+
 *
 */
(function($) {
	jQuery.fn.extend({
			autoScroll: function(options) {
					// Capture instance
					var $this = $(this);

					var settings = $.extend({
							autoScroll: true,
							disabled: 'disabled',
							interval: 10,
							next: '.next',
							prev: '.previous',
							step: 15
						}, options);

					// Loop through the selector results so that each is handled separately
					// And return this so more functions can be daisy chained
					return $this.each(function() {
							// Capture instances
							var $this = $(this);
							var $parent = $this.parent(); // wrapper
							var $children = $this.children(); // children

							var $width = 0;
							$children.children().each(function() {
									$width += $(this).outerWidth(true);
								});
							$children.width($width);
							$width -= $this.width();

							$children.css('left', 0);

							var $interval;

							var $previous = $parent.find(settings.prev);
							$previous
								.addClass(settings.disabled)
								.bind('mouseover', function() {
										$interval = setInterval(function() {
												scroll(1);
											}, settings.interval);
									})
								.bind('mouseout', function() {
										clearInterval($interval);
									});

							var $next = $parent.find(settings.next);

							if ($width <= 0) {
								$next.addClass('disabled');
							}
							else {
								$next.removeClass('disabled');
							}

							$next
								.bind('mouseover', function() {
										$interval = setInterval(function() {
												scroll(-1);
											}, settings.interval);
									})
								.bind('mouseout', function() {
										clearInterval($interval);
									});

							var scroll = function(direction) {
									if ($width <= 0) return;

									var left = parseInt($children.css('left'), 10);
									var new_left = left + direction * settings.step;

									if (new_left > 0) {
										new_left = 0;
									}
									else if (new_left < -$width) {
										new_left = -$width;
									}

									$children.css({
											left: new_left
										});

									if (new_left == 0) {
										$previous.addClass('disabled');
									}
									else {
										$previous.removeClass('disabled');
									}
									if (new_left == -$width) {
										$next.addClass('disabled');
									}
									else {
										$next.removeClass('disabled');
									}
								};

							if (settings.autoScroll) {
								$interval = setInterval(function() {
										scroll(-1);
									}, settings.interval);
							}
						});
				}
		});
	})(jQuery);