/*
 * jQuery Twitter Widget
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * Copyright (c) 2009 Anthony Ferguson
 * 
 * Usage:
 * 		Simply have have this in your HTML somewhere:
 *		<ul class="TwitterWidget" user="fergusweb" count="3"></ul>
 */


jQuery(document).ready(function($){
	$('ul.TwitterWidget').TweetList();
});


(function($) {
	// Primary Function
	$.fn.TweetList = function(options) {
		return this.each(function() {
			var ul = $(this);

			// JSON direct to twitter is having some problems.  Using local copy for now.  Unsure this this is a JSON issue, or a connection issue here.
			twitterJSON = 'http://twitter.com/statuses/user_timeline/'+ ul.attr('user') +'.json?count='+ ul.attr('count');
			
//			alert(twitterJSON);
//			twitterJSON = 'http://rabs/wordpress/wp-content/themes/thesis_16/custom/fergusweb.json';
//			twitterJSON = 'http://rabs/wordpress/wp-content/themes/thesis_16/custom/brendon.json';
			twitterJSON = 'http://www.fergusweb.net/wp-content/themes/Fergusweb/custom/fergusweb.json';
			
			// Is looking pretty good.  Need to auto-format links within (this).text (content).
			
			$.getJSON( twitterJSON, function(data) {
				$(data).each(function(i) {
					
					li = $('<li>').attr({ id: this.id }).appendTo( $(ul) );
					$('<span>').attr({ class:'tweet', innerHTML:this.text }).appendTo( $(li) );
					$('<a>').attr({ class:'time', href:'http://twitter.com/'+ ul.attr('user') +'/statuses/'+ this.id, innerHTML:FormatTime(this.created_at) }).appendTo( $(li) );
					
				});
			});
			
		});
	};
	// Time Formatting
	// This borrowed heavily from: http://twitter.com/javascripts/blogger.js
	// Must be a nicer way to do this? Surely?
	function FormatTime(Time) {
		timeVals = Time.split(' ');
		timeValue = timeVals[1]+' '+timeVals[2]+' '+timeVals[5]+' '+timeVals[3]; // Mon DD YYYY HH:ii:ss
		dateObj = Date.parse(timeValue);
		timeRel = new Date(); // Using local timezone
		timeDelta = parseInt((timeRel.getTime() - dateObj) / 1000)+(timeRel.getTimezoneOffset()*60);  // Get the number of seconds since tweet, in local timezone
		if (timeDelta < 60) {
			return 'less than a minute ago';
		} else if(timeDelta < 120) {
			return 'about a minute ago';
		} else if(timeDelta < (60*60)) {
			return (parseInt(timeDelta / 60)).toString() + ' minutes ago';
		} else if(timeDelta < (120*60)) {
			return 'about an hour ago';
		} else if(timeDelta < (24*60*60)) {
			return 'about ' + (parseInt(timeDelta / 3600)).toString() + ' hours ago';
		} else if(timeDelta < (48*60*60)) {
			return '1 day ago';
		} else {
			return (parseInt(timeDelta / 86400)).toString() + ' days ago';
		}
	}
})(jQuery);
