/**
 * @author Benjamin Falk
 */

(function( $ ) {
	var methods = {
	
		/**
		 * Init scalebackground function
		 */
		init: function( options ) {
			if (typeof options != "object") {
				options	= {};
			}
			
			return this.each(function() {
				if (!options.image) {
					var backgroundImage = $(this).css('backgroundImage');
					var matches	= backgroundImage.match(/url\(["]?(.+?)["]?\)/i, backgroundImage);
					if (!matches) {
						return;
					}
					options.image = matches[1];
				}
				
				$(this).append('<div id="scalebackgroundimage"><img src="" alt="" /></div>');
				$("#scalebackgroundimage img").load(function() {
					$(this).data('imgWidth', $(this).width());
					$(this).data('imgHeight', $(this).height());
					methods.resize();
					$("#scalebackgroundimage img").css({
						visibility: 'visible'
					});
				});
				$("#scalebackgroundimage img").css('visibility', 'hidden');
				$("#scalebackgroundimage img").attr('src', options.image);
				
				$("#scalebackgroundimage").css({
					position: 'fixed',
					left: 0,
					top: 0,
					width: '100%',
					height: '100%',
					zIndex: 0,
					overflow: 'hidden'
				});
				$("#scalebackgroundimage img").css({
					position: 'absolute',
					left: 0,
					top: 0,
					zIndex: 0
				});
				
				$(window).resize(methods.resize);
			});
		},
		
		resize: function() {
			// get document dimensions
			var docWidth	= $(window).width();
			var docHeight	= $(window).height();
			
			// get original image size
			var imgWidth	= $("#scalebackgroundimage img").data('imgWidth');
			var imgHeight	= $("#scalebackgroundimage img").data('imgHeight');
			
			var newWidth	= docWidth;
			var newHeight	= docWidth / imgWidth * imgHeight;
			var newLeft		= 0;
			var newTop		= docHeight / 2;
				newTop		-= newHeight / 2;
			
			if (newHeight < docHeight) {
				newHeight	= docHeight;
				newWidth	= docHeight / imgHeight * imgWidth;
				newLeft		= docWidth / 2;
				newLeft		-= newWidth / 2;
				newTop		= 0;
			}
			
			$("#scalebackgroundimage img").css({
				left: newLeft,
				top: newTop,
				width: newWidth,
				height: newHeight
			});
		}
	}
	
	$.fn.scalebackground = function( method ) {
		if ( methods[method] ) {
			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
		}
		else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		}
		else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.scalebackground' );
		}
	}
})( jQuery );
