//jQuery SmoothScroll | Version 10-04-30
$(document).ready(function(){
	$('a[href*=#]').click(function() {
		// duration in ms
		var duration=500;
		// easing values: swing | linear
		var easing='swing';
		
		// get / set parameters
		var newHash=this.hash;
		var target=$(this.hash).offset().top;
		var oldLocation=window.location.href.replace(window.location.hash, '');
		var newLocation=this;
		
		// make sure it's the same location      
		if(oldLocation+newHash==newLocation)
		{
		   // animate to target and set the hash to the window.location after the animation
		   $('html:not(:animated),body:not(:animated)').animate({ scrollTop: target }, duration, easing, function() {
		
		      // add new hash to the browser location
		      window.location.href=newLocation;
		   });
		
		   // cancel default click action
		   return false;
		}
	});
	
	var japagenav = $('#pagenav');
	var janavhelper = $('#ja-navhelper');
	var pages = $('.page-content');
	var pagetitles = $('li.page-link');
	var pageactive = -1;
	
	var pageactivetimeout = 0;
	detectpageactive();
	$(window).bind ('scroll', function () {
		if (pageactivetimeout) clearTimeout(pageactivetimeout);
		pageactivetimeout = setTimeout(detectpageactive, 200);
	});
	
	pagetitles.each (function(i, title) {
		$(title).children('a').bind('click', function (){activetopage(i)});
	});
	
	function detectpageactive () {
	  //detect the active 
	  var scrolltop = $(window).scrollTop();
	  var active = -1;
	  pages.each(function(i, page){
	    var page_position = $(page).position();
	    if ((i==0 || page_position.top <= scrolltop+100)) {
	      active = i;
	      return;
	    }
	  });
	  
	  if (active >=0 && pageactive != active) {
	    activetopage (active);
	  }
	  
	  if (active == -1) {
	    //no active
	    pagetitles.removeClass ('active');
	    pages.removeClass ('active');
	    if (pageactive >= 0) {
	      var theme = pages[pageactive].getProperty('rel');
	      if (theme) japagenav.removeClass (theme);
	    }
	    pageactive = -1;
	  }
	}
	
	function activetopage (active) {
	  if (active == pageactive) return;
	  pagetitles.removeClass ('active');
	  pages.removeClass ('active');
	  $(pagetitles[active]).addClass ('active');
	  $(pages[active]).addClass ('active');
	  
	  //get current theme
	  pageactive = active;
	}
});

