/**
* author Remy Sharp
* url http://remysharp.com/tag/marquee
*/

(function($) {
	$.fn.marquee = function(klass, timeout) {
		var newMarquee = [],
            last = this.length;

		// works out the left or right hand reset position, based on scroll
		// behavior, current direction and new direction
		function getReset(newDir, marqueeRedux, marqueeState) {
			var behavior = marqueeState.behavior, width = marqueeState.width, dir = marqueeState.dir;
			var r = 0;
			if (behavior == 'alternate') {
				r = newDir == 1 ? marqueeRedux[marqueeState.widthAxis] - (width * 2) : width;
			} else if (behavior == 'slide') {
				if (newDir == -1) {
					r = dir == -1 ? marqueeRedux[marqueeState.widthAxis] : width;
				} else {
					r = dir == -1 ? marqueeRedux[marqueeState.widthAxis] - (width * 2) : 0;
				}
			} else {
				r = newDir == -1 ? marqueeRedux[marqueeState.widthAxis] : 0;
			}
			return r;
		}

		function isFirstChildOut(marqueeRedux, marqueeState, width) {
			return marqueeRedux[marqueeState.axis] > width;
		}

		function isLastChildOut(marqueeRedux, marqueeState, width) {
			var currentEl = $(marqueeRedux.childNodes[0].childNodes[marqueeRedux.childNodes[0].childNodes.length - 1]);
			var currentParentEl = $(marqueeRedux.childNodes[0]);
			return currentParentEl.position().left + currentEl.position().left - width > marqueeState.width;
		}

		function moveFirstToEnd(marqueeRedux, marqueeState, width) {
			var c = marqueeRedux.childNodes[0].removeChild(marqueeRedux.childNodes[0].childNodes[0]);
			marqueeRedux.childNodes[0].appendChild(c);
			marqueeRedux[marqueeState.axis] -= width;
		}

		function moveLastToStart(marqueeRedux, marqueeState, width) {
			var c = marqueeRedux.childNodes[0].removeChild(marqueeRedux.childNodes[0].childNodes[marqueeRedux.childNodes[0].childNodes.length - 1]);
			marqueeRedux.childNodes[0].insertBefore(c, marqueeRedux.childNodes[0].childNodes[0]);
			marqueeRedux[marqueeState.axis] += width;
		}

		function duplicateToFillWidth(marqueeRedux, width) {
			while ($(marqueeRedux.childNodes[0]).outerWidth(true) < width) {
				var length = marqueeRedux.childNodes[0].childNodes.length;
				for (var i = 0; i < length; i++) {
					var clone = marqueeRedux.childNodes[0].childNodes[i].cloneNode(true);
					marqueeRedux.childNodes[0].appendChild(clone);
				}
			}
		}

		var firstDragChildWidth = null;
		var lastDragChildWidth = null;

		function drag(current, next) {
			marqueeRedux = newMarquee[0];
			$marqueeRedux = $(marqueeRedux);
			marqueeState = $marqueeRedux.data('marqueeState');

			if (firstDragChildWidth == null)
				firstDragChildWidth = $(marqueeRedux.childNodes[0].childNodes[0]).outerWidth(true);

			if (lastDragChildWidth == null)
				lastDragChildWidth = $(marqueeRedux.childNodes[0].childNodes[marqueeRedux.childNodes[0].childNodes.length - 1]).outerWidth(true);

			if (current > next) {
				if (isLastChildOut(marqueeRedux, marqueeState, lastDragChildWidth)) {
					moveLastToStart(marqueeRedux, marqueeState, lastDragChildWidth);
					$marqueeRedux.data('scrollX', $marqueeRedux.data('scrollX') + lastDragChildWidth);
					firstChildWidth = null;
					firstDragChildWidth = null;
					lastDragChildWidth = null;
				}

				marqueeRedux[marqueeState.axis] -= current - next;
			} else {
				if (isFirstChildOut(marqueeRedux, marqueeState, firstDragChildWidth)) {
					moveFirstToEnd(marqueeRedux, marqueeState, firstDragChildWidth);
					$marqueeRedux.data('scrollX', $marqueeRedux.data('scrollX') - firstDragChildWidth);
					firstChildWidth = null;
					firstDragChildWidth = null;
					lastDragChildWidth = null;
				}

				marqueeRedux[marqueeState.axis] += next - current;
			}
		}

		function checkFirstChildWidth(marqueeRedux) {
			if (firstChildWidth == null)
				firstChildWidth = $(marqueeRedux.childNodes[0].childNodes[0]).outerWidth(true);
		}

		function scroll(marqueeRedux, marqueeState) {
			var amount = (marqueeState.scrollamount * marqueeState.dir);
			scrollAmount += amount;
			//document.body.append(amount);

			marqueeRedux[marqueeState.axis] += amount;
		}

		var scrollAmount = null;
		var firstChildWidth = null;
		// single "thread" animation
		function animateMarquee() {
			var i = newMarquee.length,
                marqueeRedux = null,
                $marqueeRedux = null,
                marqueeState = {},
                newMarqueeList = [],
                hitedge = false;

			while (i--) {
				marqueeRedux = newMarquee[i];
				$marqueeRedux = $(marqueeRedux);
				marqueeState = $marqueeRedux.data('marqueeState');

				if ($marqueeRedux.data('paused') !== true) {
					checkFirstChildWidth(marqueeRedux);
					if (firstChildWidth != null) {
						scroll(marqueeRedux, marqueeState);


						if (scrollAmount > firstChildWidth) {
							moveFirstToEnd(marqueeRedux, marqueeState, firstChildWidth);
							scrollAmount = 0;
							firstChildWidth = $(marqueeRedux.childNodes[0].childNodes[0]).outerWidth(true);
						}

						newMarqueeList.push(marqueeRedux);
						marqueeState.last = marqueeRedux[marqueeState.axis];

						// store updated state only if we ran an animation
						$marqueeRedux.data('marqueeState', marqueeState);
					}
				} else {
					// even though it's paused, keep it in the list
					newMarqueeList.push(marqueeRedux);
				}
			}

			newMarquee = newMarqueeList;

			if (newMarquee.length) {
				setTimeout(animateMarquee, timeout);
			}
		}

		// TODO consider whether using .html() in the wrapping process could lead to loosing predefined events...
		this.each(function(i) {
			var $marquee = $(this),
                width = $marquee.attr('width') || $marquee.width(),
                height = $marquee.attr('height') || $marquee.height(),
                $marqueeRedux = $marquee.after('<div ' + (klass ? 'class="' + klass + '" ' : '') + 'style="display: block-inline; width: ' + width + 'px; height: ' + height + 'px; overflow: hidden;"><div style="float: left; white-space: nowrap;">' + $marquee.html() + '</div></div>').next(),
                marqueeRedux = $marqueeRedux.get(0),
                hitedge = 0,
                direction = ($marquee.attr('direction') || 'left').toLowerCase(),
                marqueeState = {
                	dir: /down|right/.test(direction) ? -1 : 1,
                	axis: /left|right/.test(direction) ? 'scrollLeft' : 'scrollTop',
                	widthAxis: /left|right/.test(direction) ? 'scrollWidth' : 'scrollHeight',
                	last: -1,
                	loops: $marquee.attr('loop') || -1,
                	scrollamount: $marquee.attr('scrollamount') || this.scrollAmount || 2,
                	behavior: ($marquee.attr('behavior') || 'scroll').toLowerCase(),
                	width: /left|right/.test(direction) ? width : height
                };

			var itemsContainer = marqueeRedux.childNodes[0];
			for (var i = 0; i < itemsContainer.childNodes.length; i++) {
				var item = itemsContainer.childNodes[i];
				if (item.nodeName == '#text')
					itemsContainer.removeChild(item);
			}

			firstChildWidth = $(itemsContainer.childNodes[0]).outerWidth(true);
			if (firstChildWidth != null && jQuery(itemsContainer).outerWidth(true) < width + firstChildWidth) {
				//itemsContainer.appendChild(document.createTextNode(' '));
				duplicateToFillWidth(marqueeRedux, width + firstChildWidth);
			}


			// corrects a bug in Firefox - the default loops for slide is -1
			if ($marquee.attr('loop') == -1 && marqueeState.behavior == 'slide') {
				marqueeState.loops = 1;
			}

			$marquee.remove();

			// events
			$marqueeRedux.bind('mouseover', function() {
				$marqueeRedux.trigger('stop');
			}).bind('mouseout', function() {
				if ($marqueeRedux.data('drag') == true) {
					var currentMouseY = event.clientY;
					var currentMouseX = event.clientX;
					var offset = $marqueeRedux.offset();
					var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body

					currentMouseY = (document.all ? iebody.scrollLeft : pageXOffset) + currentMouseY;
					currentMouseX = (document.all ? iebody.scrollTop : pageYOffset) + currentMouseX;

					if (offset.top > currentMouseY || offset.top + $marqueeRedux.outerHeight(false) - 2 <= currentMouseY ||
                        offset.left > currentMouseX || offset.left + $marqueeRedux.outerWidth(false) < currentMouseX) {
						$marqueeRedux.data('drag', false);
						$marqueeRedux.trigger('start');
					}
				}
				else {
					$marqueeRedux.trigger('start');
				}

			}).bind('mousemove', function() {
				if ($marqueeRedux.data('drag') == true) {
					var current = this.scrollLeft;
					var next = $marqueeRedux.data('scrollX') + ($marqueeRedux.data('x') - event.clientX);
					drag(current, next);
					scrollAmount = null;
				}
			}).bind('mousedown', function() {
				$marqueeRedux.data('drag', true).data('x', event.clientX).data('scrollX', this.scrollLeft);
			}).bind('mouseup', function() {
				firstDragChildWidth = null;
				lastDragChildWidth = null;
				$marqueeRedux.data('drag', false);
			})

			$marqueeRedux.bind('stop', function() {
				$marqueeRedux.data('paused', true);
			}).bind('pause', function() {
				$marqueeRedux.data('paused', true);
			}).bind('start', function() {
				$marqueeRedux.data('paused', false);
			}).bind('unpause', function() {
				$marqueeRedux.data('paused', false);
			}).data('marqueeState', marqueeState); // finally: store the state

			// todo - rerender event allowing us to do an ajax hit and redraw the marquee

			newMarquee.push(marqueeRedux);

			marqueeRedux[marqueeState.axis] = getReset(marqueeState.dir, marqueeRedux, marqueeState);
			$marqueeRedux.trigger('start');

			// on the very last marquee, trigger the animation
			//if (i + 1 == last) {
			animateMarquee();
			//}

		});

		return $(newMarquee);
	};
} (jQuery));

