function load_tweets(query) {
	var last_ID = $(".tweet_result:first").attr("ID");
	
	if (last_ID) {
		last_ID = last_ID.replace("tweet", "");
		var url = "http://search.twitter.com/search.json?q=" + query + "&since_id=" + last_ID + "&rpp=3&callback=?";
	} else {
		var url = "http://search.twitter.com/search.json?q=" + query + "&rpp=3&callback=?"; 
	}
	
	$.getJSON(url, function(json) {

		var results = '';
		$(json.results).each(function() {
			if (this.id == undefined) return;
			results += "<p class='tweet_result' id='tweet" + this.id + "'><a href='http://twitter.com/" + this.from_user + "' class='tweet_user'><img width='48' height='48' alt='" + this.from_user + "' src='" + this.profile_image_url + "' /></a>" + "<a href='http://twitter.com/" + this.from_user + "'>" + "@" + this.from_user + ":</a> " + linkify(this.text) + "<br/><span>" + relative_time(this.created_at) + "</span></p>";
		});
		$("#twitter_results").prepend(results);
	});

	$(".tweet_result:gt(20)").remove();
}

function linkify(text) {
    return text.replace(/(https?:\/\/[\w\-:;?&=+.%#\/]+)/gi, '<a href="$1">$1</a>')
               .replace(/(^|\W)@(\w+)/g, '$1<a href="http://twitter.com/$2">@$2</a>')
               .replace(/(^|\W)#(\w+)/g, '$1#<a href="http://search.twitter.com/search?q=%23$2">$2</a>');
}

function relative_time(time_value) { 
  var values = time_value.split(" "); 
  var parsed_date = new Date(); 
  parsed_date.setTime(Date.parse(time_value)); 
  var months = new Array('Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 
    'Set', 'Out', 'Nov', 'Dez'); 
  var postedAt = ''; 
  var m = parseInt(parsed_date.getMonth()); 
  var h = parseInt(parsed_date.getHours()); 
  var min = parseInt(parsed_date.getMinutes()); 
  if (min < 10) min =  "0" + min; 
  postedAt = h +":"+ min; 
  postedAt += ", "+ parsed_date.getDate(); 
  postedAt += " " + months[m]; 
  postedAt += " "+ parsed_date.getFullYear(); 
  
  return postedAt; 
}  
