/**
 * 
 */
var TIMEOUT = 5000;
var SPEED = 500;

function goForward(){
	var index = $('#teaser-gallery-headlines > li').index($('#teaser-gallery-headlines > li.active-gallery-item'));
	var next = index + 1;

	if(index >= $('#teaser-gallery-headlines > li').size() - 1){
		next = 0;
	}
	
	$('div.teaser-gallery-box.active-gallery-item').stop(false, true).removeClass('active-gallery-item').fadeOut(SPEED);
	$('div.teaser-gallery-box').eq(next).stop(false, true).addClass('active-gallery-item').hide().fadeIn(SPEED);
	$('#teaser-gallery-headlines > li').eq(index).stop(false, true).removeClass('active-gallery-item').animate({width: '190px', backgroundPosition:'-55px bottom'}, SPEED);
	$('#teaser-gallery-headlines > li').eq(next).stop(false, true).addClass('active-gallery-item').animate({width: '245px', backgroundPosition:'0px bottom'}, SPEED);
}

$(function(){
	$('#teaser-gallery-headlines > li:first').css({width: '245px', backgroundPosition:'0px bottom'}).addClass('active-gallery-item');
	$('div.teaser-gallery-box').eq(0).addClass('active-gallery-item').show();
	
	if($('#teaser-gallery-headlines > li').length > 4){
		var item_height = $('#teaser-gallery-headlines').height() / $('#teaser-gallery-headlines > li').length;
		$('#teaser-gallery-headlines > li').css({height: (item_height - 12) + 'px', lineHeight: (item_height * 1.3) + 'px'});
		$('#teaser-gallery-headlines > li > a').css({lineHeight: (item_height * 1.3) + 'px'});
	}
	
	var autochange = window.setInterval("goForward()",TIMEOUT);
	var autochange_running = true;
	
	$('#teaser-gallery-headlines > li').each(function(){
		$(this).hover(function(){
			window.clearInterval(autochange);
			autochange = window.setInterval("goForward()",TIMEOUT);
			autochange_running = false;
			var index = $('#teaser-gallery-headlines > li').index(this);

			if(!$(this).hasClass('active-gallery-item')){
				$('div.teaser-gallery-box.active-gallery-item').stop(false, true).removeClass('active-gallery-item').fadeOut(SPEED);
				$('div.teaser-gallery-box').eq(index).stop(false, true).addClass('active-gallery-item').hide().fadeIn(SPEED);
				$('#teaser-gallery-headlines > li.active-gallery-item').stop(false, true).removeClass('active-gallery-item').animate({width: '190px', backgroundPosition:'-55px bottom'}, SPEED);
				$(this).stop(false, true).addClass('active-gallery-item').animate({width: '245px', backgroundPosition:'0px bottom'}, SPEED);
			}
		}, function(){
			if(!autochange_running){
				//autochange = window.setInterval("goForward()",TIMEOUT);
				autochange_running = true;
			}
		});
	});
	
});

