/**********************************************

	Background Resizer script

	

	Resizes the background to the window

	size, while maintaining aspect ratio, 

	and cropping as little as possible.

	

	Written by: 

		Adam Quaile, adamquaile@gmail.com

		www.62degrees.co.uk



**********************************************/



$(window).load(function() {



	// Replace css background image with img tag in DOM
	// alert($('body').css('background-image'));
	bg = $('body')
			.css('background-image')
			.substring(
				4,
				parseInt(
					$('body')
					.css('background-image')
					.length
				) -1
			)
	bg = trim(bg, '"');
	//alert(bg);

	$('#bg').html("<img src='"+bg+"' id='bgimg' alt='' />");


	$('#bgimg')
	    .attr('src', bg)
	    .load(function(){
	        resize_bg();
	    });


/*
	$('#bg').html("<img src='"+bg+"' id='bgimg' alt='' />");
	
	$('#bgimg').load(function () {
console.log('hello');
		resize_bg()

	})

*/

	// $('body').css('background', 'none');

	



	function resize_bg() {

		

		// alert('eg')

		

		// Now do the resizing

		img = $('#bgimg');

		
		// console.log(img);

		i_x = img.width()

		i_y = img.height()

		w_y = $(window).height();

		w_x = $(window).width();

		

		r_x = w_x / i_x;

		r_y = w_y / i_y;

		

		r = Math.max(r_x, r_y);		

		

		t_x = r * i_x;

		t_y = r * i_y;

		

		// alert(i_x)

		

		img.attr('height', t_y);

		img.attr('width', t_x);

		

	}



	// resize_bg()

	$(window).resize(function () {

		resize_bg();

	});

});

/**
*
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
*
**/
 
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}