
/* From File: /var/www/www.housetohome.co.uk/web/js/list.js */
/*
	Opens and closes list items
*/
$j = jQuery;	  
$j(document).ready(function() {
	// called when the close buttons are clicked
	// hide the relevant question and reapply a link around the heading text
	function addCloseButtonClickEvent(event) {
		// get references to the containing list item and heading
		var container = $j(this).parents("li");
		var heading = container.find('h2');
			
		addHeadingLink(heading);
		
		// hide the question
		container.addClass("closed");
	}

	// called when a heading links are clicked
	// show the relevant question, remove the link from the heading text and add a close button
	function addOpenFaqClickEvent(event) {
		// add click event to open an FAQ item
		var container = $j(this).parents('li');
		
		addCloseButton(container);
			
		// show the question
		container.removeClass("closed");
		
		removeHeadingLink(this);
	}
	
	// wrap a link round the text of heading
	function addHeadingLink(heading) {
		var headingLink = $j('<a>' + $j(heading).text() + '</a>');
		
		headingLink.click(addOpenFaqClickEvent);
		$j(heading).html(headingLink);
	}
	
	// remove the link from the the text of a heading
	function removeHeadingLink(headingLink) {
		$j(headingLink).parent().replaceWith('<h2>' + $j(headingLink).text() + '</h2>');
	}
	
	// add a close button to a question container
	function addCloseButton(container) {
		var closeButton = $j('<a>Close</a>');
		
		closeButton.addClass('close_item');
		closeButton.click(addCloseButtonClickEvent);
		$j(container).append(closeButton);
	}
	
	// get default shown questions and add close buttons to them
	var openQuestions = $j('.faq_list li[class!=closed]');
	
	openQuestions.each(function(i, element) {	
		addCloseButton(element);	
	});

	// get default hidden questions and add links around the heading text
	var closedQuestions = $j('.faq_list .closed h2');

	closedQuestions.each(function(i, element) {
		addHeadingLink(element);
	});
});

