// Use a namespace for our scripts.
var WMX = WMX || {};

WMX.StockPhotoColor = Class.create({
	initialize: function (id) {
		this.container = $(id);

		if (!this.container)
			return;

		this.captioncontainer = new Element('div');
		this.captioncontainer.addClassName('caption');
		this.imagecontainer   = new Element('div');
		this.imagecontainer.addClassName('main');
		this.colorcontainer   = new Element('div');
		this.colorcontainer.addClassName('colors');

		this.images = new Array();

		this.container.select('img').each(this._addImage.bind(this));
		this.container.update();

		this.captioncontainer.update(this.imagecontainer.select('img')[0].alt);
		this.imagecontainer.select('img')[0].setStyle({ opacity: 1.0 });

		this.container.insert(this.captioncontainer);
		this.container.insert(this.imagecontainer);
		this.container.insert(this.colorcontainer);

		this.currentIndex = 0;
	},

	_addImage: function (img, index) {
		img.setStyle({ opacity: 0.0 });
		this.images[index] = img;
		this.imagecontainer.insert(img);

		var colorspan = new Element('span', {title: img.alt }).setStyle({
			backgroundColor: img.getStyle('color')
		});

		colorspan.update('&nbsp;&nbsp;&nbsp;&nbsp;');
		colorspan.observe('mouseover', this._changeImage.bindAsEventListener(this, index));

		this.colorcontainer.insert(colorspan);
	},

	_changeImageComplete: function (oldIndex) {
		this.captioncontainer.update(this.images[this.currentIndex].alt);
		this.images[oldIndex].setStyle({ opacity: 0.0 });
	},

	_changeImage: function (e, index) {
		var curIndex = this.currentIndex;
		if (curIndex != index)
		{
			Effect.Queues.get(this.container.id + curIndex).each(function(e) { e.cancel(); });
			this.imagecontainer.insert(this.images[index]);
			this.images[index].appear({
				duration: 0.5,
				afterFinish: this._changeImageComplete.bind(this, curIndex),
				queue: { scope: this.container.id + curIndex }
			});

			this.currentIndex = index;
		}
	}
});

