/* FAQMachine Javascript Effects (requires jQuery) */
/* by White Whale Web Services */
var questions,lastquery='',matches,resultsdiv;

$(document).ready(function() {
//	$('#faqmachine_query').after('<div id="debug"></div>');
	matches = questions = $('.widget_faq>ul>li').each(function() {
		$.data(this,'keywords',($(this).find('.faq_question').get(0).innerHTML).toLowerCase().replace(/[,-\/]/g,' ').replace(/[^a-zA-Z 0-9]+/g,''));
		$(this).hide();
	}); // grab questions, attach data to match against, hide questions
	answers = $('.faq_answer').hide(); // grab and hide the questions/answers
	$('.widget_faq .faq_question').click(function() { $(this).next().slideToggle() }); // add onclick for question titles
	$('#faqmachine_query').attr('autocomplete','off').keyup(function() { // on each keypress, filter the questions
		var query = $.trim($(this).val().toLowerCase().replace(/[,-\/]/g,' ').replace(/[^a-zA-Z 0-9]+/g,'')),subquery;
		if(query==lastquery) return; // do nothing if the query is unchanged
		if(lastquery.length==0) hideMFAQ();
		matches.hide(); // hide the questions
		answers.hide(); // collapse the answers
//		$('#debug').html('"'+lastquery+'"->');
		if(query.indexOf(lastquery)!=0) {  // if this query is not a subset of the last query, reinitialize the matches and search on all terms
			matches = questions;
			subquery = query;
		} else subquery = query.substring(query.lastIndexOf(' ')+1,query.length); // if this query is a subset of the last query, no need to search the last query's terms
		if(query.length==0) { showMFAQ(); lastquery=''; return; } // return no results if there is no query
		lastquery=query;
//		$('#debug').append(query + '"<br/>Searched <strong>'+matches.length+'</strong> questions using <strong>"'+subquery+'"</strong>...');
		$.each(subquery.split(' '),function() { // filter the result for each word in the query
			var search = this;
//			$('#debug').append('<br/><em>'+this+':</em><br/>');
			matches = matches.filter(function() {
//				$('#debug').append('<div style="color:'+((' ' + $.data(this,'keywords')).indexOf(' ' + search)>=0 ? '#2c2' : '#c22')+'">"<strong>'+search+'</strong>" in "<strong>' + $.data(this,'keywords') + '</strong>"</div>');
				return (' ' + $.data(this,'keywords')).indexOf(' ' + search)>=0;
			});
		});
//		$('#debug').append('... found <strong>'+matches.length+'</strong> matches.');
		if(matches.length<=15) matches.show();
		else if(matches.length) return;
	});
	$('.widget_faq').prepend('<h4 id="mfaq">Most Frequently Asked Questions</h4>');
	showMFAQ();
});

function showMFAQ() { $('#mfaq,.mfaq').show(); }
function hideMFAQ() { $('#mfaq,.mfaq').hide(); }