
var Gallery = {
	height: 50,
	width: 50,
	popupURL: '',

	show: function(options_id, options_values_id) {
		var thumb_el = $('extra_images');
	
		if (extra_images === undefined || thumb_el === undefined)
			return;
		
		thumb_el.empty();
		
		var images = extra_images.filter(function(item, index) {
			return (item.options_id == options_id && item.options_values_id == options_values_id);
		});
		
		if (images.length === 0)
			return Gallery.show(0, 0);
			
		if (images.length === 1)
			thumb_el.setStyle('display','none');
		else
			thumb_el.setStyle('display','');
		
		images.each(function(item, index) {
			var el = new Element('img', {
				'src': item.tiny,
				'width': this.tiny_width,
				'height': this.tiny_height,
				'class': 'gallery'
			});
			
			el.addEvent('click', this.select.pass([el, item.reg, item.full, item.full_width, item.full_height], this));
			
			if (index === 0) {
				if (item.tiny === '')
					el.setStyle('display','none');
				
				el.addClass('selected');
				this.select(el, item.reg, item.full, item.full_width, item.full_height);
			}
		
			thumb_el.adopt(el);
		}.bind(this));
	},
	
	select: function(el, reg_url, full_url, full_width, full_height) {
		$$('img.gallery').removeClass('selected');
		el.addClass('selected');
		$('main_image').src = reg_url;
		$('full_image').removeEvents('click').addEvent('click', function(event) {
			event.stop();
			this.popup(full_url, full_width, full_height);
			return false;
		}.bind(this));
	},
	
	popup: function(url, width, height) {
		popupImage(this.popupURL.substitute({full_url: url}), width, height);
	
		return false;
	},
	
	findOptions: function() {
		if (option_ids === undefined)
			return;
		
		option_ids.each(function(option_id) {
			if (document.forms['cart_quantity']['id['+ option_id +']'] !== undefined) {
				$$('select[name^=id]').each(function(el) {
					if (el.name != 'id['+ option_id +']')
						return;

					el.addEvent('change', function() {
						Gallery.show(option_id, el.options[el.selectedIndex].value);
					});
				});
			}
		}.bind(this));
	}
};

window.addEvent('domready', Gallery.findOptions.bind(Gallery));