	var fresh_tweets = [];
	var $twitterwall = $("#twitterwall");
	var tweet_inserter = false;
	var db_poller = false;
	var $tweet_number = $('#total_tweets');
	
	/**
	 * The main function. Starts the twitterwall
	 *
	 * @param $start_id int The row id to start getting tweets from
	 * @return null
	 */
	function twitterwall()
	{		
		$(window).load(function() 
		{			
			// Query the DB and get the fresh tweets
			poll_db();
			
			// Call out a random tweet speech bubble
			shout();
			
			// Start the random tweet speech bubble timer
			shouter = setInterval("shout()", 6000);
		});
	}
	
	/**
	 * Polls the database for new tweets and adds them to the
	 * stack of fresh tweet we can feed from.
	 *
	 * @param $start_id int The row id to start getting tweets from
	 * @return null
	 */
	function poll_db()
	{				
		$.ajax({
			url: "twitterwall.php",
			type: "GET",
			dataType: "json",
			data: $.param({start_id:start_id}),
			success: function(tweets) 
			{
				fresh_tweets = fresh_tweets.concat(tweets);
				
				if(tweets[tweets.length-1] != undefined)
				{
					start_id = tweets[tweets.length-1]["id"];
				}
				
				if(fresh_tweets.length != 0)
				{
					insert_tweets();
				}
				else
				{
					setTimeout("poll_db()", 20000);
				}
			}
		});
		
	}
	
	/**
	 * Adds commas to large numbers
	 *
	 * @param $number string
	 * @return string
	 */
	function addCommas(number)
	{
		number += '';
		x = number.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	}
	
	/**
	 * Updates the total number of tweets on the page
	 *
	 * @param $number string The new number
	 * @return null
	 */
	function update_total($number)
	{
		$tweet_number.html(addCommas($number));
	}
	
	/**
	* Removes the last tweet on the page
	*/
	function remove_last_tweet()
	{
		$('.avatar:last-child').remove();
	}
	
	/**
	 * Inserts tweets from the fresh tweets array
	 *
	 * @return null
	 */
	function insert_tweets()
	{
		// Get the first tweet from the pile
		tweet = fresh_tweets.shift();  

		$img = $("<img />")
			.error(function()
			{
				$(this).attr('src','/images/default.png');
			})
			.load(function()
			{
				$(this)
					.prependTo($twitterwall)
					.wrap("<div class='avatar'></div>")
					.wrap("<a href='"+tweet['link']+"' title='"+tweet['title']+"'></a>")
					.height('1px').width('1px')
					.css({'margin-left':'24px','margin-top':'24px'})
					.animate(
						{height:'48px', width:'48px', marginLeft:0, marginTop:0}, 
						'fast',
						'linear',
						function()
						{
							// Add it to the count
							update_total(tweet['id']);
															
							// Chop off the last
							if($twitterwall.children('.avatar').size() > max_tweets) 
							{
								remove_last_tweet();
							}
							
							// Clean up
							if(fresh_tweets.length > 100)
							{
								fresh_tweets = [];
							}
							
							if(fresh_tweets.length == 0)
							{
								start_id = tweet["id"];
								poll_db();
							}
							else
							{
								setTimeout("insert_tweets()", 2000);
							}
						}
					);				
			})
			.attr({
				'src': tweet["avatar"],
				'width': 48,
				'height': 48,
				'title': tweet['author_name'],
				'rel': 'external'
			});	
	}
	
	/**
	 * Picks a random tweet and shows the speech bubble
	 *
	 * @return null
	 */
	function shout()
	{
		$('.tweet').parent().removeClass('active');
		$('.tweet').remove();
		
		random_number = Math.floor(Math.random() * $twitterwall.children('.avatar').size());
		
		safe_x = $(window).width() - 950;
		safe_y = $(window).height() - 144;
				
		$avatar = $('.avatar').eq(random_number);
		
		avatar_pos = $avatar.offset();

		if(avatar_pos.left < safe_x && avatar_pos.top < safe_y )
		{
			author_name = $avatar.children('a').children('img').attr('title');
			title = $avatar.children('a').attr('title');
	
			$img = $avatar
					.append("<div class='tweet' style='display:none'><div class='tweet-top'></div><div class='tweet-mid'><a href='http://twitter.com/"+author_name+"'>@"+author_name+"</a>&nbsp;said:<br/>"+title+"</div><div class='tweet-btm'></div></div>")
					.addClass('active')
					.children('.tweet')
				
			if ($.support.opacity == false)
			{
				$img.show();
			}
			else
			{
				$img.fadeIn('slow');
			}
			
		}
		else if($(window).width() > 900 && $(window).height() > 300)
		{
			shout();
		}
		
		$img = "";
		$avatar = "";
		avatar_pos = "";
	}