/**
* Preloade 1.0 // 2011.01.30
* <http://idered.pl/news/jquery/preloader/>
* 
* @author    Idered <IderedPL@gmail.com>
*/
$.fn.preloader = function(options) {
	var defaults = {
		onDone:function(){ },
		onEachLoad:function(img){},
		fadeIn : 500,
		delay : 100,
		interval : 200,
		parentWrap : 'a',
		loader: 'loader.gif'
	},
	options = $.extend(defaults, options),
	images = $(this).find('img'),
	delayTime = 0;
	
	images.css({
			visibility : 'visible',
			opacity : 0
		}).each(function() {
			var thisParent = $(this).parent(options.parentWrap) 
			if(thisParent.length) 
				thisParent.addClass('preloader');
			else 
				$(this).wrap('<a class="preloader unwrap"/>');
		});
	
	var timer = setInterval(function() {
			init()
		}, options.interval);
		
	init = function() {
		images = images.filter(function() {
				if(this.complete && this.naturalWidth !== 0) {
					delayTime = delayTime + options.delay;
					$(this).css({
							visibility : 'visible'
						}).delay(delayTime).animate({
							opacity : 1
						}, options.fadeIn, function() {													
							$(this).parent().removeClass('preloader');
							if($(this).parent().hasClass('unwrap')) 
								$(this).unwrap();
							options.onEachLoad($(this));
						});
				} else {
					return this;
				}
			}
		);
		if(images.length == 0) {
			clearInterval(timer);
			options.onDone();
		}
	};
}
