$.fn.extend({'Underlay': Underlay});

function Underlay(props)
{
		var self = this;
		var MINIMAL_TRUSTED_HEIGHT = 2;//px 		
		var isAllTrusted = false;
		var defaultProps = {'controlHeight': false, 'controlWidth': false};
		
		initUnderlay();
		
		function initUnderlay()
		{
			initProperties();
			self.each(initLoadTrueImage);
		}

		function initProperties()
		{
			if( typeof props !== 'object' )
			{
				props = {};
			}
			for(i in defaultProps)
			{
				if(!defaultProps.hasOwnProperty(i) || props.hasOwnProperty(i)) continue;
				props[i] = defaultProps[i];
			}
		}
		
		function initLoadTrueImage()
		{
			var cont = $(this);
			cont.css({'font-size':	'0px', 'line-height':	'0px', 'overflow': 'hidden'});
			var input = $('input[name=true_src]', cont);
			var img = $(new Image());
			img.load(onloadTrueImage);
			img.attr('src', input.val());
			img.css({display: 'none'});
			cont.append(img);
		}
		
		function onloadTrueImage()
		{
			var img = $(this);
			if( img.height() > MINIMAL_TRUSTED_HEIGHT )
			{
				onTrustedLoadImage(img);
			}
			else
			{
				img.addClass('need-control');
				if( isAllTrusted )
				{
					isAllTrusted = false;
					initControlSize();
				}
			}
		}
		
		function initControlSize()
		{
			setTimeout(controlSize, 500);
		}
		
		function controlSize()
		{
			isAllTrusted = true;
			$('.need-control', self).each(onloadTrueImage);
		}
		
		function onTrustedLoadImage( img )
		{
			img.removeClass('need-control');
			var parent = img.parent();
			if( props.controlHeight )
			{
				img.css('margin-top', Math.ceil((parent.height() - img.height())/2) + 'px' );
			}
			if( props.controlWidth )
			{
				img.css('margin-left', Math.ceil((parent.width() - img.width())/2) + 'px' );
			}
			img.prevAll('img').hide();
			img.fadeIn('slow');
		}
}

