/**
 * Created by IntelliJ IDEA.
 * Author: Khrystyna Skvarok
 * Date: 03-Mar-2011
 * Time: 15:28:13
 *
 * Covers specified element with image.
 */
(function($){
	var settings = {
			"source": "",
			"center": false
		},
		content,
		image;

	$.fn.coverme = function(options){
		if (options) $.extend(settings, options);

		image = $("<img>").attr("src",settings.source);
		content = $(this).css("overflow","hidden")
						.css("visibility","hidden")
						.prepend(image);

		$(window).load(function(){cover();})
				 .bind("resize",function(){cover();});

		return this;
	};

	function cover(){
		var contentWidth = content.width();
		var contentHeight = content.height();
		var imageWidth = image.width();
		var imageHeight = image.height();
		var k = 1;

		if (contentWidth > contentHeight){
			if (imageWidth > imageHeight){
				k = imageWidth/imageHeight;
				var newImageHeight = Math.round(contentWidth * (1/k));
				image.css({width:contentWidth,height:newImageHeight});

				if(newImageHeight < contentHeight){
					k = imageHeight/imageWidth;
					image.css({height:contentHeight,width:Math.round(contentHeight * (1/k))});
				}
			}else{
				k = imageHeight/imageWidth;
				image.css({height:contentHeight,width:Math.round(contentHeight * (1/k))});
			}
		}else{
			k = imageHeight/imageWidth;
			image.css({height:contentHeight,width:Math.round(contentHeight * (1/k))});
		}

		content.css("visibility","visible");
		// Center background image
		if (settings.center){
			image.css("position","relative");
			if (image.width() > contentWidth) image.css("left", "-" + Math.round((image.width() - contentWidth)/2) + "px");
			else image.css("left", "0");
		}
	}
})(jQuery);
