$(document).ready(function() {
	
	function getAnchorFromHref(href) {
		if(href.indexOf('#') !== -1) {
			var name = href.split('#').pop();
			var anchor = $('a[name=' + name + ']');
			return anchor;
		} else {
			return false;
		}
	}
	
	function showNewsBar() {
		$('.newsbar').removeClass('closed');
		$('.header').css('margin-top', 22);
		var m = $('.highlight').css('margin-top').replace('px', '');
		$('.highlight').css('margin-top', m*1 + 21);
	}
	
	function hideNewsBar() {
		$('.newsbar').addClass('closed');
		$('.header').css('margin-top', 0);
		var m = $('.highlight').css('margin-top').replace('px', '');
		$('.highlight').css('margin-top', m*1 - 21);
	}

	
	/* news bar */
	$('.newsbar .close').click(function() {
		hideNewsBar();
		return false;
	});
	
	$('.newsbar a[class!=close]').click(function() {
		if(typeof(_gaq) !== 'undefined') {
			_gaq.push(['_trackEvent', 'NewsBarLink', this.href]);
		}
		return true;
	});

	function smoothScroll(href) {
		var name = href.split('#').pop();
		var anchor = $('#' + name);
		
		if(anchor.length == 0) {
			return false;
		}
		var headerHeight = $('.header').height();
		var anchorOffset = $(anchor).offset().top - headerHeight;
		var onComplete = null;

		if(window.history.pushState) {
			onComplete = function() {
				window.history.pushState(null, null, '#' + name);
			}
		} else {
			onComplete = function () {
				window.location.hash = name;
			}
		}
		$('html,body').stop().animate({scrollTop: anchorOffset}, 500, onComplete);

		$('.header li').removeClass('selected');
		$('.header li a[href="#'+name+'"]').parent().addClass('selected');
		

	}
	
	// Smooth scroll to sections
	$('.header li a[href*=#]').click(function(event) {
		event.preventDefault();
		smoothScroll(this.href);
	})
	
	setTimeout(function() {
		showNewsBar();
		var href = window.location.href;
		
		if(href.indexOf('#') !== -1) {
			smoothScroll(href);
		}
		
	}, 600);

});

