jQuery.noConflict();

// When the document is loaded (jQuery function)
jQuery(document).ready(function() {
	// Call the Twitter API to retrieve the last 10 tweets in JSON format for the pcpro Twitter account
	jQuery.getJSON("http://twitter.com/statuses/user_timeline.json?screen_name=primowebmedia&count=1&callback=?", function(tweetdata) {		
		// Grab a reference to the ul element which will display the tweets
		var tl = jQuery("#tweet-list");
		// For each item returned in tweetdata
		jQuery.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
//			tl.append("<li>&ldquo;" + urlToLink(tweet.text) + "&rdquo;&ndash; " + relTime(tweet.created_at) + "</li>");
			tl.append("<p>" + urlToLink(tweet.text) + "<span>" + relTime(tweet.created_at) + "</span></p>");
		});
	});
});

// Converts any links in text to their HTML <a href=""> equivalent
function urlToLink(text) {
  var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(exp,"<a href='$1' target='_blank'>$1</a>"); 
};

// Takes a time value and converts it to "from now" and then returns a relevant text interpretation of it
function relTime(time_value) {
	time_value = time_value.replace(/(\+[0-9]{4}\s)/ig,"");
	var parsed_date = Date.parse(time_value);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var timeago = parseInt((relative_to.getTime() - parsed_date) / 1000);			
	if (timeago < 60) return 'less than a minute ago';
	else if(timeago < 120) return 'about a minute ago';
	else if(timeago < (45*60)) return (parseInt(timeago / 60)).toString() + ' minutes ago';
	else if(timeago < (90*60)) return 'about an hour ago';
	else if(timeago < (24*60*60)) return 'about ' + (parseInt(timeago / 3600)).toString() + ' hours ago';
	else if(timeago < (48*60*60)) return '1 day ago';
	else return (parseInt(timeago / 86400)).toString() + ' days ago';
};
