window.$ = jQuery;

function readURLAnchor(){
	faq_id = self.document.location.hash.substring( 1 );
	if( faq_id != "" && !isNaN(faq_id) ) { /* Make sure it's a number, and not just a section jump */

		if( $( "#faq_container #faq_" + faq_id ).length == 0 ){
			// No matching FAQ content ID was found. So maybe the user
			// is using an old forum based ID in the URL
			if( $( "div[oldForumThreadId = '" + faq_id + "']" ).length > 0 ){
				faq_id = $( "div[oldForumThreadId = '" + faq_id + "']" ).attr( "id" );
				faq_id = faq_id.replace(/faq_container_/, "");
			}
			else faq_id = "";
		}
		if( faq_id != "" ){
			area_id = $( "#faq_container #faq_" +  faq_id ).attr( "area_id" );
			showFAQ( faq_id, true );
		}

	} else {
		/* If we don't have an FAQ id, turn them all off */
		turnOffFAQs();
	}
	attachFAQLinks();
}

function attachFAQLinks() {
	$("h3.faq_subject").click(function() {
		heading = $(this);
		faq_id = heading.attr('id').replace(/faq_heading_/, '');
		self.document.location.hash = faq_id;
		showFAQ(faq_id, true);
	});
}

function showFAQ( faq_id, scroll ){
	if(typeof scroll == "undefined") {
		scroll = true;
	}

	showFAQSection( "faq", faq_id );
	setFAQSelectedItem( "faq_container", faq_id );

	if(scroll) {
		$.scrollTo( "#faq_container_" + faq_id, { offset: { top:-100 } } );
	}

}

function turnOffFAQs() {
	$(" .faq_content_container ").css('display', 'none');
}

function setFAQSelectedItem( name, id ){
	name_and_id = name + "_" + id;
	name_selected = name + "_selected";

	changeFAQStyleClass( name, name_and_id, name, name_selected );
}

function changeFAQStyleClass( element_set_class_name, selected_element_id, unselected_class_name, selected_class_name ){
	$( "#faq_container ." + element_set_class_name ).removeClass( selected_class_name );
	$( "#faq_container ." + element_set_class_name ).addClass( unselected_class_name );
	$( "#faq_container #" + selected_element_id ).addClass( selected_class_name );
}

function showFAQSection( section_type, section_id ){
	$( "#faq_container ." + section_type + "_content_container" ).css( "display", "none" );
	$( "#faq_container #" + section_type + "_" + section_id ).css( "display", "block" );
}

function checkFAQLoadability(site) {

	faq_id = self.document.location.hash.substring( 1 );
	if(!faq_id) return false;

	$.post('/parts/faq/load/' + faq_id, {}, function( responseText ) {
		if(site == 'scratchlive') {
			// Since Scratchlive.net has those freaky title div wrappers around the h1's,
			// We'll need to remove the one that's currently in there before putting our
			// AJAX one in, otherwise we'll have two... and it'll look silly
			h1Content = $('.title h1:first').text();
			responseText += "<h1>" + h1Content + "</h1>";

			$('.title').remove();
		}
		$('#content').prepend(responseText);
	});
	
}

$(document).ready( readURLAnchor );
