(function($) 
{
	// plugin definition
	$.fn.onscreenloader = function(options) {
	
		var items = this
	
		$(window).bind("scroll", moveViewport);
		$(window).bind("resize", resizeViewport);

		items.each( function()
		{
			$(this).attr('left',$(this).offset().left);
			$(this).attr('top',$(this).offset().top);
			$(this).attr('right',$(this).offset().left + $(this).width());
			$(this).attr('bottom', $(this).offset().top + $(this).height());			
		});
		
		return checkPlacements(items);

		function resizeViewport()
		{
			checkPlacements(items)
		};
		
		function moveViewport()
		{
			checkPlacements(items)
		};
		
		function checkPlacements(items)
		{
			
			var windowLeft = $(document).scrollLeft();
			var windowTop = $(document).scrollTop();
			var windowRight = windowLeft + $(window).width();
			var windowBottom = windowTop + $(window).height();
			
			return items.each ( function() 
			{
				if ( !$(this).attr('loaded'))
				{
					if ( (( ($(this).attr('left') > windowLeft) && ($(this).attr('left') < windowRight) ) || ( ($(this).attr('right') > windowLeft) && ($(this).attr('right') < windowRight) ) ) && (( ( $(this).attr('bottom') > windowTop) && ( $(this).attr('bottom') < windowBottom ) ) || ( ( $(this).attr('top') > windowTop) && ( $(this).attr('top') < windowBottom ) )  ) )
					{
						if ( $(this).attr('original') )
						{
							$(this).attr('src', $(this).attr('original'));
						}
						$(this).attr('loaded','loaded');
					}
					else if ( !$(this).attr('original') )
					{
						$(this).attr('original', $(this).attr('src'));
						$(this).removeAttr('src','');
					}
				
				}

			});			
		}
		
	};

	
})(jQuery);