/**
 * Twitter - Javascript
 * v1.1 - 2010-03-10
 *
 * Based on Monitter.
 *
 */

$.fn.reverse = Array.prototype.reverse;
String.prototype.wordWrap = function(m, b, c)
{
    var i, j, s, r = this.split("\n");
    if(m > 0) for(i in r)
    {
        for(s = r[i], r[i] = ""; s.length > m;
            j = c ? m : (j = s.substr(0, m).match(/\S*$/)).input.length - j[0].length
            || m,
            r[i] += s.substr(0, j) + ((s = s.substr(j)).length ? b : "")
        );
        r[i] += s;
    }
    return r.join("\n");
};

String.prototype.linkify = function () 
{
	return this.replace(/((https?\:\/\/|ftp\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi, function (m) 
	{
		return m.link(m);
	});
};
String.prototype.linkuser = function () 
{
	return this.replace(/[@]+[A-Za-z0-9-_]+/g, function (u) 
	{
		var username = u.replace("@", "");
		return u.link("http://twitter.com/" + username);
	});
};
String.prototype.linktag = function () 
{
	return this.replace(/[#]+[A-Za-z0-9-_]+/g, function (t) 
	{
		var tag = t.replace("#", "%23");
		return t.link("http://search.twitter.com/search?q=" + tag);
	});
};

function fetch_tweets(elem, found) 
{
	elem = $(elem);
	input = elem.attr('title');
	if (input != window.twitter['text-' + input]) 
	{
		window.twitter['last_id' + input] = 0;
		window.twitter['text-' + input] = input;
		if (!window.twitter['sb-tweet-count-' + input]) { window.twitter['sb-tweet-count-' + input] = 0; }
		window.twitter['limit'] = rpp;
	}
	var url = "http://search.twitter.com/search.json?q=from%3A" + input + "&rpp=" + rpp + "&since_id=" + window.twitter['last_id' + input] + "&callback=?";
	if (found == null) 
	{
		var found = 'false';
	}
	$.getJSON(url, function (json) 
	{
		$(json.results).reverse().each(function () 
		{
			if (json.results != '') 
			{
				if ($('div#sb-tweet-' + this.id, elem).length === 0) 
				{
					if (window.twitter['sb-tweet-count-' + input] >= window.twitter['limit']) 
					{
						$('div.sb-tweet:last').remove();
					}
					var image = '<img src="' + this.profile_image_url + '" alt="Twitter Image"></div>';
					var splitText = this.text.split(/(\b@[a-zA-Z0-9_]+)|(\b#[a-zA-Z0-9_]+)/).join(" ");
					var thedate = new Date(Date.parse(this.created_at)).format('mmm d "at" h:MM TT');
					var divstr = '<div id="sb-tweet-' + this.id + '" class="sb-tweet sb-tweet-count-' + window.twitter['sb-tweet-count-' + input] + '"><div class="sb-twitter-source-prefix"></div><div class="twitter-source-text"><p>' + splitText.linkify().linkuser().linktag() + '</p></div><div class="sb-twitter-source-suffix"></div><div class="sb-clear-both"><!-- CLEAR --></div><div class="sb-twitter-source-wrapper"><div class="sb-twitter-source-user"><p>posted by <strong><a href="http://twitter.com/' + this.from_user + '" title="Visit ' + this.from_user + ' on Twitter">' + this.from_user + '</a></strong> on ' + thedate + '</p></div><div class="sb-clear-both"><!-- CLEAR --></div></div></div>';
					window.twitter['last_id' + input] = this.id;
					elem.prepend(divstr);
					$('div#sb-tweet-' + this.id, elem).hide();
					$('div#sb-tweet-' + this.id, elem).fadeIn('slow');
					found = 'true';
					window.twitter['sb-tweet-count-' + input]++;
				}
			}
		});
		input = escape(input);
		rpp = 1;
		setTimeout(function () 
		{
			fetch_tweets(elem, found);
		},
		15000);
		if (found != 'true') 
		{
			if (($('div#sb-tweet-empty').text() != 'No recent tweets found.') && ($('div#sb-tweet-empty').text() == '')) 
			{
				var divstr = '<div id="sb-tweet-empty" class="sb-tweet"><h3>No recent tweets found.</h3></div>';
				elem.prepend(divstr);
				$('div#sb-tweet-empty', elem).fadeIn('slow');
			}
		}
	});
	return (false);
}
$(document).ready(function () 
{
	window.twitter = {};
	$('.sb-twitter-content').each(function (e) 
	{
		rpp = 5;
		fetch_tweets(this);
	});
});
