/*
 * jTwit jQuery Plugin
 * Copyright (c) 2008 Chris Scott (chris@iamzed.com)
 * Licensed under the MIT license.
 *
 */

(function($) {
	var opts,
		lastUpdated,
		lastStatusUpdate,
		$displayContainer,
		displayTimer;
	
	$.fn.jTwit = function(options) {

		// allow options
		opts = $.extend({}, $.fn.jTwit.defaults, options);
	
	
		$displayContainer = this;
		$displayContainer.addClass("jtwit-container");
		
		var firstRun = true;

		// update timer	
		$.timer(1, function(timer){
			displayTimer = timer;
			updateTweets();

			if (firstRun){
				firstRun = false;
				timer.reset(opts.updatefrequency);
			}
		});
		
		return this;
	};
	
	$.fn.jTwit.defaults = {
		username: 'chrisscott',
		showfriends: false,
		filterexpression: '',
		updatefrequency: 60000,
		maxtweets: 20,
	};
	
	$.jTwit = {
		
		stop : function(){
			displayTimer.stop();
		},
		
		start : function(){
			updateTweets();
			displayTimer.reset(opts.updatefrequency);
		}
	};



	function updateTweets(){
		
		(opts.showfriends) ? type = 'friends' : type = 'user';
		 
		$.getJSON("http://twitter.com/statuses/" + type + "_timeline/" + opts.username + ".json?callback=?",
			function(result){
				result;
				if( Date.parse(result[0].created_at) >= lastUpdated || lastUpdated == undefined )
				{
					firstRun = false;
					$displayContainer.text("");
					addTweet( result[0] );
				}
			}
		);
	}

	/*
	 * JavaScript Pretty Date
	 * Copyright (c) 2008 John Resig (jquery.com)
	 * Licensed under the MIT license.
	 *
	 * Updated by Chris Scott for normal date format
	 */

	function prettyDate(time){
		var date = new Date((time || "")),
			diff = (((new Date()).getTime() - date.getTime()) / 1000),
			day_diff = Math.floor(diff / 86400);

		if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
			return;

		return day_diff == 0 && (
				diff < 60 && "just now" ||
				diff < 120 && "1 minute ago" ||
				diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
				diff < 7200 && "1 hour ago" ||
				diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
			day_diff == 1 && "yesterday" ||
			day_diff < 7 && day_diff + " days ago" ||
			day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
	}
	
	function addTweet(tweetData){
		//console.log('addTweet adding : ' + tweetData.created_at + ' : ' + tweetData.text);

		// if filtering, check it
		if (opts.filterexpression != '' && !tweetData.text.match(opts.filterexpression)) return;

		$text = $('<div>')
			.addClass('jtwit-tweet-text')
			.html("&quot;"+tweetData.text+"&quot;");

		$userlink = $('<a>')
			.attr('href', 'http://twitter.com/' + tweetData.user.screen_name + '/')
			.append($text);

		$date = $('<div>')
			.addClass('jtwit-tweet-date')
			.html('<a href="http://twitter.com/' + tweetData.user.screen_name + '/statuses/' + tweetData.id + '">' + prettyDate(tweetData.created_at) + '</a>');

		$tweet = $('<div>')
			.append($userlink)
			.append($date)
			.addClass('jtwit-tweet')
			.hide();

		$displayContainer.prepend($tweet.fadeIn('slow'));

		lastUpdated = Date.parse(new Date().toUTCString());
		//console.log('addTweet setting lastUpdated to: ' + lastUpdated);

		// remove latest class from all
		$displayContainer.find('.jtwit-tweet-latest')
			.removeClass('jtwit-tweet-latest');

		// add class to latest tweet
		$displayContainer.find('.jtwit-tweet:first')
			.addClass('jtwit-tweet-latest');
	}

})(jQuery);