jQuery(function ($) {
    function scroll_tweet(li){
        
        var post = li.children("div.post"),
        pWidth = post.width();
        if (pWidth > parseInt(balloon.css('width'))){
            var leftEnd = li.find('div.end');
            if(leftEnd.length === 0){
                leftEnd = $('<div class="end left" />').appendTo(li);
            } 
            var offsX = parseInt(leftEnd.width());
            post.animate({left: offsX - pWidth - 55}, 23000, 'linear', function(){post.css('left', offsX);});
        }
    }

    function swap_tweets(current_tweet){
        var next_tweet = (current_tweet + 1) % 3; /* max five tweets */
        var li = $("li#tweet" + next_tweet);

        $("#tweet" + current_tweet).fadeOut(300).css('display', 'none');
        setTimeout(function(){
            li.fadeIn(400).css('display', 'block');
         }, 400);

        setTimeout(function(){scroll_tweet(li);}, 3800);                

        display_tweet = next_tweet;
        setTimeout(function(){swap_tweets(display_tweet);}, 11300);
    }
        
    var balloon = $("#twitterpost div.balloon");
    display_tweet = 0;
    if($("div.balloon ul li#tweet1").html() !== null){
        setTimeout(function(){swap_tweets(display_tweet);}, 12000);
        var firstli = $("li#tweet0");
        setTimeout(function(){scroll_tweet(firstli);}, 7500);
    }

});

