(function( $ ){
	$.fn.twitterbox = function() {
		var timeoutInterval = 5000;
		var t = setTimeout("$('#twitterbutton_next').click();", timeoutInterval); 
		var autoAdvancing = true;
		var buttons = $('<div id="twitterbox_buttons" />');
		buttons.append('<a href="#" id="twitterbutton_prev">prev</a>');
		buttons.append('<a href="#" id="twitterbutton_pause">pause</a>');
		buttons.append('<a href="#" id="twitterbutton_next">next</a>');
		
		this.append(buttons);
		
		$('#twitterbutton_prev').click(function(e) {
			e.preventDefault();
			prevTweet();
		})
		
		$('#twitterbutton_pause').click(function(e) {
			e.preventDefault();
			toggleAutoAdvancing();
		})
		
		$('#twitterbutton_next').click(function(e) {
			e.preventDefault();		
			nextTweet();
		})
		
		function toggleAutoAdvancing() {
			autoAdvancing = !autoAdvancing;
			
			if (!autoAdvancing) {
				clearTimeout(t);
			} else {
				t = setTimeout("$('#twitterbutton_next').click();", timeoutInterval); 
			}
		}
		
		
		function stopAdvancing () {
			clearTimeout(t)
			autoAdvancing = false;
		}
		function prevTweet() {
			
			$('.widget_tweet:visible').fadeOut('normal', function() {
				if ($(this).prev('.widget_tweet').length) {
					$(this).prev('.widget_tweet').fadeIn('normal');
				} else {
					$('.widget_tweet:last').fadeIn('normal');
				}				
				stopAdvancing();
			});
			return false;
		}
		
		function nextTweet() {
			$('.widget_tweet:visible').fadeOut('normal', function() {
				if ($(this).next('.widget_tweet').length) {
					$(this).next('.widget_tweet').fadeIn('normal');
				} else {
					$('.widget_tweet:first').fadeIn('normal');
				}
				if (autoAdvancing) {
					t = setTimeout("$('#twitterbutton_next').click();", timeoutInterval); 
				}
			});
			return false;
		}
		
	};
})( jQuery );

