window.onresize = autoAdjustOnResize;
window.onload = autoAdjustOnResize;
$(document).ready(function() {
	//$('.imageautoadjust').load(function(){
		//autoAdjustOnResize();
	//});	
	
	$('.imageautoadjust').ready(function() {
		autoAdjustOnResize();
	});
});

function autoAdjustOnResize() {
	var bwidth = $('body').innerWidth();
	var bheight = $('body').innerHeight();
	var used_height =  $(".header").height() + $(".bottom_blocks").height();
	
	$('.parentautoadjust').css('height', (bheight-used_height) + 'px');
	
	adjustImageToFrame();
	
	water_right = (Math.abs(bwidth-$(".header .in").width())/2);
	
	$('.water').css('right', water_right+22 + 'px');
}

function adjustImageToFrame(){
	melement='.imageautoadjust';
	mparent='.parentautoadjust';
	msibling='.siblingautoadjust';
	$.each($(melement),function(){
		var siblingheight = $(this).siblings(msibling).height();
		//reset styles
		$(this).removeAttr('style');
		//measure both image and parent container
		var th = $(this).height();
		var tw = $(this).width();
		var ph = $(this).parents(mparent).height();
		var pw = $(this).parents(mparent).width();
		//register differences between width and height
		var dh = ph-th;
		var dw = pw-tw;
		
		if(dh>dw){
			$(this).css('height','100%');
			var adjust = (Math.abs($(this).width()-$(this).parents(mparent).width())/2);
			$(this).css('margin-left','-'+adjust+'px');
		}else{
			$(this).css('width','100%');
			var adjust = (Math.abs($(this).height()-$(this).parents(mparent).height())/2)+siblingheight;
			$(this).css('margin-top','-'+adjust+'px');
		}
	});
}

