$(document).ready(function() {
    
    $('#tweets').load('/inc/twitter.php', function(e) {
        
        // Constants
        var TWEET_MARGIN = 20;
        var TWEET_OFFSET = 20;

        var $tweets = $('#twitter #tweets li').hide();
        var $container = $('#twitter');
        var current = $tweets.length - 1;

        // Pause the interval on mouseover
        $tweets.hover(function() { clearInterval(interval); }, startInterval);

        function showTweet(tweet) {
            var $tweet = $(tweet);

            var pos = randomPosition(tweet);

            $tweet.css({ 
                opacity: 0, 
                display: 'block',
                top: pos.y + 'px',
                left: pos.x + 'px'
            }).animate({ opacity: 1, top: '+=' + TWEET_OFFSET + 'px', left: '+=' + TWEET_OFFSET + 'px' }, 900, 'easeOutBack');
        }

        function hideTweet(tweet) {
            var $tweet = $(tweet);

            $tweet.animate({ opacity: 0, top: '-=20px', left: '-=20px' }, 300, 'easeOutBack', function() {
                $(this).hide();
            });
        }

        function randomPosition(tweet) {
            var $tweet = $(tweet);

            var xMax = $container.width() - $tweet.outerWidth() - TWEET_MARGIN - TWEET_OFFSET;
            var yMax = $container.height() - $tweet.outerHeight() - TWEET_MARGIN - TWEET_OFFSET;

            var xPos = Math.round(Math.random() * xMax);
            var yPos = Math.round(Math.random() * yMax);

            xPos = (xPos < TWEET_MARGIN) ? xPos + TWEET_MARGIN : xPos;
            yPos = (yPos < TWEET_MARGIN) ? yPos + TWEET_MARGIN : yPos;

            if(!$('.full').length) {
                xPos = (xPos < 275) ? xPos += 275 : xPos;
            }

            return { x: xPos, y: yPos };
        }

        var interval;
        function startInterval() {
            interval = setInterval(function() {
                hideTweet($tweets.get(current));

                current = (current == 0) ? $tweets.length - 1 : current - 1;

                showTweet($tweets.get(current));
            }, 4000);
        }

        showTweet($tweets.get(current));
        startInterval();
        
    });

    
    $('#expand').click(function(event) {
        event.preventDefault();
        
        $('#headline').animate({ top: '360px' }, 500, 'easeOutBack');
        $('#content').animate({ paddingTop: '440px' }, 500, 'easeOutBack');
        $('#twitter, #parallax').animate({ height: '300px' }, 500, 'easeOutBack', function() {
            $('body').addClass('full');
            var parallax = $('#parallax').html();
            $('#parallax').replaceWith('<ul id="parallax">' + parallax + '</ul>');
            $('#parallax').jparallax({ mouseport: $('#twitter') });
        });
        $('#parallax li').animate({ height: '350px' }, 500, 'easeOutBack');
        $(this).fadeOut(500);
    });

    $('#parallax').jparallax({ mouseport: $('#twitter') });
        
});