jQuery.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 = jQuery(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['count-' + input]) { window.twitter['count-' + input] = 0; }
		window.twitter['limit'] = 3;
	}
	var url = "http://search.twitter.com/search.json?q=" + input + "&rpp=" + rrp + "&since_id=" + window.twitter['last_id' + input] + "&callback=?";
	if (found == null) {
		var found = 'false';
	}
	jQuery.getJSON(url, function (json) {
		jQuery(json.results).reverse().each(function () {
			if (json.results != '') {
				if (jQuery('#tw' + this.id, elem).length === 0) {
					if (window.twitter['count-' + input] >= window.twitter['limit']) {
						jQuery('div.tweet:last').slideUp('slow', function() {
							jQuery(this).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));
					var thedatestr = thedate.getHours() + 'h' + thedate.getMinutes() + 'm';
					var divstr = '<div id="tw' + this.id + '" class="tweet count-' + window.twitter['count-' + input] + '"><div class="twitter-source-wrapper"><div class="twitter-source-icon"></div><div class="twitter-source-user"><p><strong><a href="http://twitter.com/' + this.from_user + '" title="Visit ' + this.from_user + ' on Twitter">' + this.from_user + '</a></strong> at ' + thedatestr + '</p></div><div class="clear-both"><!-- CLEAR --></div></div><p>' + splitText.linkify().linkuser().linktag() + '</p><div class="clear-both"><!-- CLEAR --></div></div>';
					window.twitter['last_id' + input] = this.id;
					elem.prepend(divstr);
					jQuery('#tw' + this.id, elem).hide();
					jQuery('#tw' + this.id, elem).fadeIn('slow');
					found = 'true';
					window.twitter['count-' + input]++;
				}
			}
		});
		input = escape(input);
		rrp = 1;
		setTimeout(function () {
			fetch_tweets(elem, found);
		},
		15000);
		if (found != 'true') {
			if ((jQuery('#twempty').text() != 'No recent tweets found.') && (jQuery('#twempty').text() == '')) {
				var divstr = '<div id="twempty" class="tweet"><h3>No recent tweets found.</h3></div>';
				elem.prepend(divstr);
				jQuery('#twempty', elem).fadeIn('slow');
			}
		}
	});
	return (false);
}
jQuery(document).ready(function () {
	window.twitter = {};
	jQuery('.twitter-content').each(function (e) {
		rrp = 3;
		fetch_tweets(this);
	});
});
