﻿var DHTMLScroller = {

  obj : null,

  init : function(sContainerDiv, sContentDiv, sTrackDiv, sScrubberDiv, bKeepScrubberHeight)
  {
    oScrollScrubber = document.getElementById(sScrubberDiv);
    var o = oScrollScrubber;
    
    o.root = o;              
    o.bKeepScrubberHeight = bKeepScrubberHeight;
    o.oContainer = document.getElementById(sContainerDiv);
    o.oContent = document.getElementById(sContentDiv);
    o.oScrollTrack = document.getElementById(sTrackDiv);

    this.initScroll(sScrubberDiv);
  },
  
  initScroll : function(sScrubberDiv)
  {
    oScrollScrubber = document.getElementById(sScrubberDiv);
    var o = oScrollScrubber;
    
    o.oContent.style.top = "0px"; 
    o.style.top = "0px";   
    o.contentScrollDist = o.oContainer.offsetHeight - o.oContent.offsetHeight;

    if (o.contentScrollDist >= 0) {
        o.oScrollTrack.style.display = o.style.display = "none";
    } else {
        o.oScrollTrack.style.display = o.style.display = "block";
        if (!o.bKeepScrubberHeight) {
            var perc = (o.oContainer.offsetHeight / o.oContent.offsetHeight)
            var iScrubberHeight = o.oScrollTrack.offsetHeight * perc;
            iScrubberHeight = (iScrubberHeight < 10) ? 10 : iScrubberHeight;
            o.style.height = Math.round(iScrubberHeight) + "px";
        }
        
        o.scrubberScrollDist = o.oScrollTrack.offsetHeight - o.offsetHeight;
        o.maxY = parseInt(oScrollScrubber.style.top) + o.scrubberScrollDist;    
            
        o.minY  = 0        
        o.onmousedown  = DHTMLScroller.start;
    }    
  },

  start : function(e)
  {
    var o = DHTMLScroller.obj = this;
    e = DHTMLScroller.fixE(e);
    var y = parseInt(o.root.style.top);

    o.lastMouseY  = e.clientY;

    if (o.minY != null)  o.minMouseY  = e.clientY - y + o.minY;
    if (o.maxY != null)  o.maxMouseY  = o.minMouseY + o.maxY - o.minY;

    document.onmousemove  = DHTMLScroller.drag;
    document.onmouseup    = DHTMLScroller.end;

    return false;
  },

  drag : function(e)
  {
    e = DHTMLScroller.fixE(e);
    var o = DHTMLScroller.obj;

    var ey  = e.clientY;
    var y = parseInt(o.root.style.top);
    var ny;
    
    if (o.minY != null) ey = Math.min(ey, o.maxMouseY);
    if (o.maxY != null) ey = Math.max(ey, o.minMouseY);
    
    ny = y + ey - o.lastMouseY;
    
    o.root.style.top = ny + "px";
    DHTMLScroller.obj.lastMouseY  = ey;
    
    // scroll the content
    perc = (ny / o.scrubberScrollDist);
    newTop = Math.round(o.contentScrollDist * perc);
    o.oContent.style.top = newTop + "px";     

    return false;
  },

  end : function()
  {
    document.onmousemove = null;
    document.onmouseup   = null;
    DHTMLScroller.obj = null;
  },

  fixE : function(e)
  {
    if (typeof e == 'undefined') e = window.event;
    if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
    return e;
  }
};

