Event.observe(document, 'dom:loaded', function() {
	var images = [];
	var cur    = -1;
	var thumbs = $$('#product-thumbs a');
	var thumbsElement = $('product-thumbs');
	
	if (!thumbs.length) return;
	
	var productImage = $('product-image');
	var prodId = 0;
	
	// thumbnails list is the key to everything here
	thumbs.each(function(el, idx) {
		var id = el.readAttribute('rel').substring(8)
		
		// create our list of images in the slideshow
		images.push({
			id:   id,
			src:  el.readAttribute('data-src').substring(25),
			link: el.readAttribute('data-link')
		});
		
		var arrId = images.length - 1;
		
		// add click events for the thumbnails while we're here
		el.observe('click', function(e) {
			e.stop();
			slideTo(arrId);
		});
	});
	
	// for IE browsers that can't handle the truth, or :last-child in real CSS
	$$('#product-thumbs .product-thumb:last-child a').invoke('setStyle', { marginRight: 0 });
	
	// now add big images to main slideshow
	productImage.wrap('li').wrap('ul', { id: 'product-images', 'class': 'clean clearfix' }).wrap('div', { id: 'product-images-wrapper' });
	
	var productImages = $('product-images').setStyle({ width: (707 * images.length) + 'px' });
	
	//okay we have the basic setup, now add the rest of the images
	images.each(function(image, idx) {
		// start array's current position of at this index in the images array if we have the same src as the displayed non-JS image
		if (productImage.down().readAttribute('src').substring(25) == image.src) cur = idx;
		
		// now insert this image as a real image in that array
		var aObj = { target: '_blank' };
		if (image.link.length) aObj.href = 'http://' + image.link;
		
		productImages.insert(
			new Element(
				'img',
				{
					src:    'media/home_banners_nodel/' + image.src,
					alt:    '',
					width:  707,
					height: 328
				}
			).wrap('a', aObj).wrap('li')
		);
	});
	
	// now scroll to newly created version of that image
	productImages.setStyle({ left: (-707 * cur) + 'px' });
	
	// then get rid of first image
	productImage.up().remove();
	
	// select "current" thumb
	thumbs.each(function(el, idx) {
		if (idx == cur)
			el.addClassName('selected');
		else
			el.removeClassName('selected');
	});
	
	// our functions
	function slideTo(id) {
		// validate id
		id = Math.max(Math.min(images.length - 1, id), 0);
		
		// if going to self, leave it
		if (id == cur) return;
		
		cur = id;
		
		new Effect.Move(
			productImages,
			{
				duration: 0.3,
				mode:     'absolute',
				x:        -707 * cur
			}
		);
		
		$$('#product-thumbs a').each(function(el, idx) {
			if (idx == cur)
				el.addClassName('selected');
			else
				el.removeClassName('selected');
		});
	}
	
	setInterval(function() { var next = cur + 1; if (next >= images.length) next = 0; slideTo(next); }, 6000);
	
});
