var Rotator = {
    options : {
        rotatorID : '#rotator',
        rotateTime : 7,
        animationTime: 0.5
    },
    
    init : function (o) {
        Rotator.count = $(Rotator.options.rotatorID +" ul li").size();
        if (Rotator.count < 2) return;
        $.extend(Rotator.options, o || {}) 

        // add paging
        $(Rotator.options.rotatorID).append('<div class="paging"><span></span></div>');
        $(Rotator.options.rotatorID + ' ul li').each(function(index) { $(Rotator.options.rotatorID +' .paging span').append('<a href="#" rel="'+(index)+'">'+(index+1)+'</a>');});
        $(Rotator.options.rotatorID + " .paging").show();

        // set up on first
        $(Rotator.options.rotatorID + " .paging a:first").addClass("current");
        Rotator.current = 0;
        $(Rotator.options.rotatorID +" ul li:first").css('z-index', 2);
     
        // set up hover to stop rotate
        $(Rotator.options.rotatorID).hover(function() {       
            clearInterval(Rotator.timer);
        }, function() {
            Rotator.startTimer();
        });	
        
        $(Rotator.options.rotatorID + " .paging a").click(function() {	
            Rotator.next = $(this).attr('rel');
            Rotator.rotate();
            return false;
        });	
        
        Rotator.startTimer();     
    },
    
    startTimer : function() {
        clearInterval(Rotator.timer);
        Rotator.timer = setInterval(Rotator.rotate, Rotator.options.rotateTime*1000);
    },
    
    rotate : function() { 
        clearInterval(Rotator.timer);
        if (!Rotator.next) {
            Rotator.next = (Rotator.current + 1) % Rotator.count;
        }
        else if (Rotator.next == Rotator.current) {
            Rotator.next = null;
            return;
        }

        $(Rotator.options.rotatorID + " .paging a").removeClass("current");
        $(Rotator.options.rotatorID + " .paging a").eq(Rotator.next).addClass("current");

        $(Rotator.options.rotatorID +" ul li").each(function (index) {
            if (Rotator.next  == index) {
                $(this).css('opacity', 0).css('z-index', 2).animate({ 'opacity': 1 }, Rotator.animationTime, 'linear');
            }
            else if (Rotator.current  == index) {
                $(this).css('z-index', 1);
            }
            else {
                $(this).css('z-index', 0);
            }
        });
    
        Rotator.startTimer();
        Rotator.current = Rotator.next;
        Rotator.next = null;
    }
};
