function loadTwitterFeed( twitterAccount, twitterBox, noOfTweets, showTwitter, showFollowButton )
{
	if( twitterAccount != null )
	{
		twitterBox = $('div#' + twitterBox);
		getTweets( twitterAccount, twitterBox, noOfTweets, showTwitter, showFollowButton );
	}
}

function getTweets( twitterAccount, twitterBox, noOfTweets, showTwitter, showFollowButton )
{
	$.getJSON('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=' + twitterAccount + '&count=' + noOfTweets + '&callback=?',
			function(tweetdata)
			{
				strTw = "";
				if( showTwitter == true )
				{
					strTw += "<h3>" + twitterAccount + ":</h3>";
				}
				strTw += "<ul id=\"tweet-list\">\n";

				// For each item returned in tweetdata
				$.each( tweetdata, function( i,tweet )
				{
					// Append the info in li tags to the ul, converting any links to HTML <a href=.. code and convert the tweeted date
					// to a more readable Twitter format
//					sTweetDate =  Date.parse(tweet.created_at);
//					dTweetDate = new Date( sTweetDate );
//					tweet.displayDate = dTweetDate.getDate() + '-' + dTweetDate.getMonth() + '-' + dTweetDate.getFullYear() + '&nbsp;&nbsp;' + dTweetDate.getHours() + ':' + dTweetDate.getMinutes();
					strTw += "<li>" + urlToLink(tweet.text) + "<p class=\"tweettime\">" + parseTwitterDate( tweet.created_at ) + "</p></li>\n";
				});
				strTw += "</ul>\n";
				if( showFollowButton == true )
				{
					strTw += "<div><a href='http://twitter.com/#!/" + twitterAccount + "' target='_blank'><img src='images/twitter.png' /></a>&nbsp;<a href='http://twitter.com/#!/" + twitterAccount + "' target='_blank'>@" + twitterAccount + "</a></div>";
				}
				twitterBox.append(strTw);

				$('div#twitterFeed').show("slow");
			}
	);
}

function parseTwitterDate(text) {
	var newtext = text.replace(/(\+\S+) (.*)/, '$2 $1')
	var date = new Date(Date.parse(newtext)).toLocaleDateString();
	var time = new Date(Date.parse(newtext)).toLocaleTimeString();
	return date + ' • ' + time;
}

/**
 * Search text for url patterns and turn those to real links
 * @param text
 * @return string
 */
function urlToLink( text )
{
	// process links
	var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	text = text.replace( exp, "<a onclick=\"newWin(this.href);return false;\" href=\"$1\">$1</a>" );

	// process users
	var exp = /(^|\s)@(\w+)/g;
	text = text.replace( exp, "$1@<a onclick=\"newWin(this.href);return false;\" href=\"http://www.twitter.com/$2\">$2</a>" );

	// process hashtags
	var exp = /(^|\s)#(\w+)/g;
	text = text.replace( exp, "$1#<a onclick=\"newWin(this.href);return false;\" href=\"http://search.twitter.com/search?q=%23$2\">$2</a>" );

	return text
}

/**
 * Open a link in a new window
 * @param href
 * @return void
 */
function newWin( href )
{
	window.open( href, "_blank" );
}
