function adjustBackdropToWindowSizeEvent() {
	$(window).bind( "resize", function() {
		adjustBackdropToWindowSize();
	} );
}

function adjustBackdropToWindowSize() {
	var backdrop, bd_width;
	// height of 1000 pixel width version
  var heights  = [ 754, 750, 750, 750, 750, 750, 800, 750, 750, 738, 667, 750, 750, 750, 750, 926, 562 ];
	var image_nr = $('#image_nr').val();
	var width    = parseInt( $('#wrapper').width(), 10 ); 
	var h1       = returnIntOrZero( $('.header_env').height() ); 
	var h2       = returnIntOrZero( $('.menu_env').height() ); 
	var h3       = returnIntOrZero( $('.strip').height() ); 
	var h4       = returnIntOrZero( $('.striplet').height() ); 
  var h5       = returnIntOrZero( $('.footer_env').height() );
  var h6       = returnIntOrZero( window.innerHeight ); 
  var height   = h6-(h1+h2+h3+h4+h5);
  var cdn_url  = "http://assets.montyrobertsuniversity.com.s3.amazonaws.com/backdrops/";
	if ( width <= 1000 && height <= heights[image_nr-1] ) {  
		backdrop = "url("+cdn_url+image_nr+"-1000.jpg)";
		bd_width = 1000;
	} else if ( width <= 1200 && height <= heights[image_nr-1] ) {  
		backdrop = "url("+cdn_url+image_nr+"-1200.jpg)";
		bd_width = 1200;
	} else if ( width <= 1400 && height <= heights[image_nr-1] ) {
		backdrop = "url("+cdn_url+image_nr+"-1400.jpg)";
		bd_width = 1400;
	} else {
		backdrop = "url("+cdn_url+image_nr+"-1800.jpg)";
		bd_width = 1800;
	}
	$('#backdrop').css( "background-image", backdrop );
	var xpos = ((width-bd_width)/2);
	var ypos = h1+h2+h3+h4;
	$('#backdrop').css( "background-position", xpos+"px " + ypos+"px" );
}

function returnIntOrZero( _str ) {
  var val = parseInt( _str, 10 );
  return( isNaN(val) ? 0 : val);
}

function backdropSelector() {
  $('#backdrop_select').change( function() {
		var token = encodeURIComponent($('#ajax_authenticity_token').attr("value"));
    var image_nr = $(this).find(':selected').attr("id");
    $.post( "/dashboard/backdrop", "&authenticity_token="+token+"&image_nr="+image_nr, null, "script" );
	 	$('#image_nr').attr( "value", image_nr );	 	
		adjustBackdropToWindowSize();
	} );
}
	
$(document).ready( function() {
	adjustBackdropToWindowSizeEvent();
	adjustBackdropToWindowSize();
	backdropSelector();
});
