// requires: eventHelper.js

// define the element node type since it it not predefined cross-browser
var ELEMENT_NODE = 1;

// define css class names for the faq components
var FAQ_QUESTION_CSSCLASS = "faqQuestion";
var FAQ_QUESTIONTEXT_CSSCLASS = "faqQuestionText";
var FAQ_ANSWER_CSSCLASS = "faqAnswer";

// structure your HTML like the following in order for this script to work:
/*
<div id="faq">
	<div class="faqQuestion">
		<div class="faqQuestionText">
			<div><strong><a href="javascript:;">[FAQ QUESTION TEXT HERE]</a></strong></div>
		</div>
		<div class="faqAnswer">
			[FAQ ANSWER TEXT HERE]
		</div>
	</div>
	<div class="faqQuestion">
		... repeat as above for as many questions as you have
	</div>
	<div class="faqQuestion">
		... repeat as above for as many questions as you have
	</div>
</div>
*/

// add the following line to your faq after the faq contents in your HTML:
//faq_init('faq');

// initialize the faq questions
function faq_init(id) {
	faq_toggleAll(id, false, true);
}

// function to tie to the event handlers for the title links to toggle
// the display of the answer text
function faq_toggleActivate(evt) {
	faq_toggleQuestion(getEventSource(evt), true, null);
	return false;
}

function faq_toggleAll(id, show, init) {
	var faq = document.getElementById(id);

	// loop through the questions
	for (var q = 0; q < faq.childNodes.length; q++) {
		var question = faq.childNodes[q];
		if (question.nodeType == ELEMENT_NODE && question.className == FAQ_QUESTION_CSSCLASS) {
			
			// add the toggle event handlers
			for (var qt = 0; qt < question.childNodes.length; qt++) {
				var questionText = question.childNodes[qt];
				if (questionText.nodeType == ELEMENT_NODE && questionText.className == FAQ_QUESTIONTEXT_CSSCLASS) {
					
					if (init) {
						var link = questionText.getElementsByTagName("a")[0];
						addEvent(link, "click", faq_toggleActivate, false);
						addEvent(link, "keypress", faq_toggleActivate, false);
					}
				}
			}

			// hide the answers, initially
			faq_toggleQuestion(question, false, show);
	
		}
	}
}

function faq_toggleQuestion(question, findParent, show) {
	// find the faq question element as a parent of the first argument.
	// this way, we don't have to specify ids.
	if (findParent) {
		var parent = question.parentNode;
		while (parent && 
				(parent.nodeType != ELEMENT_NODE || 
				(parent.nodeType == ELEMENT_NODE && parent.className != FAQ_QUESTION_CSSCLASS))) {
			parent = parent.parentNode;
		}
		if (parent) {
			question = parent;
		}
	}
	
	// find and toggle the answer element
	for (var a = 0; a < question.childNodes.length; a++) {
		var answer = question.childNodes[a];
		if (answer.nodeType == ELEMENT_NODE && answer.className == FAQ_ANSWER_CSSCLASS) {
			
			answer.style.display = (show || (show == null && answer.style.display == "none") ? "block" : "none")
			
		}
	}
}
