var mooImageReplacer = new Class
({
	Implements: Options,
	
	img: false,
	images: {},
	
	options: {
		urls: [],
		copyrightEl: false,
		copyright: [],
		selector: '',
		firstlink: false
	},
	
	initialize: function(img, options)
	{
		this.setOptions(options);
		this.img = img;
		
		window.addEvent('domready', function() { this.startup(); }.bind(this));
	},
	
	startup: function()
	{
		var self = this;
		this.images = new Hash();

		$$(this.options.selector).each(function(img, num) {
			self.images.include(num, {
				img: img,
				url: self.options.urls[num],
				copyright: self.options.copyright[num]
			});
		});
		
		if (this.options.firstlink) {
			var copyright = '';
			if (self.options.copyrightEl) {
				copyright = self.options.copyrightEl.get('html');
			}
			this.options.firstlink.addEvent('click', function(e) {
				e.stop();
				var href = this.get('href');
				if (href != self.img.get('src')) {
					self.clickEvent({
						url: href,
						copyright: copyright 
					});
				}
			});
		}
		
		this.images.each(function(image, num) {
			var link = new Element('a', {
				'class': 'imagelink',
				href: image.url,
				events: {
					click: function(e) {
						e.stop();
						if (this.get('href') != self.img.get('src')) {
							self.clickEvent(image);
						}
					}
				}
			});
			
			link.wraps(image.img);
		});
	},
	
	clickEvent: function(image)
	{
		if (!image) return;
		
		var current = this.img;
		
		var myFx = current.get('tween', {property: 'opacity', duration: 200});
		var newImg = current.clone().setStyle('opacity', 0);
		
		newImg.addEvent('load', function() {
			myFx.start(0).chain(function() {
				var myFx = newImg.get('tween', {property: 'opacity', duration: 800});
				newImg.replaces(current);
				current.destroy();
				myFx.start(1);
				if (this.options.copyrightEl) {
					this.options.copyrightEl.set('html', image.copyright);
				}
			}.bind(this));
		}.bind(this));
		
		//trigger actual load event
		newImg.set('src', image.url);
		
		this.img = newImg;
	}	
	
});
