// Twitter feed - only called after DOM has loaded using $(document).ready - prevents page from hanging while waiting for twitter.com to deliver feed	

// When the document is loaded (jQuery function)
		$(document).ready(function() {
			// Call the Twitter API to retrieve the last 5 tweets in JSON format for the plasdinas Twitter account
			$.getJSON("http://twitter.com/statuses/user_timeline.json?screen_name=plasdinas&count=6&callback=?", function(tweetdata) {		
				// Grab a reference to the ul element which will display the tweets
				var tl = $("#twitter_update_list");
				
				
				// Remove div class .loading from DOM to remove "Feeds Loading" text
				$('#loading').remove();

				// 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
					tl.append("<li>&ldquo;" + urlToLink(tweet.text) + "&rdquo;&nbsp;" + "<h6>" + relative_time(tweet.created_at) + "</h6>" + "</li>");						
					
				});
			});
		});


// 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'>$1</a>"); 
		}

		// Takes a time value and converts it to "from now" and then returns a relevant text interpretation of it
		
		
		function relative_time(time_value) {
		  var values = time_value.split(" ");
		  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
		  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);
		  timeago = timeago + (relative_to.getTimezoneOffset() * 60);
		
		  if (timeago < 60) {
			return 'less than a minute ago';
		  } else if(timeago < 120) {
			return 'about a minute ago';
		  } else if(timeago < (60*60)) {
			return (parseInt(timeago / 60)).toString() + ' minutes ago';
		  } else if(timeago < (120*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 'yesterday';
		  } else {
			return (parseInt(timeago / 86400)).toString() + ' days ago';
		  }
		}
