var twdImageGallery = Class.create({
  initialize: function(element) {
    var defaults = {
      scrollAmount: 3
    };
    var options = Object.extend(defaults, arguments[1] || { });
    this.options = options;
    this.element = $(element);
		this.thumbs = $$('#' + this.element.id + ' .thumbs img');
		this.thumbHeight = this.thumbs[0].getHeight();
		this.image_count = $$('#' + this.element.id + ' .thumbs img').length;
		this.max_offset = this.image_count * this.thumbHeight;
		this.track = $$('.thumbnail_track')[0];
		this.track.setStyle({
			position: 'absolute',
			zIndex: 0
		});
		this._attachEvents();
		this.setArrows();
  },
  
	_attachEvents: function() {
		var handle_top = $("thumbs_up");
		var handle_bottom = $("thumbs_down");
		handle_top.observe("click", this._clickEventHandler.bindAsEventListener(this));
		handle_bottom.observe("click", this._clickEventHandler.bindAsEventListener(this));
		this.handle_top = handle_top;
		this.handle_bottom = handle_bottom;
		this.thumbs.each(this.thumbClickObserver.bind(this));
	},
	
	_clickEventHandler: function(e) {
		this.currentThumbSlideEvent = e;
		var element = e.findElement();
		var dir = element.id == "thumbs_up" ? "up" : "down"
		this.slideThumbnails(dir);
		this.currentThumbSlideEvent.stop();
	},
	
	thumbClickObserver: function(thumb) {
		thumb.observe("click", this.thumbEventHandler.bind(this));
	},
	
	thumbEventHandler: function(e) {
		var element = e.findElement();
		var image_id = parseInt(element.id.gsub('wa_image_', ''));
		if (!this.currentLoadEvent) {
			this.currentLoadEvent = e;
			this.showOverlay(e);
			this.changeImage(image_id);
		}
	},
	
	showOverlay: function(e) {
		var thumbs_div = $$('.thumbs')[0];
		var element = e.findElement();
		var element_offset = element.cumulativeOffset().top;
		var gallery_offset = this.element.select('.slideshow_container')[0].cumulativeOffset().top;
		var overlay_pos = element_offset - gallery_offset - parseInt(this.element.select('.slideshow_container')[0].getStyle('padding-top'));
		var overlay = new Element("div");
		overlay.setStyle({
			position: 'absolute',
			top: overlay_pos + 'px',
			left: 0,
			zIndex: 1,
			width: '100%',
			height: (this.thumbHeight - 1) + 'px',
			backgroundColor: 'black',
			opacity: 0.7
		});
		var spinner = new Image();
		spinner.src = "/images/spinner.gif";
		spinner.setStyle({borderBottom: 'none', position: 'relative', left: '70px', top: '41px'})
		overlay.update(spinner);
		thumbs_div.insert(overlay);
		this.overlay = overlay;
	},
	
  changeImage: function(image_id) {
		this.loadImage(image_id);
	},
	
	loadImage: function(image_id) {
		if (this.slider && this.slider.parentNode != null) {
			this.slider.remove();
		} else {
			delete this.slider;
		}
		var img = new Image();
		var slide_table = $$('.slide_table')[0];
		slide_table.setStyle({zIndex: 1});
		var new_image_table = new Element("table");
		new_image_table.insert(new Element('tr').insert(new Element('td').insert(img)));
		new_image_table.setStyle({zIndex: 0});
		new_image_table.addClassName('slide_table');
		$$('.slide_image')[0].insert({bottom: new_image_table});
		this.slider = slide_table;
		img.src = '/wa_images/show/' + image_id + '/477x326/image.jpg';
		img.onload = this.showImage.bind(this);
		this.currentLoadingImage = img;
	},
	
	showImage: function() {
		if (this.overlay.parentNode != null) {
			this.overlay.remove();
		} else {
			delete this.overlay;
		}
		var x = $$('.slide_image')[0].getWidth();
		new Effect.Move(this.slider, {x: -1 * x, duration: 0.5, afterFinish: function () {
			if (this.slider.parentNode != null) {
				this.slider.remove();
			} else {
				delete this.slider;
			}
		}.bind(this)});
		this.currentLoadEvent = null;
	},
	
	setArrows: function() {
		this.position = parseInt(this.track.getStyle('top') || 0);
		if (this.position == 0) {
			this.handle_top.addClassName('skip_up_inactive');
			this.handle_top.removeClassName('skip_up');
			this.handle_bottom.addClassName('skip_down');
			this.handle_bottom.removeClassName('skip_down_inactive');
		} else if (this.position > 0 && this.position < this.max_offset) {
			this.handle_top.addClassName('skip_up');
			this.handle_top.removeClassName('skip_up_inactive');
			this.handle_bottom.addClassName('skip_down');
			this.handle_bottom.removeClassName('skip_down_inactive');
		} else {
			this.handle_top.addClassName('skip_up');
			this.handle_top.removeClassName('skip_up_inactive');
			this.handle_bottom.addClassName('skip_down_inactive');
			this.handle_bottom.removeClassName('skip_down');
		}
	},
	
	slideThumbnails: function(direction) {
		var amount = this.options.scrollAmount * this.thumbHeight;
		this.position = parseInt(this.track.getStyle('top') || 0);
		if (direction == 'up') {
			if (-1 * this.position > 0) {
				new Effect.Move(this.track, {
					mode: 'relative', x: 0, y: amount, duration: 0.3,
					afterFinish: function () {
						this.setArrows();
					}.bind(this)
				});
			};
		} else {
			if ((this.position + (-1 * amount)) > -1 * this.max_offset) {
				new Effect.Move(this.track, {
					mode: 'relative', x: 0, y: -1 * amount, duration: 0.3,
					afterFinish: function () {
						this.setArrows();
					}.bind(this)
				});
			};
		};
	}
});

function putToCart (id) {
	new Effect.DropOut(
		$$("#mini_cart_amount span")[0], {
			duration: 0.5,
			afterFinish: function () {
				new Ajax.Request("/wa_shop/add_to_cart/" + id);
			}
		}
	);
	new Effect.Puff(
		'basket_' + id, {
			duration: 0.5, afterFinish: function (){
				Element.show('basket_'+ id )
			}
		}
	);
}

function calculateTotalPrice () {
	var values = $$('.basket td.sum').collect(function (td) {
		return td.innerHTML.replace(/\,/g, '.').replace(/€/g, "");
	});
	var total = values.inject(0, function(acc, n) { return acc + parseFloat(n) })
	$('total_price').update(total.toFixed(2).replace(/\./g, ",") + ' &euro;');
}
