$(function(){

    var twitter_username = 'dobs';      // The user to retrieve a Twitter history for.
    var twitter_post_count = 5;         // The number of Twitter posts to retrieve.
    var error_timeout = 5000;           // Timeout on requests, in milliseconds.
    var error_timeout_id = undefined;   // Timeout ID for timeout callback.

    function callback(data) {
        /* A callback for JSON data retrieved from Twitter.
        
        Arguments:
            data: The parsed JSON data retrieved from Twitter.
            
        This callback is called asynchronously as Twitter JSON data is
        retrieved. Existing DOM nodes under #twitter-posts are removed, and
        new nodes are created with the class .twitter-post.
        */
        clearTimeout(error_timeout_id);
        var twitter_posts = $('#twitter-posts')
        twitter_posts.empty();
        $(data).each(function(i, item) {
            var d = new Date(item.created_at);
            var twitter_post = $('<p class="twitter-post"/>').append(textFormat(item.text));
            var twitter_post_meta = $('<span class="twitter-post-meta"/>')
            twitter_post_meta.append('Posted ' + dateFormat(d) + ' &mdash;&nbsp;');
            var link = $('<a>[link]</a>').attr('href', 'http://twitter.com/dobs/status/' + item.id);
            twitter_post_meta.append(link);
            twitter_post.append(twitter_post_meta);
            if (!Modernizr.borderimage) {
                // TODO wrap non-border-image cases.
            }
            twitter_posts.append(twitter_post);
        });
    };

    function dateFormat(d) {
        /* Formatter for Twitter date information.
        
        Arguments:
            d: A date object.
            
        Accepts a JavaScript Date object and returns a relative text date
        similar to Twitter's standard date representations. A date from one
        day ago becomes "Yesterday," for example.
        */
        
        delta = (new Date()).getTime() - d.getTime();
        
        var weeks = Math.floor(delta / 604800000);
        if (weeks == 1) return 'a week ago';
        if (weeks > 1) return weeks + ' weeks ago';
        
        var days = Math.floor(delta / 86400000) % 7;
        if (days == 1) return 'yesterday';
        if (days > 1) return days + ' days ago';
        
        var hours = Math.floor(delta / 3600000) % 24;
        if (hours == 1) return 'an hour ago';
        if (hours > 1) return hours + ' hours ago';

        var minutes = Math.floor(delta / 60000) % 60;
        if (minutes > 5) return minutes + ' minutes ago';

        return 'now';
    };
    
    window.twitterError = function() {
        /* A callback for Twitter timeouts.
        
        Called on a timeout when Twitter requests exceed a set interval.
        */
        $('.twitter-post').text('Loading is taking a while. A timeout may have occurred on Twitter\'s end.');
    };

    function textFormat(text) {
        /* Formatter for Twitter post text.
        
        Arguments:
            text: The text to format.
            
        Formats post text received from Twitter. For example, by converting
        usernames and text URIs into actual links.
        
        TODO: Convert URLs into nofollow links.
        */
        var t = text;
        t = t.replace(/(http:\/\/.+?)(?:\s|$)/g, '<a href="$1" rel="nofollow">$1</a>');
        t = t.replace(/@([a-zA-Z0-9_-]+)/g, '<a href="http://twitter.com/$1" rel="nofollow">@$1</a>');
        return t;
    };
    
    error_timeout_id = setTimeout('twitterError()', error_timeout);
    $.getJSON('http://twitter.com/status/user_timeline/dobs.json?count=5&callback=?', callback);
});
