/**
 * jQuery-Plugin "onImagesLoaded"
 * @author Mailo Svetel<development@rooland.cz>
 * @author Opicze<opicze@gmail.com>
 * @class Document's images preloader
 *
 */


(function($){  
 $.fn.onImagesLoaded = function(options) {  

	var defaults = { 
		
		// PUBLIC
		interval: 250,		
		maxTime: 30000,
		onComplete: null, 
		onErrors: null,

		// PRIVATE
		images: this.find("img"),
		startedTime: 0,
		isTimeOver: false,		
		ready: new Array(),
		errors: new Array()
		
	};  
	
	var options = $.extend(defaults, options);

	var isReady = function(d)
	{
		var loaded = true;
		
		// testing how much time preloading took
		actualTime = new Date();   actualTime = actualTime.getTime();
		if ((actualTime - d.startedTime) > d.maxTime) d.isTimeOver = true;

		// test if images has loaded
		d.images.each(function(){
			img = $(this).get(0);   if(!img.complete) { loaded = false; return false; }
		});

		// if all images are finished od max time elapsed, end preloading
		if(loaded || d.isTimeOver)
		{
			// sorting images to ready or with error
			d.images.each(function(){
				img = $(this).get(0);
				if(typeof img.naturalWidth == "undefined" || img.naturalWidth == 0 || !img.complete) { d.errors.push($(this)); }
				else { d.ready.push($(this)); }
			});
				
			// run fce for complet task	
			if(typeof d.onComplete != "function") { eval(d.onComplete); } else { d.onComplete(d.ready); }
			
			// run fce for errors and leave log to firebug							
			if(d.errors.length > 1)
			{
				if(typeof d.onErrors != "function") { eval(d.onErrors); } else { d.onErrors(d.errors); }
				//console.info("List of images that can not be loaded in corect time: \n");
				//for(i in d.errors) { console.warn(d.errors[i]); }
			}
		
		// not redy yet, call test later	
		} else { setTimeout(function(){ d.isReady(d); }, d.interval); }	
	}

	// lets calculate elaapsed time
	timeStamp = new Date();
	options.startedTime = timeStamp.getTime();
	
	// save fce, because setTimeout is just global function
	options.isReady = isReady;
	setTimeout(function(){ options.isReady(options); }, options.interval); 

 };  
})(jQuery);

