
$(document).ready(function() {

    var timeValue = 2000;
    
    function setVisible(index) {
        $(".top-articles .article"+index).css("display", "block");
        $(".top-articles a.link"+index).addClass("selected");
    }
    
    function clearVisible() {
        $(".top-articles .top-article").css("display", "none");
        $(".top-articles a.link").removeClass("selected");
    }

    function onTimeout() {
        clearTimeout($(".top-articles").data("handler"));
        var current = $(".top-articles").data("current");
        current += 1;
        if (current==$(".top-articles .top-article").length)
            current = 0;
        clearVisible();
        setVisible(current);
        
        $(".top-articles").data("current", current);
        $(".top-articles").data("handler", setTimeout(onTimeout, timeValue));
    }

    function startRotation(index) {
        clearVisible();
        setVisible(index);
        $(".top-articles").data("current", index);
        $(".top-articles").data("handler", setTimeout(onTimeout, timeValue));
    }

    
    $(".top-articles a.link").hover(
        function() {
            clearTimeout($(".top-articles").data("handler"));
            clearVisible();
            $(".top-articles").data("current", Number(this.getAttribute("rel")));
            setVisible($(".top-articles").data("current"));
            return false;
        },
        function() {
            startRotation($(".top-articles").data("current"));
            return false;
        }
    );

    
    $(".top-articles .top-article").hover(
        function() {
            clearTimeout($(".top-articles").data("handler"));
            return false;
        },
        function() {
            startRotation($(".top-articles").data("current"));
            return false;
        }
    );
    
    
    $(".top-articles .top-article").css("display", "none");
    startRotation(0);

});

