var ImgLoader = new Class({

	initialize: function() {
		this.queue = [];
		this.int = null;
	},
	
	loadImg: function(cont, url) {
		if ($(cont).img && $(cont).img.get('src') == url) return;
		
		if ($(cont).img) $(cont).img.dispose();
		$(cont).img = new Element('img', { 'src': url });
		if (!$(cont).span)
			$(cont).span = new Element('span').set('text', 'Loading...').inject(cont);
		else
			$(cont).span.setStyle('display', 'block');
		
		if (!$(cont).fx) {
			$(cont).getElement('img').set('morph', { 'link': 'cancel' });
			$(cont).fx = new Fx.Morph(cont, { 
				'link': 'cancel',
				'onComplete': function(elem) {
					if (elem.getStyle('padding-top') != '0px') {
						elem.getElement('img').set('src', elem.img.src);
						elem.setStyles({ 'padding-top': 0, 'padding-bottom': 0 });
					}
					else
						elem.setStyle('background-image', 'none');
				}
			});
		}
		this.queue.push(cont);
		
		if (!this.int) this.int = this.checkProgress.periodical(50, this);
	},
	
	checkProgress: function() {
		this.queue.each(function(cont) {
			if ($(cont).img.complete) {
				var imgToLoad = $(cont).img;
				var img = $(cont).getElement('img');
				if (imgToLoad.height > img.height) {
					$(cont).setStyles({ 'background-image': 'url(' + imgToLoad.get('src') + ')' });
					img.morph({ 'opacity': 0 });
					
					var offset = Math.round((imgToLoad.height - img.height) / 2);
					$(cont).fx.start({ 'padding-top': offset, 'padding-bottom': offset });
				}
				else {
					var offset = Math.round((img.height - imgToLoad.height) / 2);
					if (img.src != imgToLoad.src) $(cont).setStyle('background-image', 'url(' + img.get('src') + ')');
					if ($(cont).getStyle('padding-top') == '0px') $(cont).setStyles({ 'padding-top': offset, 'padding-bottom': offset });
					if (img.getStyle('opacity') == 1) img.setStyle('opacity', 0);
					img.set('src', imgToLoad.get('src')).morph({ 'opacity': 1 });
					
					$(cont).fx.start({ 'padding-top': 0, 'padding-bottom': 0 });
				}
				
				$(cont).span.setStyle('display', 'none');
				this.queue.erase(cont);
			}
		}, this);
		
		if (!this.queue.length) {
			$clear(this.int);
			this.int = null;
		}
	}
	
});
var imgLoader = new ImgLoader();
