$(document).ready(function(){

	//Hide all solutions initially
	$('div.solution').hide();
	
	//Show/Hide link logic
	$('a.question').click(function($event){
		$event.preventDefault();
		if($(this).parent('li').hasClass('visible')){
			$(this).parent('li').removeClass('visible').find('div').fadeOut(200);
		}else{
			$(this).parent('li').addClass('visible').find('div').fadeIn(200);
			var id = $(this).parent('li').attr('id');
			updateCount(id);
		}
	});
	
	//Get categories from drop-down
	$('#category').change(function(){
		category = $(this).attr('value');
		$('li.item').each(function(){
			$('div.solution').hide();
			if($(this).hasClass(category) || category == 'all'){
				$(this).show();
			}else{
				$(this).hide();
			}
		});
	});
	
	$('#showAll').click(function(event){
		event.preventDefault();
		$('div.solution').fadeIn(200).parent('li').addClass('visible');
	});

	$('#hideAll').click(function(event){
		event.preventDefault();
		$('div.solution').fadeOut(200).parent('li').removeClass('visible');
	});
	
	$('img.print').click(function(){
		//create new document
		var printer = window.open("about:blank");
		var question = $(this).parent('div').prev('a').text();
		var answer = $(this).prev('p').html();
		var head = "<html><body onLoad=window.print();window.close();>"		
		var page = head+"<h3>"+question+"</h3><p>"+answer+"<p></body></html>";
		printer.document.write(page);
		printer.document.close();
	});
});

function updateCount(qID){
	$.ajax({
		url: "faq/count.php",
		type: "GET",
		cache: false,
		data:{id:qID},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			handleError(XMLHttpRequest, textStatus, errorThrown);
		}
	});
}

function handleError(XMLHttpRequest, textStatus, errorThrown){
	var errorText = '<h3>There was a problem loading the page</h3>';
	errorText += '<p>XMLHttpRequest: '+XMLHttpRequest+'</p>';
	errorText += '<p>textStatus: '+textStatus+'</p>';
	errorText += '<p>errorThrown: '+errorThrown+'</p>';
	//console.log(errorText);
}