/**
 * Uses jquery
 */
var twitterUsername = 'uucidl';

$.fn.clickUrl = function() {
    var regexp = /((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g;
    var regexpb = /\B@([_a-z0-9]+)/ig;
    this.each(function() {
        $(this).html(
            $(this).html().replace(regexp, '<a href="$1">$1</a>')
        );
        $(this).html(
            $(this).html().replace(regexpb, '<a href="http://www.twitter.com/$1">@$1</a>')
        );
    });
    return $(this);
}

function relative_time(time_value) {
    var values = time_value.split(" ");
    time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    delta = delta + (relative_to.getTimezoneOffset() * 60);
    if (delta < 60) {
        return 'a moment ago';
    } else if (delta < 120) {
        return 'a minute ago';
    } else if (delta < (60 * 60)) {
        return (parseInt(delta / 60)).toString() + ' minutes ago';
    } else if (delta < (120 * 60)) {
        return 'an hour ago';
    } else if (delta < (24 * 60 * 60)) {
        return (parseInt(delta / 3600)).toString() + ' hours ago';
    } else if (delta < (48 * 60 * 60)) {
        return '1 day ago';
    } else {
        return (parseInt(delta / 86400)).toString() + ' days ago';
    }
}
$(function() {
    $.getJSON('http://twitter.com/status/user_timeline/'+twitterUsername+'.json?count=20&callback=?', function(data) {
        for (var i=0;i<data.length;i++) {
            var tweet = data[i];
            if (tweet.text.match(/^ *@/)) continue;
            var q = $('#twitter-status');
            q.find('div.body > p').html(tweet.text).clickUrl();
            q.find("div.body > img").attr('src', tweet.user.profile_image_url);
            q.find('h2 .time').text(relative_time(tweet.created_at)+' to '+tweet.user.followers_count+' followers');
            q.find('h2 a').attr('href', 'http://twitter.com/'+twitterUsername+'/status/'+tweet.id);
            q.fadeOut(200, function(){ q.fadeIn(300); });
	    break;
        }
    });
});

