/**
 * jQuery Preloader for preloading all image objects located
 * in a given selection. As arguments the preloader expects
 * the selection set (given as a css selector id), the function
 * to be executed as resume and an option set, whereas the
 * only option by default is now:
 *
 * activate : true / false -> enabling / disabling preloader
 *
 * Version 1.0 2009-03-04
 */
(function($) {
	// define the jquery preloader function
	$.fn.preloader = function(selection, fn, options) {
		debug(this.size());
		// build main options before element iteration
		var opts = $.extend({}, $.fn.preloader.defaults, options);
		// set image selection set
		var $imgs = $(selection);
		// iterate and check for images loaded
		return this.each(function() {
			var $this = $(this);
			// build element specific options
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			// execute preloader on images selection
			if (o.activate == false) {
				fn.call( this );
			} else {
				// check image loading state by using interval timeout
				var intID = setInterval(function() {
					if (allImagesLoaded($imgs) == true) {
						clearInterval(intID);
						$($this).css({'display':'none'});
						fn.call( this );
					}
				}, 50);
			}
		});
	};
	// function to check elements loading state
	function allImagesLoaded($imgs) {
		for (var i = 0; i < $($imgs).size(); i++) {
			var $img = $($imgs).get(i);
			if ($img.complete == false) {
				return false;
			}
		}
		return true;
	};
	function debug($message) {
		if (window.console && window.console.log)
			window.console.log('debug: ' + $message);
	};
	// plugin defaults
	$.fn.preloader.defaults = {
		activate : true
	};
})(jQuery);
