$(document).ready(function() { 

	$(window).resize(function() {
		resize_background();	
	});

	$('div#login.user a').click(function() { 
		
		if ($(this).parent().hasClass('open')) {
			$('div#account_menu').fadeOut('fast');
			$(this).parent().removeClass('open');	
		} else {	
			$('div#account_menu').fadeIn('fast');
			$(this).parent().addClass('open');
		}
		
		return false;
		
	});


	
	var bg_cnt = $('#backgrounds ul li').length;

	if (bg_cnt>1) {
	
		show_background_controls();
	
		$('#backgrounds .prev a').click(function() { 
			rotate_background('prev');
			return false;
		});
	
		$('#backgrounds .next a').click(function() { 
			rotate_background('next');
			return false;
		});	
		
	}

	resize_background();
	
});



function show_background_controls() {

	$('#backgrounds .prev, #backgrounds .next').css('display','block');

}

function resize_background() { 
	
	var win_h = $(window).height();
	var win_w = $(window).width();
	var img_h = 800;
	var img_w = 1200;
	var win_aspect = win_w/win_h;
	var img_aspect = img_w/img_h;	
	if (win_aspect>=img_aspect) {
		var new_h = win_w/img_aspect;
		var new_w = win_w;				
	} else {
		var new_h = win_h;
		var new_w = win_h*img_aspect;			
	}	
	$("#backgrounds img").css("height",parseInt(new_h)+"px").css("width",parseInt(new_w)+"px");	
	
}



function rotate_background(direction) {

		var total = $('#backgrounds li').length;
		if ($('#backgrounds li.active').length>0) {
			var current = parseInt($('#backgrounds li.active').attr('class').replace("b_",""));
		} else {
			var current = 1;
		}
		var new_active = 0;
		
		if (direction == 'prev') {
			new_active = current - 1;
			if (new_active<1) {
				new_active = total;
			}
		
		} else {
			new_active = current + 1;
			if (new_active>total) {
				new_active = 1;
			}
		}
	
		// Queue
		$('#backgrounds li.b_'+new_active).addClass('queued');
		// Transition
		$('#backgrounds li.active').fadeOut('3s',function() { 
			$('#backgrounds li.active').removeClass('active').show();
			$('#backgrounds li.b_'+new_active).addClass('active').removeClass('queued');
		});

}
