$('#twitter-feed').append("Loading tweets...");

function relative_created_at(time_value) {  
  var created_at_time = Date.parse(time_value.replace(" +0000",""));
  var relative_time = ( arguments.length > 1 ) ? arguments[1] : new Date();
  var wordy_time = parseInt(( relative_time.getTime() - created_at_time ) / 1000) + (relative_time.getTimezoneOffset()*60);

  if ( wordy_time < 59 ) {
    return 'less than a minute ago';
  } else if ( wordy_time < 89) {
    return 'about a minute ago';
  } else if ( wordy_time < 3000 ) {         // < 50 minutes ago
    return ( parseInt( wordy_time / 60 )).toString() + ' minutes ago';
  } else if ( wordy_time < 5340 ) {         // < 89 minutes ago
    return 'about an hour ago';
  } else if ( wordy_time < 9000 ) {          // < 150 minutes ago
    return 'a couple of hours ago';  
  } else if ( wordy_time < 82800 ) {         // < 23 hours ago
    return 'about ' + ( parseInt( wordy_time / 3600 )).toString() + ' hours ago';
  } else if ( wordy_time < 129600 ) {       //  < 36 hours
    return 'a day ago';
  } else if ( wordy_time < 172800 ) {       // < 48 hours
    return 'almost 2 days ago';
  } else {
    return ( parseInt(wordy_time / 86400)).toString() + ' days ago';
  }
}

function parse_links(str) {
  tokens = str.split(/\s+/);
  parsed = [];
  for(var i = 0; i < tokens.length; i++) {
    if(tokens[i].indexOf('http') == 0) {
      parsed.push('<a href="' + tokens[i] + '">' + tokens[i] + '</a>');
    } else {
      parsed.push(tokens[i]);
    }
  }
  return parsed.join(' ');
}


$(window).load(function() {
  html = '<ul class="twitter-feed">'
  for(var i = 0; i < Twitter.posts.length; i++) {
    html += '<li>';
    html += parse_links(Twitter.posts[i].text);
    html += '<span class="date">' + relative_created_at(Twitter.posts[i].created_at) + '</span>';
    html += '</li>';
  }
  html += '</ul>';
  $('#twitter-feed').replaceWith(html);
  
  $('ul.twitter-feed a').click(function() {
    window.open(this.href);
    return false;
  });
});

