/**
 * Album.js - Simple album class
 * 
 * @author  Webstores <info at webstores dot nl>
 *           Copyright (c) Webstores internet totaalbureau <http://www.webstores.nl/>
 */

var PhotoAlbum = function(element, images, options) {
	
	var el;
	var imgs;
	var overlay;
	var current;
	
	/**
	 * Get the index of the current image
	 * 
	 * @return {Number} The current index
	 */
	var getCurrentIndex = function() {
		return imgs.indexOf(current);
	};
	
	/**
	 * Prepare the previous image
	 */
	var prevImage = function() {
		WS.show(overlay);
		
		var prev;
		if(current == imgs.first()) {
			prev = imgs.last();
		}
		else {
			prev = imgs[getCurrentIndex() - 1];
		}
		
		setImage(prev);
	};
	
	/**
	 * Prepare the next image
	 */
	var nextImage = function() {
		WS.show(overlay);
		
		var next;
		if(current == imgs.last()) {
			next = imgs.first();
		}
		else {
			next = imgs[getCurrentIndex() + 1];
		}
		
		setImage(next);
	};
	
	/**
	 * Display the given image
	 * 
	 * @param {Object} obj The image object
	 */
	var setImage = function(obj) {
		current = obj;
		
		WS.Event.addEvent(el, 'load', function() {
			setTimeout(function() {
				WS.hide(overlay);
			}, 100);
		});
		
		WS.setText('photo-title', obj.title);
		WS.setText('photo-caption', WS.DOM.getChild(obj, 1).alt);
		
		// We need to set src after we add the onload event, see:
		// http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called
		el.src = obj.href;
	};
	
	/**
	 * Initialize the photo album
	 */
	var initialize = function() {
		el = $(element);
		imgs = WS.Util.collectionToArray(images);
		overlay = $('loading-overlay');
		current = imgs[0];
		
		for(var i = 0; i < imgs.length; i++) {
			WS.Event.addEvent(imgs[i], 'click', function(e) {
				WS.Event.stopEvent(e);
				WS.show(overlay);
				setImage(this);
			});
		}
		
		if(options.initial) {
			setImage(imgs[options.initial]);
		}
		else {
			WS.hide(overlay);
		}
	}();
	
	
	/**
	 * Public API
	 */
	return {
		prev: function() {
			prevImage();
		},
		
		next: function() {
			nextImage();
		}
	};
};
