$(document).ready(function(){
	

	var $mainCarousel = $('#carousel .main .slider');
	//var bgImages      = [];

	// Get all backgrounds
/*	$mainCarousel.find('img').each(function(i){
		bgImages[i] = $(this).attr('src').replace('_teaser', '_bg');
	});*/
	
	$('#wrapper').after('<div id="bg"></div>');
	var $bg  = $('#bg');
	var i    = 0;
	
	// Load background images
	$(bgImages).each(function(i) {
		$('<img/>').hide().attr('src', bgImages[i]).load(function(){
			bgPos($(this));
			if(i == 0) { $(this).show(); }
		}).appendTo($bg);
		bgPos($bg.find('img:last'));
	});
	
	$bg.height($('#wrapper').height() - $('#end-wrapper').height());

	// Main carousel and background
	$mainCarousel.before('<a id="carousel-prev" href="#prev">Prev</a><a id="carousel-next" href="#next">Next</a><div id="carousel-nav"><div class="l"></div><div class="r"></div><div class="inner"></div></div>').cycle({ 
		fx:     'scrollHorz', 
		speed:   300, 
	    timeout: 5000, 
	    pager:  '#carousel-nav .inner',
	    next:   '#carousel-next',
	    prev:   '#carousel-prev',
	    pause:   true,
	    before: function(currSlideElement, nextSlideElement, options) {
	    	
	    	var speed = (options.speed);
	    	var currentSlide = $(currSlideElement).index();
	    	var nextSlide    = $(nextSlideElement).index();
	    	
	    	if(currentSlide != nextSlide) {
		    	$('#bg img').eq(currentSlide).fadeOut(speed);
				$('#bg img').eq(nextSlide).fadeIn(speed);
			}
			
			$('#carousel .sec .slider').cycle(nextSlide);
			
	    }
	});

	$('#carousel-nav').css('margin-left','-'+($('#carousel-nav').outerWidth()/2)+'px');
	
	// Sec carousel
	$('#carousel .sec .slider').cycle({
		fx:     'fade', 
		speed:   400,
		timeout: 0
	});
	
});

$(window).resize(function(){
	$('#bg').find('img').each(function(){
		bgPos($(this));
	});
});

function bgPos($img) {
	$img.css('left', ($('body').width()/2 - $img.width()/2)+'px');
}
