var fading = false;
var teaserHover = false;
var maxTeasers = 5;

function teaserSwitch(id, skipLoaded) {

	if (loadedTeasers.length != maxTeasers) {
		return false;
	}

	if (fading) {
		return false;
	}

	$('.teaser-switch .switch').removeClass('act');
	$('#switch_'+id).addClass('act');

	var duration = 500;
	
	var target = $('#teaser_' + id);
	var current = $('.teaser.act');

	fading = true;
	
	$(current).fadeOut(duration, function() {
		$(current).removeClass('act');
	});

	if ($(target).hasClass('act')) {
		return false;
	}

	$(target).fadeIn(duration, function() {
		$(target).addClass('act');
		fading = false;
	});
	

};

function teaserTimer() {
	setTimeout(function(){
		if (!teaserHover) {
			var current = $('.teaser-switch .switch.act').attr('id').substr(-1)*1;
			var next = (current >= maxTeasers) ? 1 : (current+1);
			teaserSwitch(next);
		}
		teaserTimer();
	}, 5000);
}

var loadedTeasers = [];
function preloadTeasers() {
	$([
		'/img/teaser/1.png',
		'/img/teaser/2.png',
		'/img/teaser/3.png',
		'/img/teaser/4old.png',
		'/img/teaser/5old.png'
//		'/img/teaser/6.png'
	]).each(function(i, val) {
		var img = new Image();
		img.src = val;
		$(img).bind('load', function(){
			loadedTeasers.push(this.src);
		})
	});
}

$(document).ready(function(){
	preloadTeasers();

	$('.teasers').hover(function(){
		teaserHover = true;
	},function(){
		teaserHover = false;
	});

	$('.teaser-switch .switch').click( function(){
		var link = this;
		if ($(link).hasClass('act')) {
			return;
		}
		teaserSwitch($(link).html());
	});

	$('.teaser-switch .switch-left').click(function(){
		var curId = $('.teaser-switch .switch.act').html();
		if (curId > 1) {
			curId--;
		}
		else {
			curId = maxTeasers;
		}
		teaserSwitch(curId);
	});

	$('.teaser-switch .switch-right').click(function(){
		var curId = $('.teaser-switch .switch.act').html();
		if (curId < maxTeasers) {
			curId++;
		}
		else {
			curId = 1;
		}
		teaserSwitch(curId);
	});

//	teaserSwitch(1, true);
	teaserTimer();
});

