window.addEvent('domready', function() {
    new Request.JSONP({
        url: 'http://api.twitter.com/1/statuses/user_timeline.json',
        data: {
            screen_name: 'ben_bliss',
            count: 4
        },
        onComplete: function(tweets){
            console.log(tweets);
            
            Object.each(tweets, function(tweet){
                //Format dates nicely.
                var created_date = Date.parse(tweet.created_at).format('%B %e');
                
                //Link up twitter usernames or links in tweets
                tweet_words = tweet.text.split(' ');
                var marked_up_words = '';
                Object.each(tweet_words, function(word){
                    var tw_username = word.match(/^@(\w+)/);
                    var h_link = word.match(/^http:\/\/\S+/);
                    if(tw_username){
                        word = '<a href="http://twitter.com/' + tw_username[1] + '">' + word + '</a>';
                    }
                    if(h_link){
                        word = '<a href="' + h_link + '">' + word + '</a>';
                    }
                    marked_up_words = marked_up_words + word + ' ';
                });
                
                //Inject li elements with tweet text and date.
                var tweetli = new Element('li', { html: '<p>' + marked_up_words + '</p>' });
                var tweet_date = new Element('div', { 
                    html: created_date + ' via ' + tweet.source,
                    class: 'tweet-date'
                });
                tweetli.grab(tweet_date);
                $('tweet-list').grab(tweetli);
            });
        },
        count: 3
    }).send();
});
