//////////////////////////////////////////////////////////
// This function handles preload of hidden images
//
// Return void
//////////////////////////////////////////////////////////
var imageLoader = {
	"images" : [],
	"loaderFunction" : function() {
		log("loader function called");
		var repeate = false;
		for (var i = 0; i < imageLoader.images.length; i++) {
			var image = imageLoader.images[i];
			if (image.loading) {
				if (image.preload.complete) {
					image.loading = false;
					if (image.preload.width > 0 || (!isUndefinedOrNull(image.preload.naturalWidth) && image.preload.naturalWidth > 0)) {
						image.error = false;
						signal(image, 'onimageloadok');
					} else {
						image.error = true;
						signal(image, 'onimageloaderror');
					}
					signal(image, 'onimageloaded');
				} else {
					repeate = true;
				}
			}
		}
		if (repeate) {
			callLater(.1, imageLoader.loaderFunction);
		}
	}
}

function showOnLoaded(event) {
	log("showing " + event.src().src);
	removeElementClass(event.src(), 'hidden');
}

function preloadHiddenImages() {
	map(function(imgTag) {
		if (!isUndefinedOrNull(imgTag.src)) {
			var preload = new Image();
			/*var preload = null;
			if (isUndefinedOrNull(imgTag.width) || imgTag.width == 0 ||
				isUndefinedOrNull(imgTag.height) || imgTag.height == 0) {
				preload = new Image();
			} else {
				preload = new Image(imgTag.width, imgTag.height);
			}*/
			preload.src = imgTag.src;
			imgTag.preload = preload;
			imgTag.loading = true;
			imgTag.error = null;
			imageLoader.images.push(imgTag);
		}
		if (hasElementClass(imgTag, "showonloaded")) {
			connect(imgTag, 'onimageloadok', showOnLoaded);
		}
	}, getElementsByTagAndClassName("img", "hidden"));
	if (imageLoader.images.length > 0) {
		imageLoader.loaderFunction();
	}
}
addLoadEvent(preloadHiddenImages);

