jQuery(document).ready(function($) {
    // Declare variables to hold twitter API url and user name
    var api_url         = 'http://search.twitter.com/search.json?callback=?&';
    var twitter_user    = 'ktchn';
    var no_of_tweets    = 2;
    var tweet_container = $('#tweet_container');
    
    // Enable caching
    $.ajaxSetup({ cache: true });

    // Send JSON request
    // The returned JSON object will have a property called "results" where we  
    // find a list of the tweets matching our request query
    $.getJSON(
        api_url + 'rpp=' + no_of_tweets + '&q=from:' + twitter_user,
        function(data) {
            tweet_container.append('<ul><\/ul>');
            
            $.each(data.results, function(i, tweet) {
                // Uncomment line below to show tweet data in Fire Bug console
                // Helpful to find out what is available in the tweet objects
                //console.log(tweet);
                
                // Before we continue we check that we got data
                if(tweet.text !== undefined) {
                    // Calculate how many hours ago was the tweet posted
                    var date_tweet = new Date(tweet.created_at);
                    var date_now   = new Date();
                    var date_diff  = date_now - date_tweet;
                    var hours      = Math.round(date_diff/(1000*60*60));
                    
                    // Build the html string for the current tweet
                    var tweet_html = '<li class="tweet_text">';
                    tweet_html    += tweet.text + ' - ';
                    tweet_html    += '<span class="tweet_hours">';
                    tweet_html    += '<a href="http://www.twitter.com/';
                    tweet_html    += twitter_user + '/status/' + tweet.id;
                    tweet_html    += '" target="_blank" >' + hours;
                    tweet_html    += ' hours ago<\/a><\/span><\/li>';

                    // Append html string to tweet_container div
                    tweet_container.children().append(tweet_html).autolink();
                }
            });
        }
    );

    // Autolink funcion
    jQuery.fn.autolink = function () {
        return this.each(function() {
            var pattern     = /((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g;
            var replacement = '<a href' + '="$1" target="_blank">$1<\/a>';
            $(this).html($(this).html().replace(pattern, replacement));
        });
    };
    
});

