/**
 * Photo gallery script
 * @author Derek Beumer <derek@thoughtstack.net>
 * @copyright Copyright (c) 2008, Derek Beumer
 * @version $Id$
 * @package lahmayer
 */

var photos = {
	firstAnchor: null,
	helpMessageDiv: null,
	init: function () {
		photos.helpMessageDiv = new Element('div');
		/*photos.helpMessageDiv.insert('<ol><li>Drag the mouse over a thumbnail to expand.</li><li>Click a thumbnail to pin the expanded photo.</li><li>Click the expanded photo for a full view.</li></ol>');*/

		var breaks = $$('.gallery br');

		for (var i = 0; i < breaks.length; i++) {
			breaks[i].style.display = 'none';
		}

		var anchors = $$('.gallery a');
		photos.firstAnchor = anchors[0];

		anchors.each(function (anchor) {
			anchor.full = new Element('img');
			anchor.full.observe('load', photos.handleAnchorImageLoad.bindAsEventListener(anchor.full));
			anchor.full.src = photos.filterThumbnail(anchor.childElements()[0].src);

			if (anchor === photos.firstAnchor) anchor.full.first = true;

			//anchor.observe('click', photos.handleAnchorClick.bindAsEventListener(anchor));
			anchor.observe('mouseover', photos.handleAnchorMouseOver.bindAsEventListener(anchor));
			//anchor.observe('mouseout', photos.handleAnchorMouseOut.bindAsEventListener(anchor));

			anchor.href = 'javascript: void(0);';
		});
	},
	handleAnchorClick: function (event) {
		photos.refreshPreview(this, true);
	},
	handleAnchorMouseOver: function (event) {
		photos.refreshPreview(this, false);
	},
	handleAnchorMouseOut: function (event) {
		photos.refreshPreview(null, false);
	},
	handleAnchorImageLoad: function (event) {
		var img = this;
		var ratio;

		if (img.height > 300) {
			ratio = 300 / img.height;

			img.width = img.width * ratio;
			img.height = 300;
		}

		if (img.width > 600) {
			ratio = 600 / img.width;

			img.width = 600;
			img.height = img.height * ratio;
		}

		if (img.first) {
			photos.refreshPreview(photos.firstAnchor);
		}
	},
	displayHelpMessage: function () {
		$('preview-box').update(photos.helpMessageDiv);
	},
	refreshPreview: function (anchor) {
		if (anchor) {
			var previewAnchor = new Element('a');

			previewAnchor.id = 'preview-anchor';
			previewAnchor.href = anchor.full.src;
			previewAnchor.insert(anchor.full);

			$('preview-box').update(previewAnchor);
		}
	},
	filterThumbnail: function (url) {
		return url.sub(/\-\d+x\d+\./, '.');
	}
};

Event.observe(document, 'dom:loaded', photos.init);
