/*
		SimpleFaq 1.0
		2009 Darin Reid
		http://darinreid.com
		
		Requires: jquery-1.3.2.min.js
*/	

jQuery(document).ready(function(){

	// Settings
	var slideSpeed 	= 300; // milliseconds
	var lessLink		= 'Hide answer';
	var topLink			= 'Back to top';
	var faq 				= jQuery('dl.faq');
	
	// The lessLink and topLink controls object
	var controls = '<p class="controls"><a class="lessLink" href="#">' + lessLink + '</a> <a href="#top">' + topLink + '</a></p>';
	
	// Check for the top margin on <dt>s set with css
	var marginTop = faq.children('dt:first').css('margin-top');
	
	// Add "top" anchor to the top of the page
	jQuery('body').prepend('<a name="top"></a>');
	
	// For each question
	faq.children('dt').each(function(){
	
		var question = jQuery(this);
		var answer = question.next('dd');
		var nextQuestion = answer.next('dt');
		
		// Wrap question contents in a link
		question.contents().wrap('<a href="#"></a>');
		
		// Hide answers
		answer.hide();
		
		// Add controls
		answer.append(controls);
		
		// Clicking on a question
		question.click(function(event){
			
			// Prevent default linking behavior
			event.preventDefault();
		
			// If active hide answer, otherwise show answer
			if(question.hasClass('active')){
				hideAnswer(answer);
			} else {
				showAnswer(answer);
			}
		});
	
	});
	
	// Clicking on a lessLink
	jQuery('p.controls').children('p > a.lessLink').click(function(event){
		
		var answer = jQuery(this).parent('p.controls').parent('dd');
		var nextQuestion = answer.next('dt');
		
		// Prevent default linking behavior
		event.preventDefault();
		
		hideAnswer(answer);
	});
	
	function showAnswer(answer){
		
		var question = answer.prev('dt');
		var nextQuestion = answer.next('dt');
		
		// Add active class
		question.addClass('active');
		
		// Slide down
		answer.slideDown(slideSpeed);
		
		// Fix for jumping top margin on next question
		nextQuestion.animate({ marginTop: '0' }, slideSpeed);
	}
	
	function hideAnswer(answer){
	
		var question = answer.prev('dt');
		var nextQuestion = answer.next('dt');
	
		// Remove active class
		question.removeClass('active');
		
		// Slide up
		answer.slideUp(slideSpeed);
				
		// Fixes jumping top margin on next question
		nextQuestion.animate({ marginTop: marginTop}, slideSpeed);
	}

});