$(function() {
	initMenu();
	initBanner();
});

function initMenu() {
	var menu = $('#menu');
	var links = menu.children('li');
	links.each(function() {
		if($(this).children('ul').length) {
			$(this).addClass('tog');
		}
	});
}

function initBanner() {
	//customized for PM site, removed title and slide_menu text
	var slideshow = $('#banner');
	var slides = slideshow.children('a');
	var fadeNum = 0;
	
	//if at least one slide:
	if(slides.length != 0) {
		//wrap each with a div and overlay the title
		slides.each(function() {
			var slide = $(this).detach();
			var wrap = $('<div class="slide" />').appendTo(slideshow);
			wrap.append(slide);
		});
	}
	
	//if more than one slide:
	if(slides.length > 1) {
		//create the menu
		var menu = $('<div class="slide_menu" />').prependTo(slideshow);
		slides.each(function(index) {
			//add buttons for each slide
			if(index == 0) {
				menu.append($('<a href="#" class="active"></a>'));
			} else {
				menu.append($('<a href="#"></a>'));
			}
			//add id's to each slide
			$(this).parent().attr('id', 'slide' + (index + 1));
		});
		//add events to each button
		var buttons = menu.children('a');
		buttons.each(function(index) {
			$(this).click(function() {
				fadeNum = index;
				nextFade();
				return false;					   
			});
		});
		var auto_fade = null;
		function nextFade() {
			if(auto_fade != null) {
				clearInterval(auto_fade);
			}
			var slide_items = $('.slide');
			var fadeLength = slide_items.length;
			//fade out everything except target slide
			$(slide_items).filter(function(index) {
				return index != fadeNum;						 
			}).fadeOut();
			//fade in target slide
			$(slide_items[fadeNum]).fadeIn();
			//set active menu button
			buttons.removeClass('active');
			buttons.eq(fadeNum).addClass('active');
			//find next slide
			if (fadeNum < (fadeLength-1)) {
				fadeNum++;
			} else {
				fadeNum = 0;
			}
			auto_fade = setInterval(nextFade, 7500);
		}
		nextFade();		
	}
}
