
(function($){

	$.fn.WaitForImgLoad = function(options){
		
		var o = $.extend({
			onload: function(){},
			onerror: function(){},
			onImgError: function(){},
			width: null,
			height: null,
			removeAttributes: null	
		},options);
		
		
		
		this.count = 0;
		this.overallCount = 0;
		
		var obj = this;
		
		function getPercentage(nFull,nPartial)
		{
			return (nPartial / nFull);	
		}
		
		function setDimensions()
		{
			
			if(!o.width && !o.height)return;//If there is no width or height relative dimensions
						
			var iWidth = this.width; 
			var iHeight = this.height;
			
			
			var thisWidth = (!o.width) ? iWidth: o.width;
			var thisHeight = (!o.height) ? iHeight: o.height;
			
						
			var p = null;//Percentage
			
			while((iWidth > thisWidth) || (iHeight > thisHeight))
			{
				if(iWidth > thisWidth)
				{
					p = getPercentage(iWidth,thisWidth);
					iWidth = iWidth * p;
					iHeight = iHeight * p;
				}
				
				if(iHeight > thisHeight)
				{
					p = getPercentage(iHeight,thisHeight);
					iWidth = iWidth * p;
					iHeight = iHeight * p;
				}
			}
						
			if(p)//If percentage has been set
			{
				var finalWidth = Math.round(iWidth); 
				var finalHeight = Math.round(iHeight);
				$(this)
					.css({
						width: finalWidth + 'px',
						height: finalHeight + 'px'	
					})
					.attr({
						width: finalWidth,
						height: finalHeight	
					});		
			}	
		}
		
		return this.each(function(){//Loop through each image
			if(o.removeAttributes)
			{
				$(this).removeAttr('width').removeAttr('height');	
			}
			if(this.complete) {
				var $o = obj;
				$o.overallCount += 1;
				$o.count += 1;
				if(o.width || o.height)setDimensions.call(this);
				if($o.count == $o.length)o.onload.call($o);	
				if($o.overallCount == $o.length && $o.count != $o.length)o.onerror.call($o);	
			} else {
				$(this)
				.bind('load',{obj:obj},function($e){
					var $o = $e.data.obj;
					$o.overallCount += 1;
					$o.count += 1;
					if(o.width || o.height)setDimensions.call(this);
					if($o.count == $o.length)o.onload.call($o);	
					if($o.overallCount == $o.length && $o.count != $o.length)o.onerror.call($o);					
				})
				.bind('error',{obj:obj},function($e){
					var $o = $e.data.obj;
					$o.overallCount += 1;	
					o.onImgError.call(this);
					if($o.overallCount == $o.length)o.onerror.call($o);	
				}).bind('abort',{obj:obj},function($e){
					var $o = $e.data.obj;
					$o.overallCount += 1;	
					if($o.overallCount == $o.length)o.onerror.call($o);	
				}).attr('src',this.src);
			}
		});
	};
	
})(jQuery);
