// Loader

var imgLoader = new function Loader() {
	//List of images with the attribute {onload='imgLoader.addLoadedObj(this)'}
	//These are images you want to load first
	this.loadedObjs = new Array();
	//These is the numbers of images that have the attribute {imgLoader='loader.addLoadedObj(this)'}
	//This is use for firing loadObjs
	this.numObjsToLoad = 0; 
	
	//List of the images to load after all images with "onload='imgLoader.addLoadedObj(this)';" are loaded
	this.objsToLoad = null;
	this.objsLoaded = false;
	this.callback = null;
	this.ieFixTimer = setTimeout("imgLoader.loadObjs();",10000);
	
	this.setObjsToLoad = function (imagesArray) {
		this.objsToLoad = imagesArray;
	};
	this.setCallback = function(callback) {
		this.callback = callback;
	};
	
	this.addLoadedObj = function(obj) {
		if(obj == null || obj.src == null)
			return;

		if(!inArray(obj.src, this.loadedObjs))
			this.loadedObjs.push(obj.src);
		
		if(this.numObjsToLoad != 0 && this.loadedObjs.length >= (this.numObjsToLoad - 1))
			this.loadObjs();
	};
	
	this.loadObjs = function() {
		//if(this.objsLoaded)
			//return;
			
		if(this.callback != null && !this.objsLoaded)
			this.callback();
			
		this.objsLoaded = true;

		var images = document.getElementsByTagName("img");
		var x = 0;
		for(index in images) {
			if(!this.objsToLoad[x])
				return;
			
			if(!/lazy_loader/.test(images[index].className))
				continue;
			
			if((images[index].src != undefined) && images[index].getAttribute("onload") == null && this.objsToLoad[x]) {
				images[index].src = this.objsToLoad[x];
				x++;
			}
		}
	};
	
	//Calculates the number of imgs and iframes within a specific node
	this.setNumOfObjsToLoad = function(node) {
		var images = node.getElementsByTagName("img");
		var iframes = node.getElementsByTagName("iframe");
		var tempObjs = new Array();
		
		for(var x=0; x < images.length; x++) {
			if(!inArray(images[x].src, tempObjs)) {
				tempObjs.push(images[x].src);
			}
		}
		
		for(var x=0; x < iframes.length; x++) {
			if(!inArray(iframes[x].src, tempObjs)) {
				tempObjs.push(iframes[x].src);
			}
		}

		this.numObjsToLoad += tempObjs.length;
		//alert(this.numObjsToLoad);
	};
};

function inArray(value, array) {
	for(var x=0; x < array.length; x++) {
		if(array[x] == value)
			return true;
	}
	
	return false;
}
