// prototype library extension - TODO: move to more appropriate place
// source: http://tobielangel.com/bytesandpieces/2006/08/16/extending-prototype-a-better-syntax-for-dom-insertion/
// IE6: all element variables must go through $(), otherwise insertion... methods aren't always defined
Element.addMethods({
	insertionBefore: function(element, content) {
		new Insertion.Before(element, content);
		return $(element.previousSibling);
	},

	insertionTop: function(element, content) {
		new Insertion.Top(element, content);
		return $(element.firstChild);
	},

	insertionBottom: function(element, content) {
		new Insertion.Bottom(element, content);
		return $(element.lastChild);
	},

	insertionAfter: function(element, content) {
		new Insertion.After(element, content);
		return $(element.nextSibling);
	}
});

// prototype library extension defined in domready.js
Event.onDOMReady(function() {
	init_works();
});

function init_works() {

	// find and activate works
	var works = document.getElementsByClassName('work');
	var last_work = works[works.length - 1];

	if (works && works.length > 1) {

		// create the work chooser
		var work_chooser = last_work.insertionAfter('<div id="work_chooser"></div>');

		for (var i = 0; i < works.length; i++) {

			var work = works[i];
			var images = work.getElementsByTagName('img');

			// add a thumbnail and hide the full description if the work has an image
			if (images) {

				// the first image will be the thumbnail
				work.image = images[0];

				// clear the image after every fourth image
				var clear_class = ((i + 1)%4 == 1)?' clearleft':'';

				work.thumbnail = work_chooser.insertionBottom('<img src="' + work.image.src + '" class="thumbnail' + clear_class + '" />');

				// attach click event
				work.thumbnail.work = work;
				work.thumbnail.style.cursor = 'pointer';
				Event.observe(work.thumbnail, 'click', function(e) {
					if (!window.is_animating) {
						show_work(Event.element(e).work, works);
					}
				}, true);

				// hide all works except the first one
				if (i == 0) {
					window.current_work = work;
				}
				if (i > 0) {
					work.hide();
				}
			}
		}
	}
}

function show_work(work) {

	if (work != window.current_work) {

		new Effect.Parallel(
			[
				new Effect.BlindUp(window.current_work, { transition: Effect.Transitions.linear, sync: true }), 
				new Effect.BlindDown(work, { transition: Effect.Transitions.linear, sync: true })
			],
			{
				afterFinish: function(effect) {
					window.is_animating = false;
				} 
			}
		);

		// set global animation state
		window.is_animating = true;
		window.current_work = work;
	}

	// scroll to top
	new Effect.ScrollTo(window, { offset: 0 });
}