var refreshRate = 5000;
var streamTimerID;
var tweetboxsize = 'small';
var paused = false;
var OAuthAccounts = new Array();

jQuery.fn.reverse = Array.prototype.reverse;

function linktext(text)
{
	text = text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, 
		function(href)
		{
			return '<a href="'+href+'" target="_blank" title="view this link">'+href+'</a>';
		}
	);
	
	text = text.replace(/[@]+[A-Za-z0-9-_]+/g, 
		function(user)
		{
			user = user.replace("@","");
			return '@<a href="http://twitter.com/'+user+'" target="_blank" title="view @'+user+'\'s profile">'+user+'</a>';
		}
	);
	
	text = text.replace(/[#]+[A-Za-z0-9-_]+/g, 
		function(tag)
		{
			tag = tag.replace("#", "");
			return '#<a href="http://wthashtag.com/'+tag.toLowerCase()+'" target="_blank" title="More on #'+tag+'">'+tag+'</a>';
		}
	);
	
	return text;
};
		
function fetch_tweets(elem)
{
	if(paused)
	{
		$('#tweets .time').each(
			function()
			{
				var ots = $(this).attr('id');
				$(this).html( getRelativeTimestamp(ots) );
			}
		);
		streamTimerID = setTimeout( function() { fetch_tweets(elem) }, refreshRate);
		return;
	}
	
	elem = $(elem);
	input = elem.attr('title');
	lang = elem.attr('lang');
	if(input != window.wthstream['text-'+input])
	{
		window.wthstream['last_id'+input] = 0;
		window.wthstream['text-'+input] = input;
		window.wthstream['count-'+input] = 12;
	}
	
	var url = "http://search.twitter.com/search.json?q="+input+"&lang="+lang+"&rpp="+rrp+"&since_id="+window.wthstream['last_id'+input]+"&callback=?";
	
	$.getJSON(url, function(json)
	{
		$('div.tweet:gt('+window.wthstream['limit']+')', elem).each(function()
		{
			$(this).slideDown(500);
		});
		
		$(json.results).reverse().each(function()
		{
			if($('#tw'+this.id, elem).length == 0)
			{
				window.wthstream['count-'+input]++;
				var timestamp = new Date( Date.parse(this.created_at) ).getTime();
				var thedatestr = getRelativeTimestamp( timestamp );
//				var thesource = this.source.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"');
				
				var reply = '@'+this.from_user+' ';
				var retweet = 'RT '+this.from_user+': '+this.text;
				var direct = 'd '+this.from_user+' ';
				var twclass = "tweet";
				
				for(var i=0; i < OAuthAccounts.length; i++)
				{
					var pattern = new RegExp("@"+OAuthAccounts[i], 'gi');
					if( this.text.search(pattern) > 0 || this.to_user == OAuthAccounts[i])
					{
						twclass += " reply";
						break;
					}
				}
				
				var dstr = '';
				dstr += '<div id="tw'+this.id+'" class="'+twclass+'">'+"\n";
				dstr += '	<img width="48" height="48" src="'+this.profile_image_url+'" title="@'+this.from_user+'" class="twavatar" id="twavatar-'+this.id+'" />'+"\n";
				dstr += '	<div class="followOverlay" id="fo-'+this.id+'"><a href="javascript:;">follow</a></div>'+"\n";
				dstr += '	<p class="text">'+"\n";
				dstr += '		<b><a href="http://twitter.com/'+this.from_user+'" title="View profile" target="_blank">'+this.from_user+'</a></b>&nbsp;'+"\n";
				dstr += '		'+linktext(this.text)+'<br />';
				dstr += '		<span class="tweetmeta">' + "\n";
//				dstr += '			<span class="time" id="'+timestamp+'">'+thedatestr+'</span> from '+thesource+'&nbsp;&nbsp;&nbsp;'+"\n";
				dstr += '			<span class="time" id="'+timestamp+'">'+thedatestr+'</span>&nbsp;&nbsp;&nbsp;'+"\n";
				dstr += '			<a onclick="twitterAction(\''+reply+'\', \''+this.id+'\');" title="Reply to @'+this.from_user+'">Reply</a>&nbsp;';
				dstr += '			<a onclick="twitterAction(\''+retweet+'\', \''+this.id+'\');" title="Retweet this">Retweet</a>&nbsp;';
				dstr += '			<a href="http://twitter.com/'+this.from_user+'/statuses/'+this.id+'" title="View this tweet" target="_blank">View Tweet</a>';
				dstr += '		</span>' + "\n";
				dstr += '	</p>'+"\n";
				dstr += '</div>';
				
				window.wthstream['last_id'+input] = this.id;
				elem.prepend(dstr);
				
				$('#tw'+this.id, elem).hide();
				$('#tw'+this.id, elem).slideDown(500);
			}
			
		});
		
		$('#tweets .time').each(
			function()
			{
				var ots = $(this).attr('id');
				$(this).html( getRelativeTimestamp(ots) );
			}
		);
		
		input = escape(input);
		(tweetboxsize == "small") ? rrp = 6 : rrp = 12;
		streamTimerID = setTimeout( function() { fetch_tweets(elem) }, refreshRate);
	});
	
	return(false);
}

function pauseStream()
{
	paused = true;
	
	$('#pauseStream').hide();
	$('#resumeStream').show();
}

function resumeStream()
{
	paused = false;
	fetch_tweets($('.wthstream'));
	
	$('#resumeStream').hide();
	$('#pauseStream').show();
}

function tweetBox(size)
{
	if(size == "large")
	{
		$('#tweets').css({height: 900});
		$('#moretweets').hide();
		$('#lesstweets').show();
	}
	else if(size == "small")
	{
		$('#tweets').css({height: 450});
		$('#lesstweets').hide();
		$('#moretweets').show();
	}
}

$(document).ready(function() {
	window.wthstream = {};
	$('.wthstream').each(function(e) { rrp = 12; fetch_tweets(this); });
/*	
	$('.twavatar').hover(
		function()
		{
			alert("hover over");
			$('#fo-'+this.id.replace("twavatar-", "")).show();
		},
		function()
		{
			alert("hover out");
			$('#fo-'+this.id.replace("twavatar-", "")).hide();
		}
	);
*/
});

function getRelativeTimestamp(thedate)
{
	var now = Number(new Date().getTime()) + 60000; // not sure why there's a discrepancy, but we have to correct it
	var diff = Math.round( (now - thedate) / 1000 );
	
	if(diff <= 60)
		return diff + " seconds ago";

	var mins = Math.round(diff / 60);
	if(mins < 60)
	{
		if(mins == 1)	return "1 minute ago";
		else			return mins + " minutes ago";
	}
	
	var hours = Math.round(mins / 60);
	if(hours < 24)
	{
		if(hours == 1)	return "1 hour ago";
		else			return hours + " hours ago";
	}
	
	var days = Math.round(hours / 24);
	if(days == 1)	return "1 day ago";
	else			return days + " days ago";
}