var $twitWrapper;
var $speechbubble;
var $twitText;
var $twitWhen;

jQuery(function($)
{
	getTwitter();
});

function getTwitter()
{
	$twitWrapper = $('#twitWrapper');
	$speechbubble = $('#speechbubble');
	$twitText = $('#speechbubble p');
	$twitWhen = $('#tweetTime');
	
	if ($twitWrapper.size() > 0)
	{
		if ($.browser.msie)
		{
			$speechbubble.css({'background-image':'url(\'_img/speechbubble.gif\')'});
		}
		
		$speechbubble.animate(
		{
			opacity:0
		}, 0, 'linear').show();
		
		// Var to store Twitter feed response
		var twitText = 'Sorry, Twitter feed unavailable!  Please try again later.';
		try
		{
			// AJAX call to Twitter API, callback to eval json response
			var twitAJAX = $.getJSON(
				"http://search.twitter.com/search.json?from=chrisfrancis27&rpp=1&callback=?",
				function(data)
				{
					var twitJSON = eval(data);
					twitText = twitJSON.results[0].text.replace(/(ftp|http|https|file):\/\/[\S]+(\b|$)/gim, '<a href="$&" class="my_link" target="_blank">$&</a>');
					$twitText.html(twitText);
					
					// Do some maths to see how long ago tweet was made
					var unixNow = Math.round(new Date().getTime());
					var unixTwit = Math.round(new Date(twitJSON.results[0].created_at).getTime());
					
					if (unixNow - unixTwit <= 3600000)
					{
						var twitWhen = "- less than an hour ago";
					}
					else if (unixNow - unixTwit > 3600000 && unixNow - unixTwit <= 86400000)
					{
						var twitWhen = "- earlier today";
					}
					else if (unixNow - unixTwit > 86400000 && unixNow - unixTwit <= 604800000)
					{
						var twitWhen = "- earlier this week";
					}
					else
					{
						var twitWhen = "- more than a week ago";
					}
					
					$twitWhen.text(twitWhen);
				}
			);
		}
		catch(err)
		{
			//
		}
		
		var config = 
		{  
			over: twitHover,
			timeout: 200,
			out: twitUnHover
		};
		
		$twitWrapper.hoverIntent(config).click(twitClick);
	}
}

function twitHover()
{
 	$twitWrapper.animate(
 	{
		width:'410px',
		height:'120px'
	}, 0, 'linear', function()
		{
		 	$speechbubble.animate(
			{
				opacity:1
			}, 300, 'linear');
		}
	).css('cursor','pointer');
}

function twitUnHover()
{
	$speechbubble.animate(
	{
		opacity:0
	}, 300, 'linear', function()
		{
			$twitWrapper.css({'width':'19px','height':'25px'});
		}
	);
}

function twitClick()
{
	$('#twitLink').attr({'href':'http://twitter.com/chrisfrancis27','target':'_blank'});
}
