(function($) {
	$(document).ready(function() {
		if ($('div.twitterBox').length > 0) {
			var countTweets = $('.twitterBox .twitterBoxInner ul li').length;
			prepareTweets();
			
			if (countTweets > 1) {
				startTweetInterval();
				$('.twitterBox').hover(
					function () {
						stopTweetInterval();
					},
					function () {
						startTweetInterval();
					}
				);
			}
		}
		
		
		if ($('#mainnavigation').length > 0) {
			var restWidth = $('#mainnavigation').width() - $('#mainnavigation ul').width();
			var countItems = $('#mainnavigation ul li').length;
			
			var addWidthPerItem = Math.floor(restWidth/countItems);
			
			$('#mainnavigation ul li a').each(function () {
				$(this).width($(this).width()+addWidthPerItem);
			});
		}
	});
	
	/* ---------------------------
	   Twitter
	--------------------------- */
	var twitterI;
	
	function startTweetInterval () {
		twitterI = setInterval(function () {
			var tweets = 		$('.twitterBox .twitterBoxInner ul');
			var currentTweet = 	$(tweets).find('li.active:first');
			var nextTweet = 	$(currentTweet).next();
			
			if ($(nextTweet).length <= 0) {
				nextTweet = $(tweets).find('li:first');
			}
	
			var index = $(nextTweet).index('.twitterBox .twitterBoxInner ul li');
			
			showTweet(index);
			
		}, 6000);
	}
	
	function stopTweetInterval() {
		clearInterval(twitterI);
	}
	
	function showTweet(index) {
		var tweets = $('.twitterBox .twitterBoxInner ul');
		var tweetToShow = $(tweets).find('li:eq('+index+')');
		
		$(tweets).find('li.active').slideUp(200, function () {
			$(this).removeClass('active');
			
			var label = $(tweetToShow).find('span.label').text();
			$('.twitterBox div.label').text(label);
			
			$('.twitterBox div.controls ul li.active').removeClass('active');
			$('.twitterBox div.controls ul li:eq('+index+')').addClass('active');
			
			$(tweetToShow).slideDown(200, function () {
				$(this).addClass('active');
			});
		});
	}
	
	function prepareTweets() {
		var tweetBox = $('.twitterBox');
		var firstTweet = $(tweetBox).find('.twitterBoxInner ul li:first');
		var countTweets = $(tweetBox).find('.twitterBoxInner ul li').length;
		
		$(firstTweet).addClass('active');
		var label = $(firstTweet).find('span.label').text();
		
		$(tweetBox).find('div.label').text(label);
		
		for (var i=0; i<countTweets; i++) {
			$('<li><a href="javascript:showTweet('+i+');">'+(i+1)+'</a></li>').insertBefore($(tweetBox).find('div.controls ul li:last'));
		}
		$(tweetBox).find('div.controls ul li:first').addClass('active');
		
	}
	
	
	
	
	$.loadShowreel = function (url) {
		Shadowbox.open({
			content: url+'?iframe=1',
			player: 'iframe',
			width: 875,
			height: 425
		});
		
		return false;
	}
})(jQuery);
