if (!JL) var JL = {};

JL.ColorSwatches = Class.create({
	initialize: function (colorAttr, mediaPath, products) {
		// Find color attribute
		$H(products.attributes).each(function (pair) {
			if (pair.value.code === colorAttr) {
				this.element = $('attribute'+pair.key);
				this.colors = pair.value.options;
				throw $break;
			}
		}.bind(this));

		if (!this.element) throw(Effect._elementDoesNotExistError);
		this.element.observe('change', this.selectOnChange.bind(this));
		
		// Create swatches
		this.swatches = new Element('ul');
		//var hash = $H(colors);
		this.colors.each(function (color) {
			// Create list item
			var swatch = new Element('li');
			this.swatches.insert(swatch);
			
			// Create image
			var img = new Element('img');
			var src = mediaPath+'swatches/' + color.label.gsub(/[\s//]/, '_') + '.png';
			img.src = src;
			img.alt = color.label;
			img.title = color.label;
			img.color_value = color.id;
			img.observe('click', this.swatchOnClick.bind(this));
			swatch.insert(img);					
		}.bind(this));
		
		// Insert into DOM
		$('color-swatches').insert(this.swatches);
	},
	selectSwatch: function (value) {
		this.swatches.select('img').each(function (item) {
			if (item.color_value === value) {
				item.addClassName('selected');
			} else {
				item.removeClassName('selected');
			}
		});
	},
	selectOption: function (value) {
		this.element.value = value;
		spConfig.configureElement(this.element);
	},
	selectOnChange: function (event) {
		var element = event.element();
		this.selectSwatch(element.value);
	},
	swatchOnClick: function (event) {
		var element = event.element();
		this.selectSwatch(element.color_value);
		this.selectOption(element.color_value);
	}
});

