(function(window, $){
	function fitToParent(jElement, options, jParent){
		options = $.extend(true, {}, {
			cssSelectors : {
				Parent : 'div:first'
			},
			Permanent : false,
			fitHeight : true
		}, options);
		if(!(jElement && jElement instanceof $ && jElement.length)) return false;
		if(!(jParent && jParent instanceof $ && jParent.length)){
			if(options.cssSelectors.Parent.length){
				jParent = jElement.parents(options.cssSelectors.Parent);
			} else {
				jParent = jElement.parent();
			}
		}
		if(jElement.length > 1){
			jElement.each(function(index){
				setElementSizes($(this), jParent.eq(index), options);
			});
		} else {
			setElementSizes(jElement, jParent, options);
		}
		
		if(options.Permanent===true){
			$(window).bind('resize.fitToParent', function(){
				if(fitToParent.Timer) return false;
				fitToParent.Timer = setTimeout(function(){
					fitToParent(jElement, options, jParent);
					clearTimeout(fitToParent.Timer);
					fitToParent.Timer = null;
				}, 1);
			});
		}
	}
	
	function setElementSizes(jElement, jParent, options){
		var baseWidth, parentWidth = jParent.width('100%').width(), baseHeight, parentData = jParent.data(), elementWidth = jElement.width() || jElement.attr('width');
		if(!(parentData && (baseWidth = parentData['chBaseW']))) jParent.data('chBaseW', (baseWidth = elementWidth));
		if(!(parentData && (baseHeight = parentData['chBaseH']))) jParent.data('chBaseH', (baseHeight = jElement.height() || jElement.attr('height')));
		if(parentWidth != baseWidth) {
			if(baseWidth < parentWidth) {
				jElement.width(baseWidth)
				if(options.fitHeight!==false) jElement.height(baseHeight);
			} else {
				jElement.width(parentWidth);
				if(options.fitHeight!==false) jElement.height(Math.round(parentWidth/baseWidth*baseHeight));
			}
		}
		jParent.css('width','');
	}
	
	$.fn.fitToParent = function(options, jParent){
		fitToParent($(this), options, jParent);
	}
})(this, jQuery);
