
(function($){

	$.fn.WaitForImgLoad = function(options){
		
		var o = $.extend({
			onload: function(){},
			onerror: function(){},
			width: null,
			height: 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 p = null;//Percentage
						
			if(o.width && iWidth > o.width)//If width has been specified and width of the image is bigger than specified
			{
				p = getPercentage(iWidth,o.width);
				iWidth = iWidth * p;
				iHeight = iHeight * p;	
				if(o.height && iHeight > o.height)
				{
					p = getPercentage(iHeight,o.height);
					iWidth = iWidth * p;
					iHeight = iHeight * p;
				}
			
			} else {
				if(iHeight > o.height)
				{
					p = getPercentage(iHeight,o.height);
					iWidth = iWidth * p;
					iHeight = iHeight * p;
					if(o.width && iWidth > o.width)
					{
						p = getPercentage(iWidth,o.width);
						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
			$('<img />')
			.bind('load',{obj:obj},function($e){
				var $o = $e.data.obj;
				$o.overallCount += 1;
				$o.count += 1;
				if(o.width || o.height)
				{
					var sSrc = $(this).attr('src').split('/');
					setDimensions.call($('img[src$=' + sSrc[sSrc.length - 1] + ']')[0]);
				}
				if($o.count == $o.length)o.onload.call($o);	
				if($o.overallCount == $o.length && $o.count != $o.length)o.onerror.call($o);					
			})
			.bind('error 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);
