$(function(){
	
	// twitter feeds
	$('#tweets').each(function(i, item){
		
		var container = $( item ).find( '.tweets-feed' ).delegate('a', 'click', function(e){ window.open( e.currentTarget.href ); return false; }),
			loading   = $( '<p class="tweets-loading">Chargement en cours...</p>' ),
			template  = $( item ).find( '#tweet-template').html(),
			patterns  = [/\%from_user/, /\%post/, /\%time/, /\%source/],
			count     = $( item ).data( 'count' ) ? $( item ).data( 'count' ) : 1 ,

			format_post_link = function( post ){
							
				var patterns = 	[
									// match twitter user
									/@(\w+)/gi,

									// match #tags
									/(?:^| )[\#]+([\w\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u00ff\u0600-\u06ff]+)/gi,

									// match url
									/\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/gi
								];

				var replacements = [				
									' <a href="http://twitter.com/$1" class="twitter-user">@$1</a> ',
									' <a href="http://twitter.com/#search?q=%23$1" class="twitter-tags">#$1</a> ',
									' <a href="$1" class="twitter-link">$1</a> '
								   ];

				return preg_replace( patterns, replacements, post );
			},
			get_time_elapsed = function( time ){
				
				var now  	= new Date();
				var time 	= new Date( time );
				var diff 	= now.getTime() - time.getTime();
				var minutes = diff / 1000 / 60 >> 0;
				var hours 	= minutes / 60 >> 0;
				var days    = hours / 24 >> 0;

				if( hours === 0 ) return minutes > 1 ? minutes + ' minutes' : minutes + ' minute';
				else if( hours < 24 ) return hours > 1 ? hours + ' heures' : hours + ' heure';
				else return days > 1 ? days + ' jours' : days + ' jour';
			},
			preg_replace     = function( regexp, replacement, str ){
				var result = str;

				if( regexp instanceof Array && replacement instanceof Array )
				{
					var n = regexp.length;
					while( --n >= 0 ) result = result.replace( regexp[n], replacement[n] );
				}
				else result = result.replace( regexp, replacement );

				return result;
			};
			
		container.append( loading );
		$.getJSON('//search.twitter.com/search.json?from=ebhoren&rpp='+count+'&callback=?', function( data ){
			
			var posts = data.results, post, node, html, 
				shiv = typeof innerShiv === 'function',
				i = 0, n = posts.length;
			
			if( n == 0 ) loading.html('Aucun tweet');
			else loading.remove();
			
			for(; i<n; i++)
			{
				post = posts[ i ];
				html = preg_replace(patterns, 
									[
										post.from_user,
										format_post_link(post.text), 
										get_time_elapsed(post.created_at)
									], 
									template);
				
				if( shiv ) node = $( innerShiv(html, false) );
				else node = $( html );
				
				container.append( node );
			};
			
		});
	});
	
});
