var Gallery = function(config) {
	var autoAdvance = (config.autoAdvance !== undefined) ? config.autoAdvance : true;
	var $gallery = $(config.selector);
	var $counter = $gallery.find('li.counter');
	
	var $items = $gallery.find('ul.images li').hide();
	$items.eq(0).show().find('div.quote').show();
	var count = $items.length;
	
	$counter.text('1 of ' + count);
	
	$items.each(function(i) {
		$(this).data('i', i + 1);
	});
	
	$('ul.gallery_nav').show();
	
	var showNext = function() {
		var $current = getCurrentItem();
		var $next = getNextItem($current);
		hide($current, function() { show($next); });
	};
	
	var showPrev = function() {
		var $current = getCurrentItem();
		var $prev = getPrevItem($current);
		hide($current, function() { show($prev); });
	};
	
	var getCurrentItem = function() {
		return $gallery.find('ul.images li:visible');
	};
	
	var getNextItem = function($li) {
		return $li.next().length ? $li.next() : $items.eq(0);
	};
	
	var getPrevItem = function($li) {
		return $li.prev().length ? $li.prev() : $items.eq($items.length - 1);
	};
	
	var hide = function($li, callback) {
		var callback = callback || function() {};
		$li.fadeOut(500, function() {
			$li.find('div.quote').hide();
			callback();
		});
	};
	
	var show = function($li, callback) {
		var callback = callback || function() {};
		$li.fadeIn(1000, function() {
			$li.find('div.quote').fadeIn(1000);
			callback();
		});
		updateCounter($li);
	};
	
	var updateCounter = function($li) {
		var current = $li.data('i');
		$counter.text(current + ' of ' + count);
	};
	
	$gallery.find('li.next')
		.click(function() {
			showNext();
			autoAdvance = false;
		});

	$gallery.find('li.prev')
		.click(function() {
			showPrev();
			autoAdvance = false;
		});
		
	setInterval(function() {
		if (autoAdvance) {
			showNext();
		}
	}, 8000);
	
};

$(document).ready(function() {
	new Gallery({selector : '#subpage div.gallery'});
});

