function linkurl(string){
	return string.replace(/((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi, function(url){

		var href = url;
	
		if (!url.match('^https?:\/\/')) {
			href = 'http://' + url;
		}

	 	return '<a href="' + href + '">' + url + '</a>';

	});
}

function linkhashtags(text) {
	  return text.replace(/#([a-zA-Z0-9-_]+)/g, '<a href="http://twitter.com/#search?q=$1">#$1</a>');
} 

function linktwitterusers(text) {
     return text.replace(/@([a-zA-Z0-9-_]+)/g, '<a href="http://twitter.com/$1">@$1</a>');
} 

function twittercharlimit(avgcharsize) {
	teststring = "eeeetttaaaoooiii qwerty uiopas, dfghjkl zxcvbnm' WERTY UIOPAS. DFGHJKL' CVBNM 12345 67890.";
	$("#twitter_bar .tweet").html("loading latest tweet...<span style=\"display: none;\">" + teststring + "</span>");
	avgcharsize = $("#twitter_bar .tweet span").width() / 90;
	maxchar = Math.round($("#twitter_bar .tweetcontainer").width() / avgcharsize);
	return maxchar;
}

function displaytweet(twitterusername) {

	maxchar = twittercharlimit();

	JSONurl = "http://api.twitter.com/1/statuses/user_timeline/" + twitterusername + ".json?count=1&include_rts=1&callback=?";
	$.getJSON(JSONurl,function(tweet){
		
		tweetlink = "http://twitter.com/" + twitterusername + "/status/" + tweet[0].id_str;

		if ( tweet[0].text.length > maxchar) {
			maxchar = maxchar - 9;
			tweet = tweet[0].text.trim().substring(0, maxchar).split(" ").slice(0, -1).join(" ") + "...";
			tweet = linktwitterusers(linkhashtags(linkurl(tweet)));
			$("#twitter_bar .readmore").html("<a href=\"" + tweetlink + "\" target=\"_blank\">read more</a>");
			$("#twitter_bar .readmore").show();
		} else {
			tweet = linktwitterusers(linkhashtags(linkurl(tweet[0].text)));
		}
	
		$("#twitter_bar .tweet").html(tweet);
	});

}

$(document).ready(function() {
	displaytweet('clevermUK');
});

