﻿(function($) {
    $.fn.Scroll = function(o) {
        o = $.extend({
            speed: 30,
            step: 1,
            //滚动步长
            direction: "up",
            //滚动方向
            visible: 1 
            //可见元素数量
        },
        o || {});
        var i = 0;
        var div = $(this);
        var ul = $("ul", div);
        if (o.direction == "left") ul.css("float", "left");
        var ulHeight = ul.height();
        var ulWidth = ul.innerWidth();
        var ulSize = ul.size();
        var divHeight = ulHeight * ulSize;
        var divWidth = ulWidth * ulSize;
        while(ulSize <= o.visible) 
        {
        		div.append(ul.clone());
        		ul = $("ul", div);
        	 	ulSize = ul.size();
        }
        if (ulSize > o.visible) {
            div.append(ul.slice(0, o.visible).clone()) 
            div.css({
                "position": "relative",
                overflow: "hidden"
            });
            ul.css({
                "position": "relative",
                margin: "0",
                padding: "0",
                "list-style": "none"
            });
            switch (o.direction) {
            case "left":
                div.css("width", (ulWidth * o.visible) + "px");
                ul.css("float", "left");
                break;
            case "up":
                div.css({"height":(ulHeight * o.visible) + "px"});
                break;
            }
            var oTimer = setInterval(scrollUp, o.speed);
            div.hover(function() {
                clearInterval(oTimer);
            },
            function() {
                oTimer = setInterval(scrollUp, o.speed);
            });
        };
        function scrollUp() {
            if (o.direction == "left") {
                if (div.scrollLeft() >= divWidth) {
                    div.scrollLeft(0);
                } else {
                    var leftNum = div.scrollLeft();
                    leftNum += parseInt(o.step);
                    div.scrollLeft(leftNum)
                }
            }
            if (o.direction == "up") {
                if (div.scrollTop() >= divHeight) {
                    div.scrollTop(0);
                } else {
                    var topNum = div.scrollTop();
                    topNum += parseInt(o.step);
                    div.scrollTop(topNum);
                }
            }
        };
    };
})(jQuery);
