/**
 * 走马灯
 * 
 * @author linxs@35.cn
 */
(function($) { 
	$.fn.cavanLantern = function(o) {
		// 默认参数
		o = $.extend({
			vertical: false,	// 横纵
			forward: true,		// 方向
			step: 2,			// 步长
			speed: 30			// 速度
		}, o || {});
		
		// 插件扩展
		return this.each(function() {
			var timer = null;
			var num = 0;
			var ulSize = visibleSize = totalSize = 0;
			var div = $(this), ul = $("ul", div), li = $("li", ul), img = $("img", li), tl = li.size();
			var animCss = o.vertical ? "top" : "left", sizeCss = o.vertical ? "height" : "width";
			
			o.nowLong = o.nowSize = 0;
			img.each(function() {
				var image = new Image();
				image.onload = function() {
					init();
				}
				image.src = $(this).attr("src");
			});

			// 图片加载完成
			function init() {
				if (++num != tl) {
					return false;
				}
				
				// 由于li的宽度不固定，所以采用下面方式定义totalSize
				visibleSize = o.vertical ? div.height() : div.width();
				li.each(function() {
					ulSize += o.vertical ? $(this).outerHeight(true) : $(this).outerWidth(true);
				});
				totalSize = ulSize;
				if (totalSize > visibleSize) {
					totalSize += ulSize;
					ul.append(li.clone());
				}
				while (totalSize <= visibleSize * 2) {
					totalSize += ulSize;
					ul.append(li.clone());
				}
				li = $("li", ul);
				
				// 设置滚动事件
				o.step = o.forward ? o.step : -o.step;
				o.start = o.nowSize = o.forward ? (visibleSize - totalSize) : 0;
				div.mouseover(function() {
					clearInterval(timer);
				}).mouseout(function() {
					goMove();
				});
				li.css({overflow: "hidden", float: o.vertical ? "none" : "left"});
				ul.css({position: "relative", "list-style-type": "none", "z-index": "1", "padding": "0px", "margin": "0px", animCss: o.start, sizeCss: totalSize + "px"});
				div.css({position: "relative", overflow: "hidden", "z-index": "2", left: "0px", visibility: "visible"});
				
				// 开始
				goMove();
			}

			// 开启滚动
			function goMove() {
				timer = setInterval(function() {
					o.nowLong += o.step;
					o.nowSize += o.step;
					if (Math.abs(o.nowLong) > ulSize) {
						o.nowLong = 0;
						o.nowSize = o.start;
					}
					ul.css(animCss, o.nowSize + "px");
				}, o.speed);
			}
		}); // end plugin
	};
})(jQuery);