$(function() {

	//Open external links in a new tab
	$("a[rel=external]").attr('target', '_blank');
	
	//Remove IE6 image flicker
	try {document.execCommand('BackgroundImageCache', false, true);} catch(err) {}
	
	//Initialise fancyboxes
	if ($('a.fancybox').length) $('a.fancybox').fancybox();

	//Initialise carousel
	if ($('#carousel').length) initCarousel();
	
	//Initialise tweets
	if ($('ul.twitter').length) initTweets();

});

/*
=====================
Carousel
=====================
*/
var count, zIndex = 1, imageCount = 0, imagesLoadedCount = 0, delay = 5000, isRotating = false;

function initCarousel() {
	$($('#carouselNav a')[0]).addClass('active');
	$('#carouselNav a').click(function(e){
		isRotating = false;
		e.preventDefault();
		var index = $('#carouselNav a').index(this);
		$('#carouselNav a').removeClass('active');
		this.className = 'active';
		$('#carousel li').hide();
		$($('#carousel li')[index]).show();
	});
	count = $('#carousel li').length;
	if (count <= 1) return;
	imageCount = $('#carousel li img').length;
	$('#carousel li:first').css("opacity", "1");
	$('#carousel li img').each(function() {
		if (this.complete) imagesLoadedCount++;
		else {
			$(this).bind('load', function(){imagesLoadedCount++});
		}
	});
	initRotation();
}

function initRotation() {
	isRotating = true;
	if (imagesLoadedCount != imageCount) setTimeout("initRotation()", 500);
	else {
		$('#carousel li:not(li:first)').css("display", "none").css("opacity", "1");
		setTimeout("rotate(1)", delay);
	}
}
function rotate(i) {
	if (isRotating) {
		if (i == count) i = 0;
		$($('#carousel li')[i]).css("display", "none").css("z-index", zIndex).fadeIn(1200);
		setTimeout("$('#carouselNav a').removeClass('active');$($('#carouselNav a')[" + i + "]).addClass('active');", 600);
		zIndex++;
		setTimeout("rotate(" + (i+1) + ")", delay);
	}
}


var tweets;
var tweetDelay = 7000;

function initTweets() {
	tweets = $('ul.twitter li');
	tweets.first().css("display", "block");
	setTimeout("rotateTweets(0)", tweetDelay);
}

function rotateTweets(i) {
    // hide current
    $(tweets[i]).animate({top:-120}, 1000);
    // get next
    i++;
	if (i == tweets.length){
	    // if end goto first
	    i = 0;
	}
	// showNext
	$(tweets[i]).css("display", "block").css("top", 120).animate({top:0}, 1000);
    // runagain
	setTimeout("rotateTweets(" + (i) + ")", tweetDelay);
}
