jQuery(document).ready(function($)
{
  // Scrolling anchors: Uses jQuery + hashchange
  function scrollto ( $this )
  {
    if ( ! $this.hash ) return ( "" );
    var $this_hash = $($this.hash);
    if ( ! $this_hash ) return ( "" );
    var $parent1 = $this_hash.closest ( '.noscroll' );
    if ( $parent1.length )
    {
      var $parent2 = $this_hash.closest ( '.scrollto' );
      if ( $parent2.length &&
           $parent2.html().length <= $parent1.html().length )
        $parent1 = "";
    }
    if ( ! $parent1.length &&
         ( location.hostname == $this.hostname || ! $this.hostname ) &&
         location.pathname.replace(/^\//,'') == $this.pathname.replace(/^\//,'') )
      return ( $this_hash );
    else
      return ( "" );
  }

  $(window).bind ( 'hashchange', function(e)
  {
    var $this = location, $this_hash = scrollto ( location );
    if ( $this_hash.length )
    {
      var duration = 1000;    // duration in ms
      var easing = 'swing';   // easing values: swing | linear

      $('html,body').animate( { scrollTop: $this_hash.offset().top },
                              duration, easing );
    }
  });

  if ( ! $(window).scrollTop() ) $(window).trigger ( 'hashchange' );

  $('a[href*="#"]').click ( function(e)
  {
    var $this = this, $this_hash = scrollto ( this );
    // Determine applicable cases:
    if ( ! e.isDefaultPrevented() && $this_hash.length )
    {
      e.preventDefault();

      if ( location.hash == $this.hash )
      {
        // Reclick case is special:
        $(window).trigger ( 'hashchange' );
      }
      else
      {
        // Update history without scrolling:
        var hash = $this.hash.substr(1),
            dummy = $( '' ).css({
                                  visibility: 'hidden',
                                  position: 'fixed',
                                  top: '0px'
                                })
                           .attr ( 'id', hash )
                           .prependTo ( document.body );
        $this_hash.attr ( 'id', '' );
        location.hash = $this.hash;
        dummy.remove();
        $this_hash.attr ( 'id', hash );
      }
    }
  });
});
