/***********************
** BACKGROUND LOAD
************************
**/

function changeBackground(r, a, c, h, m ,n)
{
	var $j = jQuery.noConflict();
	setImage("http://www.beyondrisor.no/blog/wp-content/themes/bleed/images/bck/a" + a +"_c" + c +"_h" + h +"_m" + m +"_n" + n +"_r" + r +".jpg");	
}

/***********************
** BACKGROUND FADE
************************
**/

var id = '#bgwrapper';
var wrapper;


/**
 * Initiate 
 */
function init ()
{
	if( navigator.appName != "Microsoft Internet Explorer")
	{

		jQuery(id + '> img').each(function ()
		{
			img = jQuery(this);
			img.css('opacity', 0);
			jQuery(this).load(function () {
				resizeImg(jQuery(this));
				jQuery(this).fadeIn(1000);
			});
		})
	}
}

/**
 * Window resize handler
 */
jQuery(window).bind('resize', function()
{
	resizeImages();
})

/**
 * Load and fade in image with supplied url
 */
function setImage (url)
{
	var img = new Image();
	jQuery(img)
	.load(function ()
	{
		jQuery(this).hide();
		jQuery(id).append(this);
		resizeImg(jQuery(this));
		jQuery(this).fadeIn(1000, removePreviousImage);
	})
	.attr('src', url);
}

/**
 * Remove previous image after new images is faded in
 */
function removePreviousImage ()
{
	if (jQuery(id + '> img').size() > 1)
	{
		jQuery(id + '> img:first-child').remove();
	}
}

/**
 * Resize and center images to window size
 */
function resizeImages ()
{
	// Disallow resize background // bug Jquery .css()
	if( navigator.appName != "Microsoft Internet Explorer")
	{

		jQuery(id + '> img').each(function ()
		{
			img = jQuery(this);
			resizeImg(img);
		})
	}
}


function resizeImg (img)
{
	var w = window.innerWidth;
	var h = window.innerHeight;
	var windowaspect = w / h;
	
	img.removeAttr('width').removeAttr('height');
	var imgw = img.width();
	var imgh = img.height();
	var imgaspect = imgw / imgh;
		
	if (windowaspect > imgaspect)
	{
		img.css({'width' : w}).end();
		img.css({'height': w/imgaspect}).end();
	}
	else
	{
		img.css({'height' : h}).end();
		img.css({'width': h*imgaspect}).end();
	}

	img.css({'left': (w - img.width())*0.5}).end();
	img.css({'top': (h - img.height())*0.5}).end();
}
