String.prototype.linkify=function(){
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&;\?\/.=]+/g,function(m){
		return m.link(m);
	});
};
String.prototype.linkuser=function(){
	return this.replace(/[@]+[A-Za-z0-9-_]+/g,function(u){
		return u.link("http://twitter.com/"+u.replace("@",""));
	});
};
String.prototype.linktag=function(){
	return this.replace(/[]+[A-Za-z0-9-_]+/,function(t){
		return t;
	});
};
function fetch_tweets(elem){
	elem=$(elem);
	keyword=escape(elem.attr('title'));
	rpp=elem.attr('class').split(' ').slice(-1);
	var url="http://search.twitter.com/search.json?q="+keyword+"&rpp="+rpp+"&callback=?";
	$.getJSON(url,function(json){
		$(json.results).each(function(){
			var thetime=new Date(Date.parse(this.created_at));
			var tHour=thetime.getHours();
			if(tHour>12){
				tHour=tHour-12;
				tUnit='PM';
			}
			else{
				if(tHour==0){
					tHour=12;
				}
				tUnit='AM';
			};
			var tMin=thetime.getMinutes();
			if(tMin<10){
				tMin='0'+tMin;
			};
			var thetimestr=tHour+':'+tMin+' '+tUnit;
			var divstr='<div class="tweet"><div class="tweet-left"><a href="http://twitter.com/'+this.from_user+'" target="_blank"><img src="'+this.profile_image_url+'" /></a></div><div class="tweet-right"><p class="text"><a class="tweet-user" href="http://twitter.com/'+this.from_user+'" target="_blank">'+this.from_user+'</a>&nbsp;'+this.text.linkify().linkuser().linktag()+'<br /><span class="tweet-time">'+thetimestr+'</span></p></div><div class="clearfix"><!-- clear --></div></div>';
			elem.append(divstr);
		});
	});
	return(false);
}
$(document).ready(function(){
	$('.twitStream').each(function(){
		fetch_tweets(this);
	});
});