(function($){

var ns = "BackToTop";

window[ns] = function () {
  this.root = $('#back-to-top');
  if ( ! this.root.length ) return;
  
  this.hide();
  this.observe();
};

window[ns].prototype = {
  
  hide: function () {
    this.root.fadeOut();
    this.hiding = true;
  },
  
  show: function () {
    this.root.fadeIn();
    this.hiding = false;
  },
  
  observe: function () {
    $(window).scroll( $.proxy( this.scroll, this ) );
    this.root.click( $.proxy( this.click, this ) );
  },
  
  scroll: function ( event ) {
    var scrolltop = $(window).scrollTop();
    if ( scrolltop < 80 ) {
      if ( this.hiding ) return;
      this.hide();
      return;
    }

    var top = scrolltop + $(window).height() - 40;
    var maxTop = $(document).height() - 240;
    if ( top > maxTop ) top = maxTop;
    
    this.root.css('top', top );
    if ( this.hiding ) {
      this.show();
    }
  },
  
  click: function ( event ) {
    $('html, body').animate({scrollTop:0});
    event.preventDefault();
    if ( event && event.target && event.target.nodeName.toLowerCase() == "a" ) event.target.blur();
  }
};

})(jQuery);

