jQuery(document).ready(function($){
	
	var total_images = 7;
	var img_link = 'img/bg/';
	var img_container = $('#background-images');

	function fillViewport(theItem){

		var winWidth=$(window).width();
		var winHeight=$(window).height();
		var imageWidth=$(theItem).width();
		var imageHeight=$(theItem).height();
		var picHeight = imageHeight / imageWidth;
		var picWidth = imageWidth / imageHeight;

		if ((winHeight / winWidth) < picHeight) {
			$(theItem).css("width",winWidth);
			$(theItem).css("height",picHeight*winWidth);
		} else {
			$(theItem).css("height",winHeight);
			$(theItem).css("width",picWidth*winHeight);
		}
		
		$(theItem).css("margin-left",winWidth / 2 - $(theItem).width() / 2);
		$(theItem).css("margin-top",winHeight / 2 - $(theItem).height() / 2);
	}
	
	function operate(){
		var upcoming_img = $('img.upcoming', img_container);
		var current_img = $('img.current', img_container);
		var next_id = parseInt(upcoming_img.attr('id'))+1;
			next_id = next_id > total_images ? 1 : next_id;

		upcoming_img.ready(function(){
			if( current_img.length ){
				current_img.fadeOut(function(){
					fillViewport(upcoming_img);
					upcoming_img.fadeIn(function(){
						setTimeout(function(){ operate(); }, 4000);
						}).removeClass('upcoming').addClass('current');
						$(this).attr({
							id: next_id,
							src: img_link + next_id + '.jpg'
						});	
					}).removeClass('current').addClass('hide upcoming');
				}
		});
	}
	
	$('#1').ready(function(){
		$(window).resize();
		fillViewport('img.upcoming');
	   operate();

	});
	
	$(window).resize(function(){
	   fillViewport($('img', img_container));
	});
	
	$('#bio, #contact').click(function(e){
		e.preventDefault();
		clicked = $(this);
		target = $('#' + clicked.attr('id') + '-content');
		
		if( target.is(':visible') ) return false;
		if( $('#main section:visible').length ){
		   $('#main section:visible').fadeOut(function(){
			target.fadeIn();
		   });
		}else{
		   target.fadeIn();
		}
	});
});
