var artifex = {};

artifex.layout = (function($) {
	/* Hintergrund */
	var $bg;
	var $bg_wrapper;
	var $page;
	var img_width;
	var img_height;
	var resize_possible = false;
	var force_scale = true;
	var orientation = 'top';
	
	function start_resize()
	{
		if (resize_possible) return;
		$bg_wrapper.css('overflow', 'hidden');
		$bg.css('width', 'auto');
		$bg.css('min-width', '0px');
		img_width = $bg.width();
		img_height = $bg.height();
		/*
		if (img_width != 1600)
		{
			img_height = img_height * (1600 / img_width);
			img_width = 1600;
		}
		*/
		$bg.css('width', '100%');
		if (img_height && img_width)
		{
			resize_possible = true;
			handle_resize();
		}
	};
	
	function handle_resize()
	{
		if (!resize_possible) return;
		var screen_width = $(document).width();
		var screen_height = $(window).height();
		var bg_height = $bg_wrapper.height();
		var cur_width;
		var cur_height;
		
		if (img_width/img_height > screen_width/screen_height)
		{
			if (force_scale || img_height < screen_height)
			{
				cur_width = (screen_height / img_height) * img_width;
				cur_height = screen_height;
			}
			else
			{
				cur_width = img_width;
				cur_height = img_height;
			}
		}
		else
		{
			if (force_scale || img_width < screen_width)
			{
				cur_width = screen_width;
				cur_height = (screen_width / img_width) * img_height;
			}
			else
			{
				cur_width = img_width;
				cur_height = img_height;
			}
		}
		$bg_wrapper.height(screen_height);
		if (cur_width == img_width && cur_height == img_height)
		{
			$bg.css({
				width: cur_width + 'px',
				height: cur_height + 'px',
				top: orientation == 'top' ? '0px' : (orientation == 'center' ? '50%' : 'auto'),
				bottom: orientation == 'bottom' ? '0px' : 'auto',
				left: '50%',
				marginTop: orientation == 'center' ? ('-' + (cur_height / 2) + 'px') : '0px',
				marginLeft: '-' + (cur_width / 2) + 'px'
			});
		}
		else
		{
			$bg.css({
				width: cur_width + 'px',
				height: cur_height + 'px',
				top: orientation == 'top' ? '0px' : (orientation == 'center' ? '50%' : 'auto'),
				bottom: orientation == 'bottom' ? '0px' : 'auto',
				left: '-'  + ((cur_width - screen_width) / 2) + 'px',
				marginTop: orientation == 'center' ? ('-' + (cur_height / 2) + 'px') : '0px',
				marginLeft: '0px'
			});
		}
	};
	
	function init()
	{
		$bg_wrapper = $('#background-image');
		if ($bg_wrapper.hasClass('bottom'))
			orientation = 'bottom';
		if ($bg_wrapper.hasClass('center'))
			orientation = 'center';
		$bg = $bg_wrapper.find('img');
		$page = $('#page-wrapper');
		if ($bg.width() && $bg.height())
			start_resize();
		$bg.bind('load', start_resize);
		$(window).bind('load', start_resize);
		$(window).bind('resize', handle_resize);
	};
	
	return {
		start_resize: start_resize,
		handle_resize: handle_resize,
		init: init
	};
})(jQuery);

jQuery(document).ready(function () {
	artifex.layout.init();
});


