
/*************************************************************************

Loader.js
Downloads images from an array of url specified and makes a callback
to the calling page returning all images downloaded.

**************************************************************************/


//Reference to my callback function
var callBack;
//Array of images
var imgCollection;
//Count of total images
var totalImages = 0;
//Count of download complete
var downloadCounter = 0;
var path;

//Path - Array of URL to download
function load(myPath) {
	downloadCounter = 0;
	imgCollection = new Array;
	path = myPath;
	//alert("Total load images: " + path.length);
    totalImages = path.length;
	
	//alert("calling download next");
    downloadNext();
}

//Downloads the next image waiting in the queue
function downloadNext() {
	//alert("Trying " + path.length);
    var url = path[downloadCounter];
	//alert("Trying to load: " + url);
    download(url);
}

//Downloads an image from the specified url
function download(url) {
	//alert("Attempting to download: " + url);
    var img = new Image;
    imgCollection.push(img);
    img.onload = downloadComplete;
    img.onabort = downloadComplete;
    img.onerror = downloadComplete;
    //alert("Downloading " + url);
    img.src = url;
}

function onError() {
	//alert("Error in loading : " + path[downloadCounter]);
}

//Callback function invoked on image download success\error\abort
function downloadComplete() {
	try {
		downloadCounter++;
		//alert("Download counter: " + downloadCounter + " totalImages: " + totalImages);
		if(downloadCounter == totalImages) {
			loadingComplete();
		}
		else {
			downloadNext();
		}
	}
	catch(e) {
	}
	
}

//Makes callback to the calling script
function loadingComplete() {
    callBack(imgCollection);
}

//Registers the callback
function setCallback(myCallback) {
	//alert("Setting call back");
    callBack = myCallback;
}