// Gc.js

$(document).ready(function() {
	handleTabs();
});

function handleTabs() {
	$('ul.tabs:not(.staticTabs) li:first-child').addClass('current'); // Add class	
	
	var startingPoint = false;
	
	$('ul.tabs').each(function(index, element){ // Hide all sections except the first ones
		startingPoint = $(element).parent()
		var counter = 0;
		while(startingPoint.children('.tabSection').length == 0 && counter <= 3) {
			startingPoint = startingPoint.parent();
			counter++;
		}
	});
	
	if (location.hash.length > 1) {
		$('ul.tabs a').each(function(i) {
			var value = $(this).text();
			if ('#'+value.toLowerCase().replace(/ /g, '-') == location.hash) {
				var target = $(this);
				target.parents('li').addClass('current').siblings().removeClass('current');
				target.parents('ul').parent().children('.tabSection').eq(i).show().siblings('.tabSection').hide();
			}
		});
	}
	
	if (startingPoint && location.hash.length < 1 || $('.tabSection:visible').length > 1) {	
		startingPoint.children('.tabSection:not(:first)').hide();
	}
	
	$('ul.tabs li a:not([rel=notab])[href=#]').click(function(e){
		// change the 'current' class
		e.preventDefault();
		var a = $(e.target);
		var li = a.parent();
		var container = li.parent().parent();
		var lastChosen = li.siblings('.current');
		li.siblings().removeClass('current');
		li.addClass('current');
		
		// find the tab sections.
		var sections = container.children('.tabSection');
		var counter = 0;
		var moved = false;
		while (container.children('.tabSection').length == 0 && counter <=3) {
			container = container.parent();
			counter++;
			moved = true;
		}
		sections = container.children('.tabSection');
		
		// which link did you click?
		var newIndex = 0;
		li.parent().children().each(function(index, child){
			if($(child).text() == li.text()) {
				newIndex = index;
			}
		});
		if (newIndex>=sections.length) {
			newIndex = -1;
			// li.removeClass('current');
			// lastChosen.addClass('current');
		}
		// if we found sections outside of our container, only switch the sections if you can't find another ul.tabs
		if (moved && container.children('.tabs, .smallTabs').length == 0 || ! moved) {
			if (newIndex >=0) {
				sections.hide();
				sections.eq(newIndex).show();
			}
		}
		
		updateURL();
	});
	
}
	
function updateURL() {
	location.hash = $('.tabs .current a, .smallTabs .current a').eq(0).text().toLowerCase().replace(/ /g, '-');
}
