var galleries = [];
var gIndex = [];

window.addEvent('load', init);
window.addEvent('domready', ready);
/*window.addEvent('load', function() {
	// Initialize Lightbox
	Lightbox.init({showControls: true});
});*/

function init() {	
	// Initialize the accordion and display the first item by default
	var accordion = new Accordion('#gallery h1', '#gallery .thumbnails', {
		opacity : true,
		onActive: function(toggler, element) {
			toggler.setStyle('background-color', '#f16925');
		},
		onBackground: function(toggler, element) {
			toggler.setStyle('background-color', '#a6def3');
		}
	}, $('gallery'));
	accordion.display(0);
	
	// get the Fragment Identifier (#) from URL and display
	// the appropriate accordion group
	var fragmentID = location.href.getFragmentIdentifier();
	$$('#gallery h1').each(function(item, index) {
		if (item.id == fragmentID)
			accordion.display(index);
	});
	
	// Initialize Lightbox
	Lightbox.init({showControls: true});
};

function ready() {
	
	// Default preview image and add onMouseOver functionality to thumbnails
	$$('#gallery .thumbnails').each(function(item, index) {
		//alert(item.getFirst().getNext().className);
		var preview = item.getFirst();
		var firstThumb = preview.getNext().getFirst().getFirst();
		var first = firstThumb.getProperty('href').replace(/.jpg/, '_m.jpg');
		//var paths = first.split('/');
		new Element('img', {
			'src': first,
			'alt': ''
		}).injectInside(preview);
		var caption = new Element('div', {
			'class': 'caption'
		});
		caption.setText(firstThumb.getProperty('title').substring(0, firstThumb.getProperty('title').indexOf('<br/>')));
		caption.injectInside(preview);
	});
	
	$$('#gallery .thumbnails .thumb img').each(function(item, index) {
		item.addEvent('mouseenter', function(e) {
			var par = e.target.getParent().getParent().getParent().getParent().getFirst();
			par.getFirst().remove();
			par.getFirst().remove();
			var path = item.getParent().getProperty('href').replace(/.jpg/, '_m.jpg');
			//var paths = item.getParent().getProperty('href').split('/');
			new Element('img', {
				'src': path,
				'alt': ''
			}).injectInside(par);
			var caption = new Element('div', {
				'class': 'caption'
			});
			caption.setText(item.getParent().getProperty('title').substring(0, item.getParent().getProperty('title').indexOf('<br/>')));
			caption.injectInside(par);
		});
	});
}

String.extend({
	getFragmentIdentifier: function() {
		return o = this.split('#')[1];
	}
});