/*
 * Javascript Background Scale
 *
 * Author Max Mitschke
 */

/*
 * Reset Width and Height of the Image
 */
function reset()
{
	$('#scale img').css('height', 'auto');
	$('#scale img').css('width', 'auto');
}

/*
 * Detect Viewport and resize image
 */
function detect()
{
	var height;
	var width;
	var i = $('#scale img');
	var viewportheight = window.innerHeight ? window.innerHeight : $(window).height();
	var viewportwidth = window.innerWidth ? window.innerWidth : $(window).width();

	// Reset Height and Width on every detect
	reset();

	if(viewportheight > viewportwidth)
	{
		$('#scale img').css('height', '100%');

		width = i.width();

		if(width < viewportwidth)
		{
			reset();
			$('#scale img').css('width', '100%');
		}

	} else {
		$('#scale img').css('width', '100%');

		height = i.height();

		if(height < viewportheight)
		{
			reset();
			$('#scale img').css('height', '100%');
		}
	}
}

window.onload = function() {

	detect();

	setTimeout(function() { detect(); }, 500);

};

$(document).ready(function() {
	detect();

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