$(function(){
	$('#banners').gallerify();
	$('#primary li a').navigation();
});

$.fn.gallerify = function(){
	return this.each(function(){
		var timer;
		var container = $(this);
		var images = $('>ul>li',container);
		var nav = $('<ul id="banner_nav"></ul>').appendTo(container);
		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(),10);
			images.filter(':visible').fadeOut(300);
			images.eq(clickedIndex).fadeIn(500);
			nav.children().removeClass('on');
			$(this).parent().addClass('on');
		}
		$('a',nav).click(function(){
			window.clearInterval(timer);
			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));
		},5000);
	});
}

$.fn.navigation = function(){
	return this.each(function() {
		$(this).hover(
			function(e) {
				$('#' + $(this).parent().attr('id').replace('nav', 'secondary')).show().css('z-index', '10');
			}, 
			function(e) {
				$('#' + $(this).parent().attr('id').replace('nav', 'secondary')).hover(
					function() {
						$(this).show().css('z-index', '10');
					},
					function() {
						$(this).hide().css('z-index', 'auto');
					}
				).hide().css('z-index', 'auto');
				$('.secondary').hide().css('z-index', 'auto');
				$('#' + $('body').attr('class').replace('body', 'secondary')).show();
			}
		);
	});
}
