jQuery(document).ready(function($){

	$('input.gsc-input').focus(function(){
		$(this).addClass('focused');
	});
	$('input.gsc-input').blur(function(){
		if ($(this).val() == '') {
			$(this).removeClass('focused');
		}
	});


	$('.current-menu-parent').each(function(){
		$(this).closest('.sub-menu').show();
	});


	var tabs = $('section#featured');
	$('body').attr('role','application');
	var tabsNav = $('ul#featured-links');
	var tabsBody = $('ul#featured-content');
	var tabIDprefix = 'tab-';
	var tabIDpostfix = '-tab';
	tabsNav.attr('role', 'tablist');
	$('.tabs-panel').each(function(){
		var tabID = $(this).attr('id');
		$(this)
			.attr('role', 'tabpanel')
			.attr('aria-hidden', true)
			.attr('aria-labelledby', tabIDprefix + tabID)
			.attr('id', tabID + tabIDpostfix);
		
	});
	tabsNav.find('li').each(function(){
		$(this)
			.attr('role','tab')
			.attr('id', tabIDprefix + $(this).find('a').attr('href').split('#')[1]);
	});

	tabsNav.find('a').attr('tabindex', '-1');
		

	function selectTab(tab){
		// tab = tab + tabIDpostfix;
		tabsNav
			.find('li.tabs-selected')
				.removeClass('tabs-selected')
				.find('a')
					.attr('tabindex','-1');
		tab
			.attr('tabindex', '0')
			.parent()
				.addClass('tabs-selected');
			
		$('.tabs-panel')
				.removeClass('tabs-panel-selected')
				.attr('aria-hidden', true);
			
		$( tab.attr('href') + tabIDpostfix)
			.addClass('tabs-panel-selected')
			.attr('aria-hidden', false);

		window.location.hash = tab.attr('href').replace('#','');
		tab[0].focus();
	}

	tabsNav.find('a')
		.click(function(event){
			event.preventDefault();
			// window.location.hash = $(this).attr('href').replace('#','');
			selectTab($(this));
		});

	tabsNav.find('a')
		.keydown(function(event){
			var currentTab = $(this).parent();
			switch(event.keyCode){
				case 37:
				case 38:
					if(currentTab.prev().size() > 0){
						selectTab( currentTab.prev().find('a'));
					}
					break;
				case 39:
				case 40:
					if(currentTab.next().size() > 0){
						selectTab( currentTab.next().find('a'));
					}
					break;
				case 36:
					selectTab( tabsNav.find('li:first a') );
					break;
				case 35:
					selectTab( tabsNav.find('li:last a') );
					break;
				}
		});

	var hashedTab = tabsNav.find('a[href='+ window.location.hash + ']');
	if (hashedTab.size() > 0){
		selectTab(hashedTab);
	}
});
