YUI().use('node', 'node-event-simulate', 'cookie', function(Y){
	
	function rebuildTopicFilters()
	{
		var filter_container = Y.one('#faq_topics ul');
		
		filter_container.get('children').each(function(v){
			var anchor_tag = v.get('firstChild');
			var anchor_text = Y.Node.getDOMNode(anchor_tag);
			var id = anchor_tag.get('id');
			var text = anchor_tag.get('firstChild');
			var input = Y.Node.create('<input type="checkbox" name="topic" class="topic_checkbox" value="'+id+'" checked="checked" id="'+id+'" />');
			var label = Y.Node.create('<label for="'+id+'">'+anchor_text.innerHTML+'</label>');
			v.replaceChild(input, anchor_tag);
			v.appendChild(label);
		});
	}

	function selectQuestion(id, for_cookies)
	{
		var question = Y.one('#'+id);
		if(question != null)
		{
			var parent = question.ancestor('.question_answer');
			if(parent != null)
			{
				if(for_cookies)
				{
					question.simulate('click');
				}
				else if(parent.hasClass('closed'))
				{
					question.simulate('click');
					
				}
			}			
		}
	}

	function initCookies()
	{
		var cookies = Y.Cookie.get('open_faqs');
		if(cookies)
		{
			var current_questions = new Array();
			current_questions = Y.Cookie.get('open_faqs').split(',');
			for(var i=0; i<current_questions.length; i++)
			{
				selectQuestion(current_questions[i], true);
			}

		}
		else
		{
			Y.Cookie.set('open_faqs', new Array());
		}
	}

	var showHideTopic = function(e)
	{
		var checked = e.currentTarget.get('checked');
		var value = e.currentTarget.get('value');
		value = value.replace('topic_','');
		var question_group = Y.one('.group_'+value);
		if(checked)
		{
			question_group.removeClass('hidden');
		}
		else
		{
			question_group.addClass('hidden');
		}
		
	}

	var initFaq = function(id)
	{
		rebuildTopicFilters();
		Y.all('.question p').each(function(v){
			v.addClass('pointer');
		});
		Y.all('.topic_checkbox').on('click', showHideTopic);

		initCookies();
		var hash = window.location.hash;
		if(hash != '')
		{
			var index = hash.indexOf('#question_');
			var id = hash.substr(index+1);
			//scroll to question with YUI
			Y.one('#'+id).scrollIntoView(true);
			selectQuestion(id, false);
		}

	}
	
	Y.on('available', initFaq, '#faq_topics', this);
	Y.on('click', function(e){
		e.preventDefault();

		Y.all('.eu_toggle_box .hd').each(function(v, k){
			if (e.currentTarget.get('id') == 'expand_all' && v.ancestor('div').hasClass("closed")){
				v.simulate("click");
			}
			else if(e.currentTarget.get('id') == 'collapse_all' && !v.ancestor('div').hasClass("closed") ){
				v.simulate("click");
			}
		});
	},'#expand_all,#collapse_all');
	
});

