$(function(){
	
	$('#gallery, .thumb_list').gallerify();
	
});



$.fn.gallerify = function(){
	return this.each(function(){
		
		var timer;
		var container = $('>div',this).length ? $('>div',this) : $(this);
		var images = $('>ul>li',container);
		var nav = $('<ul class="gallery_nav"></ul>').appendTo(container);
		
		images.eq(0).parent().height(images.eq(0).children('img').height());
		
		images.each(function(){
			nav.append('<li><a href="#"><span>'+images.index(this)+'</span></a></li>').children(':first').addClass('on');
		}).not(':first').hide();
		
		var showImage = function() {
			var clickedIndex = parseInt($(this).text(),5);
			images.filter(':visible').fadeOut(600);
			images.eq(clickedIndex).fadeIn(1000);
			nav.children().removeClass('on');
			$(this).parent().addClass('on');
		}
		
		$('a',nav).click(function(){
			window.clearInterval(timer);
			timer = window.setInterval(function(){
			var next = $('.on',nav).next();
			next.length ? showImage.call(next.children('a')) : showImage.call($('a:first',nav));
		},9000);
			showImage.call(this)
			return false;
		});
		
		timer = window.setInterval(function(){
			var next = $('.on',nav).next();
			next.length ? showImage.call(next.children('a')) : showImage.call($('a:first',nav));
		},4000);
		
	});
}
