(function($) {
$.widget("ui.scaleBackground", {
	options:{
		src: "images/bg/01.jpg"
	},
	img: undefined,
	container: undefined,
	imgParams:{width: undefined, height: undefined},
	_create: function(){},
	_init: function(){
		var widget = this, $element = $(widget.element), $img, $container;
		
		$container = $("<div>").css({position:"absolute", overflow:"hidden", zIndex: -1});
		
		
		$img = $("<img src='"+widget.options.src+"'>").appendTo($container);
		// $img.css({position: "absolute", top:0, left:0, zIndex: -1});
		$img.load(function() {widget._storeImageSize();})
		
		widget.container = $container;
		widget.img = $img;
		$container.appendTo($element)	
		
		$(window).resize(function(){
			widget._update();
		}).scroll(function() {
			widget._update();
		});
		
	},
	_storeImageSize: function() {
		var widget = this, $element = $(widget.element), $img = widget.img;
		
		
		widget.imgParams = {width: $img.width(), height: $img.height(), ratio:$img.width()/$img.height()};
		widget._update();
	},
	_update: function(){
		var widget = this, $element = $(widget.element), imgParams = widget.imgParams, $w, w, params, destRatio, imageRatio;
		
		$w = $(window);
		
		
		w = {
			width: $w.width(),
			height: $w.height()
		}
		
		
		destRatio = w.width/w.height;
		imageRatio = imgParams.ratio;	
		
		
		if (imageRatio >= destRatio){
			newHeight = w.height;
			newWidth = w.height * imageRatio;
		} else {
			newHeight = w.width / imageRatio;
			newWidth = w.width;
		}
		
		widget.img.css({width: newWidth, height: newHeight});
		
		widget.container.css({width:$w.width(), height:$w.height(), top: $w.scrollTop(), left: $w.scrollLeft()});
				
		/*onsole.log(newWidth, newHeight)
		
		if (imageRatio <= destRatio){
			widget.img.css({width:"100%", height: "auto"});
		} else {
			widget.img.css({height:"100%", width: "auto"});
		}*/
		
	
	},
	destroy: function(){
		this.element.html("");
	}
});
})(jQuery);

