/* 
 *	Image gallery LIBRARY. As on http://universeBDSM.com
 *  (c) Valloir
 */
 

var getSlide = function(gallery) {

}

var gotoSlide = function(gallery, n) {
	if(typeof(n) == "string") {
		switch(n) {
			case "next":
				if($(gallery).find('li.active').length != 0)
					if($(gallery).find('li.active').next().length != 0)
						n = $(gallery).find('li.active').prevAll().length + 1;
					else
						n = 0;
				else
					n = 0;
				break;
			case "prev":
				if($(gallery).find('li.active').length != 0)
					if($(gallery).find('li.active').prev().length != 0)
						n = $(gallery).find('li.active').prevAll().length - 1;
					else
						n = $(gallery).find('li').length - 1;
				else
					n = $(gallery).find('li').length - 1;
				break;
			default: n = 0; break;
		}
	}
	var total_slides = $(gallery).find('li').length;
	if(n >= total_slides || n < 0)
		return false;
	$(gallery).find('.current').html(n + 1);
	$(gallery).find('li:not(:eq(' + n + '))').removeClass('active').animate({'opacity': 0.6});
	$(gallery).find('li:eq(' + n + ')').addClass('active').animate({'opacity': 1});
	var offset = 0;
	$(gallery).find('li').each(function(i) {
		if(i>=n) return false;
		offset += parseInt($(this).outerWidth());
	});
	offset += parseInt($(gallery).find('li:eq('+n+')').width()) / 2;	//if(n != 0)
	offset -= parseInt($(gallery).parents('.slideshow').width()) / 2;
	if(n == 0)		$(gallery).find('ul').animate({'margin-left': 0});	else		$(gallery).find('ul').animate({'margin-left': -offset});
};

var createGallery = function(slides, extra_class) {
	if(typeof(extra_class) == 'undefined')
		extra_class = "";
		
	var total_slides = slides.length;
	var gal = $(
		'<div class="gallery ' + extra_class + '">' +
			'<div class="nav">' +
				'<span class="current">1</span> of <span class="total">' + total_slides + '</span>' + 
				'<span class="prev">&lt; previous</span> &nbsp; <span class="next">next &gt;</span>' +
				'<a class="back btn-back-to">&lt; back to galleries</a>' + 
			'</div>' + 
			'<ul></ul>' +
			'<div class="clear"></div>' +
		'</div>'
	);
	
	// Add the slides
	$(slides).each(function() {
		gal.find('ul').append("<li><img src='" + this.image + "' alt='" + this.alt + "'></li>");
	});
	
	// Setup the navigation
	gal.find('.next').click(function() {
		gotoSlide($(this).parents('.gallery'), 'next');
	});
	gal.find('.prev').click(function() {
		gotoSlide($(this).parents('.gallery'), 'prev');
	});		
	gal.find('li').click(function() {
		if(!$(this).is('.active')) {
			gotoSlide($(this).parents('.gallery'), $(this).prevAll().length);
		}
		else {
			gotoSlide($(this).parents('.gallery'), $(this).prevAll().length+1);
		}
	});		
	
	gotoSlide(gal, 0);
	return gal;
}
