// smooth scrolling: replaces scrolling with smooth scrolling (not working for IE)
// example: $(window).smoothScrolling();


(function($) {
  // 
  // private variables
  //
  var _options;
  var _obj;
  var _initialized = false;

  var _tweenRunning = false;
  var _tweenTimer;

  var _scrollSpeed = 0.0;
  var _scrollAccel = 0.8;

  //
  // plugin definition
  //
  $.fn.smoothScrolling = function(options) {
    if($.browser.msie) { // MSIE incompatible
      return this;
    }

    _options = $.extend({}, $.fn.smoothScrolling.defaults, options);
    
    if(!_initialized) { 
      _obj = $(window); //$(this);

      $(_obj).mousewheel(function(event, delta) {
        _scrollHook(event, delta);
       
        event.preventDefault();
        return false;
      });
      _initialized = false;
    }

    return this; 
  };


  //
  // private functions
  //
 
  function disableQTips() {
    try {
      $('.qtip-active').qtip("hide");
      $('.qtip').qtip("disable");
    } catch(e) {};
  }

  function enableQTips() {
    try { 
      $('.qtip').qtip("enable"); 
    } catch(e) {};
  }

  function _scrollHook(event, delta) { 
    //console.log(delta);
    _scrollSpeed -= delta * ($.client.os == 'Mac' ? _options.scrollFactorMac : _options.scrollFactor);

    if (!_tweenRunning) {
      _tweenStart();
    }
  }

  function _tweenStart() {
    if(!_tweenRunning) {
      disableQTips();
      _tweenRunning = true;
      _tweenTimer = window.setInterval(_tweenWork, 20);
    }
  }
 
  
  function _tweenStop() {
    if(_tweenRunning) {
      _scrollSpeed = 0;
      window.clearInterval(_tweenTimer);
      _tweenRunning = false;
      enableQTips();
    }
  }

  
  function _tweenWork() {
    var scrollPos = _obj.scrollTop();
    _obj.scrollTop(scrollPos + _scrollSpeed);

    _scrollSpeed *= _scrollAccel;
    
    if ((_scrollSpeed <= 0.05) && (_scrollSpeed >= -0.05)) {
      _tweenStop();
      _scrollSpeed = 0.0;
      return;
    }
  }


  // 
  // public interface
  // 
  
  // interrupts the current scroll tween
  $.fn.smoothScrolling.halt = function() {
    _tweenStop();
  }


  // 
  // plugin defaults
  //
  $.fn.smoothScrolling.defaults = {
    scrollFactor: 30.0,
    scrollFactorMac: 15.0
  }


})(jQuery);

