
/*
 * Using this URL:
 * http://api.twitter.com/1/statuses/user_timeline.json?include_rts=true&user_id=77067433&count=1&
 * And this API:
 * https://dev.twitter.com/docs/api/1/get/statuses/user_timeline
 * 
 * From: 
 * http://stackoverflow.com/questions/6549223/javascript-code-to-display-twitter-created-at-as-xxxx-ago
 */
$(document).ready(function() {
	function parseTwitterDate(tdate) {
	    var system_date = new Date(Date.parse(tdate));
	    var user_date = new Date();
	    if (K.ie) {
	        system_date = Date.parse(tdate.replace(/( \+)/, ' UTC$1'))
	    }
	    var diff = Math.floor((user_date - system_date) / 1000);
	    if (diff <= 1) {return "just now";}
	    if (diff < 20) {return diff + " seconds ago";}
	    if (diff < 40) {return "half a minute ago";}
	    if (diff < 60) {return "less than a minute ago";}
	    if (diff <= 90) {return "one minute ago";}
	    if (diff <= 3540) {return Math.round(diff / 60) + " minutes ago";}
	    if (diff <= 5400) {return "1 hour ago";}
	    if (diff <= 86400) {return Math.round(diff / 3600) + " hours ago";}
	    if (diff <= 129600) {return "1 day ago";}
	    if (diff < 604800) {return Math.round(diff / 86400) + " days ago";}
	    if (diff <= 777600) {return "1 week ago";}
	    return "on " + system_date;
	}
	
	// from http://widgets.twimg.com/j/1/widget.js
	var K = function () {
	    var a = navigator.userAgent;
	    return {
	        ie: a.match(/MSIE\s([^;]*)/)
	    }
	}();

	$.getJSON(
		"http://api.twitter.com/1/statuses/user_timeline.json?include_rts=true&user_id=77067433&count=1&include_entities=false&contributor_details=false&callback=?",
		function(data) {
			$.each(data, function(i,item) {
				dateInfo = parseTwitterDate(item.created_at);
				linkPattern = /(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
				replaceText = item.text.replace(linkPattern, "<a href=\"$1\">$1</a>");
				tweetHTML = '<a href="http://twitter.com/#!/rbnzmuseum"><b>@RBNZMuseum:</b></a><br/><br/>' + replaceText + '<br /><br/><u><a href="http://twitter.com/#!/rbnzmuseum/status/' + item.id_str + '" target="_blank">' + dateInfo + '</a></u>';
				$("#tweetcontent").html(tweetHTML);
			});
		});
});
