/*
* tweetable 1.6 - jQuery twitter feed generator plugin
*
* Copyright (c) 2009 Philip Beel (http://www.theodin.co.uk/)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* With modifications from Philipp Robbel (http://www.robbel.com/) and Patrick DW (stackoverflow)
* for IE compatibility.
*
* A little code borrowed from http://tweet.seaofclouds.com/
*
* Revision: $Id: jquery.tweetable.js 2011-01-06 $ 
*
*/

(function($){
	
	//define the tweetable plugin
	$.fn.tweet = function(options){

		//specify the plugins defauls
		var defaults = {
			limit:		10,					//number of tweets to show
			username:	'love_prezzo',		//@username tweets to display
			type: 		'user',				//either user or list
			list: 		''					//name of the list if type == list
		};

		//overwrite the defaults
		var options = $.extend(defaults, options);
		
		//loop through each instance
		return this.each(function() {
		
			//assign our initial vars
			var $tweetList = $(this);
			var api = "http://api.twitter.com/1/";
			
			if(options.type == 'list') api += "lists/statuses.json?slug=" + options.list + "&owner_screen_name=" + options.username;
			else api += "statuses/user_timeline.json?screen_name=" + options.username;
			
			api += "&count=20&include_rts=1&callback=?";
			
			//do a JSON request to twitters API
			$.ajax({
				'url':			api,
				'dataType':		'json',
				'success':		function(data){
	
					var realLimit = 1;
					
					$tweetList.find('.loading').fadeOut(200,function(){
					
						$(this).remove();
					
						//loop through twitters response
						$.each(data,function(i, item){
							
		                    if( item.in_reply_to_status_id_str === null && realLimit <= options.limit ){
		                    
		                    	realLimit++;
		                    	
								$tweetList.append('<p title="' + relative_time(item.created_at) + '">' + item.text.replace(/#(.*?)(\s|$)/g, '<span class="hash">#$1 </span>').replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, '<a href="$&">$&</a> ').replace(/@(.*?)(\:|\s|\(|\)|$)/g, '<a href="http://twitter.com/$1">@$1</a>$2') + '</p>');
								
		                    }
		                    
						});
						
						$('#twitter_feed p:first').show().css({
							'top':		36
						}).animate({
							'top':		0
						},600,'easeInOutExpo',function(){
							autoTweet();
						});
					
					});
				}

			});
			
			function autoTweet(){
				
				var t = $('#twitter_feed p').size();
				var c = 1;
				var d = 4;
				var timer;
				var hover = false;
				
				$('#twitter_feed').hover(function(){
					hover = true;
					clearTimeout(timer);
				},function(){
					hover = false;
					change();
				});
				
				function change(){
					
					c = c == t ? 1 : c + 1;
					
					timer = setTimeout(function(){
					
						clearTimeout(timer);
						
						if( !hover ){
						
							$('#twitter_feed p:eq(' + ( c - 1 ) + ')').show().css({
								'top':	36
							}).stop([]).animate({
								'top':	0
							},600,'easeInOutExpo').siblings('p').stop([]).animate({
								'top':	-36
							},600,'easeInOutExpo',function(){
								$(this).hide();
							});
						
						}
						
						change();
						
					}, d * 1000);
					
				}
				
				change();
				
			}
			
		});
		
		function parse_date(date_str){
			// The non-search twitter APIs return inconsistently-formatted dates, which Date.parse
			// cannot handle in IE. We therefore perform the following transformation:
			// "Wed Apr 29 08:53:31 +0000 2009" => "Wed, Apr 29 2009 08:53:31 +0000"
			return Date.parse(date_str.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
		}
		
		function relative_time(date){
		
			var date = parse_date(date);
		
			var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
			var delta = parseInt((relative_to.getTime() - date) / 1000, 10);
			var r = '';
			
			if (delta < 60) {
				r = delta + ' seconds ago';
			} else if(delta < 120) {
				r = 'a minute ago';
			} else if(delta < (45*60)) {
				r = (parseInt(delta / 60, 10)).toString() + ' minutes ago';
			} else if(delta < (2*60*60)) {
				r = 'an hour ago';
			} else if(delta < (24*60*60)) {
				r = '' + (parseInt(delta / 3600, 10)).toString() + ' hours ago';
			} else if(delta < (48*60*60)) {
				r = 'a day ago';
			} else {
				r = (parseInt(delta / 86400, 10)).toString() + ' days ago';
			}
			
			return 'about ' + r;
		}
		
	}

})(jQuery);
