var SequenceImageLoader = {

	started: false,
	queue: 'closed',
	counter: 0,
	imageStack: [],

	initialize: function(){
		this.open();
		return true;	
	},

	addImage: function(imageUrl, returnChain){
		if (this.queue != 'open') return false;
		this.imageStack[this.imageStack.length] = {
			'imageUrl': imageUrl,
			'returnChain': returnChain
		};
		this.chain(
			function(){
				this.imageStack[this.counter].loadedImage = new Asset.image(this.imageStack[this.counter].imageUrl, {
					onload: function(){
						this.imageLoaded(this.imageStack[this.counter])
					}.bind(this)
				});
				return true;
			}
		)

		if (!this.started){
			this.started = true;
			this.callChain();
		}
	},
	
	imageLoaded: function(stackItem){
		if (stackItem) stackItem.returnChain.callChain(stackItem.loadedImage);
		if (this.imageStack.length > 0) this.nextImage();
	},
	
	nextImage: function (){
		this.counter++;
		if (this.counter == this.imageStack.length){
			this.clearChain();
			this.imageStack = [];
			this.counter = 0;
			this.started = false;
		} else {
			this.callChain();
		}
	},

	open: function(){
		this.queue = 'open';
	},
	
	close: function(){
		this.clearChain();
		this.imageStack = [];
		this.counter = 0;
		this.started = false;
		this.queue = 'closed';
	}

};

Object.append(SequenceImageLoader, new Chain());
SequenceImageLoader.initialize();
