window.addEvent('domready', function()
{
    
    //scale and centre background image
	var scaleBackground = function()
	{
		var container_coords = $('background').getCoordinates();
		
		//add 6px to width for shadow if there
		if (container_coords.width != $('background').getStyle('width').toInt()) container_coords.width += 6;
		
		var background_image = $('background').getElement('img');
		var image = new Asset.image(background_image.getProperty('src'),
		{
			onload: function()
			{
				if (background_image.hasClass('loading'))
				{
					new Fx.Style(background_image, 'opacity').start(1);
					background_image.removeClass('loading');
				}
			}
		});
		
		var width_ratio = image.width / container_coords.width;
		var height_ratio = image.height / container_coords.height;
		
		//extend vertically or horizontally (proportionally) depending on ratio
		if (width_ratio > height_ratio)
		{
			var new_height = container_coords.height;
			var new_width = image.width * new_height / image.height;
		}else{
			var new_width = container_coords.width;
			var new_height = image.height * new_width / image.width;
		}
		
		//apply new styles
		background_image.setStyles(
		{
			'width': new_width,
			'height': new_height,
			'margin-left': 0 - Math.abs(new_width - container_coords.width) / 2,
			'margin-top': 0 - Math.abs(new_height - container_coords.height) / 2
		});
	};
	
    if ($('background') != undefined)
    {
        $('background').getElement('img').setStyle('opacity', 0).addClass('loading');
		
		scaleBackground.delay(200);
        
        window.addEvent('resize', scaleBackground);
    }

	
});
