$(document).ready(function(){
	$('.cABackgroundMenuItem').click(function(){
		sText = $(this).text();
		$('.cABackgroundMenuItem').removeClass('cABackgroundMenuItemActive');
		$(this).addClass('cABackgroundMenuItemActive');
		$('#iDivBackground img').attr('src', '/img/_bg/home_' + sText + '.jpg');

		resize_bg();

		window.clearInterval(iChangeBackground);
		iChangeBackground = window.setInterval('changeBackground()', 10000);
	});

	$("#iDivBackground img").load(function(){
		resize_bg();
	});

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

	resize_bg();
});

iChangeBackground = this.setInterval('changeBackground()', 10000);

function changeBackground(){
	sCurrentBackground = $('#iDivBackground img').attr('src');
	sCurrentBackground = sCurrentBackground.replace('/img/_bg/home_','');
	sCurrentBackground = sCurrentBackground.replace('.jpg','');

	if(sCurrentBackground == '6')
		sCurrentBackground = '1';
	else
		sCurrentBackground ++;

	$('#iDivBackground img').attr('src', '/img/_bg/home_' + sCurrentBackground + '.jpg');

	$('.cABackgroundMenuItem').removeClass('cABackgroundMenuItemActive');

	$('.cABackgroundMenuItem').each(function(){
		if($(this).text() == sCurrentBackground)
			$(this).addClass('cABackgroundMenuItemActive');
	});

	resize_bg();
}

function resize_bg(){
	$("#iDivBackground img").css("left","0");
	$("#iDivBackground img").css("top","107px");
	var doc_width = $(window).width();
	var doc_height = $(window).height() - 107;
	var image_width = $("#iDivBackground img").width();
	var image_height = $("#iDivBackground img").height();
	var image_ratio = image_width/image_height;
	var new_width = doc_width;
	var new_height = Math.round(new_width/image_ratio);
	var middleContainerWidth = $("#iDivMiddleContainer").width();
	var overlayContainerHeight = $("#iDivOverlayContainer").height();
	var middleContainerOffset = Math.round(doc_width/2) - Math.round(middleContainerWidth/2);
	var overlayContainerOffset = Math.round(doc_height/2) - Math.round(overlayContainerHeight/2);
	if(new_height<doc_height){
		new_height = doc_height;
		new_width = Math.round(new_height*image_ratio);
		var width_offset = Math.round((new_width-doc_width)/2);
		$("#iDivBackground img").css("left","-"+width_offset+"px");
	}else /*if(new_height>doc_height)*/{
		var height_offset = 107 - Math.round((new_height-doc_height)/2);
		$("#iDivBackground img").css("top",height_offset+"px");
	}

	$("#iDivBackground div").width(new_width);
	//$("#iDivMiddleContainer").width(new_width);
	$("#iDivMiddleContainer").css("left",middleContainerOffset+"px");
	$("#iDivOverlayContainer").css("top",overlayContainerOffset+"px");

	$("#iDivBackground img").height(new_height);
}
