﻿/**
 * 
 * Background Scaler
 * 
 * Plugin for scaling background to the screen size,
 * keeping the image ratio.
 * 
 */
(function($){
$.fn.scaleBgImage = function() {
	
	var cont = $(this);
	var fill = $(this).children(); // Select the image(s)(note: needs to be same size.)
	
	var imageObject = cont.find('img');
	
	var image = { width: imageObject.width(), height: imageObject.height() };
	image.ratio = image.height/image.width;
	
	
	function update() {
		
		// Define window
		var wind = { width: $(window).width(), height: $(window).height() };
		wind.ratio = wind.height/wind.width;
		
		var tmpWidth;
		var tmpHeight;
		
		
		//Resize image to proper ratio
		if (wind.ratio > image.ratio) 
		{
			tmpHeight = wind.height;
			tmpWidth = wind.height / image.ratio;
		} 
		else 
		{
			tmpHeight = wind.width * image.ratio; 
			tmpWidth = wind.width;
		}
		
		fill.height(tmpHeight);
		fill.width(tmpWidth);
			 
		// Center the image
		cont.children().css('left', (wind.width - tmpWidth)/2);
		cont.children().css('top', (wind.height - tmpHeight)/2);
		
		
	};
	
	imageObject
		.load(function() {
			
			image = { width: imageObject.width(), height: imageObject.height() };
			image.ratio = image.height/image.width;
			
			$(window).resize(function() {
				update();
			});
			
			$(window).trigger('resize');
			
		})
		.each(function() {
			if(this.complete) $(this).trigger("load");
		});

};
})(jQuery);
