/**
 * Photo Gallery
 * Company: SiteCrafting (http://sitecrafting.com)
 * Author: Paul Sayre
 * Version: 1.0
 * Created: 2008-10-21
 * Updated: 2008-10-21
 * Dependicies: jQuery (1.2.6+)
 *
 * API:
 *	- Most functions can be chained
 *		Example: (new PhotoGallery('gallery')).select('random').duration(.5);
 *
 * new PhotoGallery(id):
 *	- Creates the photo gallery and initializes the actions for the gallery
 *	- Returns: Photo Gallery Object
 *
 * select(index):
 *	- Selects the photo to be shown
 *	- A tranition will occure if the dom is loaded, other way it sets the first photo
 *	- Use select('random') to switch to a random photo
 *	- Returns: Photo Gallery Object
 *
 * count():
 *	- Returns: Number of photos in the gallery
 *
 * duration(speed):
 *	- Sets the duration of the transition between photos (in seconds, can be decimal)
 *	- Returns: Photo Gallery Object
 *
 **/
var PhotoGallery = function(id) {
	var $ = jQuery; // To get around noConflict issue
	var galID = '#'+id;
	var dur = 1000;
	var last;
	var curr;
	var inTrans = false;
	var start = 0;
	var index = start;

	// Setup actions
	var init = function() {
		var photos = $(galID+' .photo').get();
		var thumbs = $(galID+' .thumb').get();
		for(var i=0; i<photos.length; i++) {
			$(thumbs[i]).data('photo', photos[i]);
			$(photos[i]).data('thumb', thumbs[i]);
		}
		$(galID+' .thumb')
			.hover(function() {
				$(this).addClass('hover');
			}, function() {
				$(this).removeClass('hover');
			})
			.click(function() {
				trans($(this).data('photo'));
			});
		last = photos[start];
		$(last).show();
		$(thumbs[start]).addClass('selected');
		index = start;
		start = true;
		return this;
	};
	$(init);
	
	// Transition from one photo to next
	var trans = function(photo) {
		if(inTrans || last == photo) return false;
		inTrans = true;
		$(last).fadeOut(dur);
		$(photo).fadeIn(dur, function() {inTrans = false;});
		last = photo;
		$(galID+' .thumb').removeClass('selected');
		$($(last).data('thumb')).addClass('selected');
		return true;
	};
	
	// Select the photo to transition to (or "random")
	var select = function(newIndex) {
		if(newIndex == undefined) return index;
		index = newIndex == 'random' ? getRandomIndex() : newIndex;
		index %= $(galID+' .photo').length;
		if(start === true) trans($(galID+' .photo:eq('+index+')'));
		else start = index;
		return this;
	};
	
	// Count the number of photos
	var count = function() {
		return $(galID+' .photo').length;
	};
	
	// Set the duration of the transition
	var duration = function(speed) {
		dur = speed * 1000;
		return this;
	};
	
	// Get a random photo's index
	var getRandomIndex = function() {
		var total = count();
		if(total < 2) return index;
		do {
			var newIndex = Math.floor(Math.random() * total);
		} while(newIndex == index && index != start);
		return newIndex;
	};
	
	// Public functions/variables
	return {
		select: select,
		count: count,
		duration: duration
	};
};