﻿/*
 * jQuery JavaScript Library Marquee Plus
 * http://mzoe.com/
 *
 * Copyright (c) 2009 MZOE
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * Date: 2009-05-13 18:54:21
 */
(function($) {
	$.fn.marquee = function(o) {
		//获取滚动内容内各元素相关信息
		o = $.extend({
			speed:		30,
			step:		1, //滚动步长
			direction:	"up", //滚动方向
			pause:		0 // 停顿时长
		}, o || {});
		var dIndex = jQuery.inArray(o.direction, ['right', 'down']);
		if (dIndex > -1) {
			o.direction = ['left', 'up'][dIndex];
			o.step = -o.step;
		}
		var div 		= $(this); // 滚动容器对象
		var ul 			= $("ul", div);
		var li 			= $("li", ul);
		var liSize 		= li.size(); // 初始元素个数
		var liWidth 	= li.width(); // 元素宽
		var liHeight 	= li.height(); // 元素高
		var ulWidth 	= ul.innerWidth();
		var ulHeight 	= ul.innerHeight();
		if ((o.direction == 'left' && liWidth * liSize > ulWidth) || 
			(o.direction == 'up' && liHeight * liSize > ulHeight)) {
			// 元素超出可显示范围才滚动
			ul.append(li.clone()); // 复制元素
			li = $("li", ul);
			liSize = li.size();
			if (o.direction == 'left') {
				ul.width(liSize * liWidth);
				if (o.step < 0) div.scrollLeft(ulWidth);
			} else {
				ul.height(liSize * liHeight);
				if (o.step < 0) div.scrollLeft(ulHeight);
			}
			var m = setInterval(_marquee, o.speed);
			ul.hover(
				function(){clearInterval(m);},
				function(){m = setInterval(_marquee, o.speed);}
			);
		}
		function _marquee() {
			// 滚动
			if (o.direction == 'left') {
				var l = div.scrollLeft();
				if (o.step < 0) {
					div.scrollLeft(l <= 0 ? ulWidth : l + o.step);
				} else {
					div.scrollLeft(l >= ulWidth ? 0 : l + o.step);
				}
				if (l % liWidth == 0) _pause();
			} else {
				var t = div.scrollTop();
				if (o.step < 0) {
					div.scrollTop(l <= 0 ? ulHeight : l + o.step);
				} else {
					div.scrollTop(l >= ulHeight ? 0 : l + o.step);
				}
				if (l % liHeight == 0) _pause();
			}
		}
		function _pause() {
			// 停顿
			if (o.pause > 0) {
				clearInterval(m);
				setTimeout(function() {
					m = setInterval(_marquee, o.speed);
				}, o.pause);
			}
		}
	};
})(jQuery);
