$(document).ready(function() {
	
	var link = "http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=bench_news&count=50&callback=?";
	
	var tweetsContainer = $('.twitter-feed');
	
	$.getJSON(link, function(tweetData) { 

			var $tweetList = $('<ul>');

			var length = tweetData.length < 50 ? tweetData.length : 50;

			for(var i = 0; i < length; i++) {

				var tweet = tweetData[i],
				$tweet = $('<li>');

				// Make the avatar, and append it to the $tweet
				$('<a/>', {
					href: 'http://twitter.com/' + tweet.text,
					html: ''
				}).appendTo($tweet);

				var text = linkify(tweet.text);
				// Make the tweet text, and append it to the $tweet
				$('<p>', {
					className: 'content',
					html: '<a href="http://twitter.com/' + tweet.user.screen_name + '">' + '</a> ' + text
				}).appendTo($tweet);

				// Append the $tweet to the $tweets
				$tweet.appendTo($tweetList);
			}

			// Append the $tweets to the DOM
			tweetsContainer.append($tweetList);

		});
	
	/*
	var link = "http://search.twitter.com/search.json?q=bench_news&count=5&callback=?";

	var tweetsContainer = $('.twitter-feed');

	$.getJSON(link, function(tweetData) { 

			var $tweetList = $('<ul>');

			var length = tweetData.results.length < 5 ? tweetData.results.length : 5;

			for(var i = 0; i < length; i++) {

				var tweet = tweetData.results[i],
				$tweet = $('<li>');

				// Make the avatar, and append it to the $tweet
				$('<a/>', {
					href: 'http://twitter.com/' + tweet.from_user,
					html: ''
				}).appendTo($tweet);

				// Make the tweet text, and append it to the $tweet
				$('<p>', {
					className: 'content',
					html: '<a href="http://twitter.com/' + tweet.from_user + '">' + '</a> ' + tweet.text
				}).appendTo($tweet);

				// Append the $tweet to the $tweets
				$tweet.appendTo($tweetList);
			}

			// Append the $tweets to the DOM
			tweetsContainer.append($tweetList);

		});
		*/

});

function linkify(text){
    if (text) {
        text = text.replace(
            /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
            function(url){
                var full_url = url;
                if (!full_url.match('^https?:\/\/')) {
                    full_url = 'http://' + full_url;
                }
                return '<a href="' + full_url + '">' + url + '</a>';
            }
        );
    }
    return text;
}
