jQuery.fn.brightgallery = function(options) {

	// default settings
	var options = jQuery.extend({
		galleryWrapperId: 'home_gallery',
		galleryIntervalId: 0,
		prevLinkId: 'prev_link',
		nextLinkId: 'next_link',
		activeLI: '',
		nextLI: '',
		prevLI: '',
		animateCaption: true,
		captionHeight: '100',
		showControls: true
	}, options);
	 
	return this.each(function() {
		if (options.animateCaption) {
			$('#' + options.galleryWrapperId + ' li span').css({opacity: '0.9'});
			$('#' + options.galleryWrapperId + ' li:not(.active) span').css({'bottom': '-' + options.captionHeight + 'px'});
		}
		
		if ($('#' + options.galleryWrapperId + ' li').length > 1) {
			// create next/prev links and create onclick events
			if (options.showControls) {
				$('<a href="#" id="' + options.prevLinkId + '">Previous</a>')
					.click(function(evt) {
						evt.preventDefault();
						clearInterval(options.galleryIntervalId);
						showPrev();
						return false;
					})
					.appendTo($('#' + options.galleryWrapperId));
					
				$('<a href="#" id="' + options.nextLinkId + '">Next</a>')
					.click(function(evt) {
						evt.preventDefault();
						clearInterval(options.galleryIntervalId);
						showNext();
						return false;
					})
					.appendTo($('#' + options.galleryWrapperId));
			}
			options.galleryIntervalId = setInterval( showNext, 5000 );
		}
	});
	
	function showNext() {
		options.activeLI = $('#' + options.galleryWrapperId + ' li.active');
		options.nextLI = $(options.activeLI).next().length ? $(options.activeLI).next() : $('#' + options.galleryWrapperId + ' li:first');

	    if ( $(options.activeLI).length == 0 ) options.activeLI = $('#' + options.galleryWrapperId + ' li:last');

	    fadeListItem(options.nextLI);
	}
	
	function showPrev() {
		options.activeLI = $('#' + options.galleryWrapperId + ' li.active');
		options.prevLI = $(options.activeLI).prev().length ? $(options.activeLI).prev() : $('#' + options.galleryWrapperId + ' li:last');
		
		if ( $(options.activeLI).length == 0 ) options.activeLI = $('#' + options.galleryWrapperId + ' li:first');
		
		fadeListItem(options.prevLI);
	}
	
	function fadeListItem(listItem) {
		$(options.activeLI).addClass('last_active');
		
		if (options.animateCaption) {
		    $(options.activeLI).children().filter('span').eq(0).animate({opactity: '0.0'}, 1000, function() {
		    	$(this).css({bottom: '-' + options.captionHeight + 'px'});
		    });
		}
		
		$(listItem).css({opacity: 0.0})
	        .addClass('active')
	        .animate({opacity: 1.0}, 1000, function() {
	        	$(options.activeLI).removeClass('active last_active');
	        });
	    
	    if (options.animateCaption) {
			$(listItem).children().filter('span').eq(0)
		        .css({opacity: 1.0})
		        .animate({opacity: 1.0}, 500, function() {
		        	$(this).animate({bottom: '0', opacity: '0.9'}, 400);
		        });
		}
	}
};