﻿jQuery(document).ready(function($) {
    // Declare variables to hold twitter user timeline
    var twitter_user_timeline = 'http://twitter.com/statuses/user_timeline/70099985.json';

    // 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(
        twitter_user_timeline + '?callback=?',
        function(data) {
            $.each(data, function(i, tweet) {
                if (i > 0) return;
                
                // Uncomment line below to show tweet data in Fire Bug console
                // Very 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 time 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 time       = Math.round(date_diff/(1000*60*60));
                    var text       = "hours";
                    
                    if(time >= 24)
                    {
                        time = Math.round(time/24);
                        text = "days";
                    }

                    // Build the html string for the current tweet
                    var tweet_html = '<img src="/common/images/tweet-top.jpg" alt="Twitter" />';
                    tweet_html    += '<div class="tweet">';
                    tweet_html    += tweet.text.replace(/(http:\/\/(\S+))/gim, '<a href="$1" target="_blank">$2</a>');
                    tweet_html    += '<\/div><div class="tweet-foot">' + time + ' ';
                    tweet_html    += text + ' ago<\/div>';

                    // Append html string to tweet_container div
                    $('.twitter').append(tweet_html);
                }
            });
        }
    );
});

