jQuery.fn.reverse = Array.prototype.reverse;
String.prototype.linkify = function() 
{
  return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(m) 
  {
  	m = m.link(m);
  	m = m.replace('href="','target="_blank" href="');
  	return m;
  });
};

String.prototype.linkuser = function() 
{
  return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(us) 
  {
    var username = us.replace("@","");
    
    us = us.link("http://twitter.com/"+username);
  	us = us.replace('href="','target="_blank" onclick="loadProfile(\''+username+'\');return(false);"  href="');
    return us;
  });
};

String.prototype.linktag = function() 
{
  return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) 
  {
    var tag = t.replace("#","%23");
    t = t.link("http://summize.com/search?q="+tag);
  	t = t.replace('href="','target="_blank" href="');
  	return t;
  });

}; 

function fetch_tweets(elem) {
	elem=$(elem);
	input=elem.attr('title');
	lang=elem.attr('lang');
	if(input!=window.utweet['text-'+input]){
		window.utweet['last_id'+input]=0;
		window.utweet['text-'+input]=input;
		window.utweet['count-'+input]=12;
		;}
	if(window.utweet['count-'+input]>10)
	var url="http://search.twitter.com/search.json?"+lang+"="+input+"&rpp="+rrp+"&since_id="+window.utweet['last_id'+input]+"&callback=?";$.getJSON(url,function(json){
//		$('div.tweet_body:gt('+window.utweet['limit']+')',elem).each(function(){
//			$(this).fadeOut('slow')});
		$(json.results).reverse().each(function(){
				if($('#tw'+this.id,elem).length==0){
					window.utweet['count-'+input]++;
					var thedate=new Date(Date.parse(this.created_at));
					var thedatestr=thedate.getHours()+':'+thedate.getMinutes();
					var divstr='<div id="tw'+this.id+'" class="tweet_body"><div class="profile_image"><a href="http://twitter.com/'+this.from_user+'" target="_blank"><img width="48" height="48" src="'+this.profile_image_url+'" ></a></div><div class="content"><strong><a href="http://twitter.com/'+this.from_user+'" target="_blank">'+this.from_user+'</a></strong>&nbsp;'+this.text.linkify().linkuser().linktag()+'&nbsp;<span class="hour">('+thedatestr+')</span></div></div>';
					window.utweet['last_id'+input]=this.id;
					elem.prepend(divstr);
					$('#tw'+this.id,elem).hide();
					$('#tw'+this.id+' img',elem).hide();
					$('#tw'+this.id+' img',elem).fadeIn(1000);
					$('#tw'+this.id,elem).fadeIn('slow');}});
		input=escape(input);
		rrp=1;
		setTimeout(function(){
			fetch_tweets(elem)},5000);
		});
	return(false)
;}

$(document).ready(function(){
	window.utweet={};
	$('.containers').each(function(e){
		rrp=20;
		fetch_tweets(this);
	});
});
