/*
 * 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,
		sizetofit: false
	};
	
	$.jTwit = {
		
		stop : function(){
			displayTimer.stop();
		},
		
		start : function(){
			updateTweets();
			displayTimer.reset(opts.updatefrequency);
		},
		
		sizetofit : function(value){
			opts.sizetofit = value;
			if (value){
				$(window).bind("resize", singlePage);
				singlePage();
			}else{
				$(window).unbind("resize");
				$('.jtwit-tweet').show();
			}
		}
	};



	function updateTweets(){
		
		(opts.showfriends) ? type = 'friends' : type = 'user';
		 
		$.getJSON("http://www.jaejudy.com/tweetUpdate.php",
			function(result){
				//console.log('running');
				// reverse the array so oldest are first
				result.reverse();

				if (lastUpdated == undefined){	
					// first time so add all tweets
					addAllTweets(result);
				}else{
					// just add since last run
					addNewTweets(result);
				}

				if (opts.sizetofit){
					$(window).bind("resize", singlePage);
					singlePage();
				}
			}
		);
	}

	function singlePage(event){
		$('.jtwit-tweet').each(function(){
			$(this).show();
			($(this).offset().top + $(this).outerHeight({ margin: true }) <= $(window).height()) ? $(this).show() : $(this).hide();
		});
	}

	function addNewTweets(tweets){
		$(tweets).each(function(i){
			//console.log('addNewTweets checking: ' + Date.parse(tweets[i].created_at) + ' : ' + tweets[i].text);
			//console.log('addNewTweets checking against lastUpdated: ' + lastUpdated);
			if (Date.parse(tweets[i].created_at) >= lastUpdated){
				//console.log('tweet is new, calling addTweet');
				if (i < opts.maxtweets){
					addTweet(tweets[i]);
				}else{
					return;
				}
			}
		});
	}

	function addAllTweets(tweets){
		//console.log('addAllTweets called');
		lastUpdated = Date.parse(new Date().toUTCString());
		//console.log('addAllTweets setting lastUpdated to: ' + lastUpdated);
		$(tweets).each(function(i){
			//console.log(Date.parse(result[i].created_at));
			if (i >= tweets.length-opts.maxtweets){
				addTweet(tweets[i]);
			}else{
				return;
			}
		});
	}
	
	/*
	 * 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(tweetData.text);

		//$image = $('<img>')
		//	.addClass('jtwit-tweet-image')
		//	.attr('src', tweetData.user.profile_image_url.replace('/\\/g', ''));
		//
		//$userlink = $('<a>')
		//	.attr('href', 'http://twitter.com/' + tweetData.user.screen_name + '/')
		//	.append($image);
		//
		//$imagecontainer = $('<div>')
		//	.addClass('jtwit-tweet-image-container')
		//	.append($userlink);

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

		$tweet = $('<div>')
			.append($text)
			//.append($imagecontainer)
			.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);



