var isDOM=document.getElementById?1:0;
var isIE=document.all?1:0;
var isNS4=(navigator.appName=='Netscape'&&!isDOM)?1:0;
var isIE4=(isIE&&!isDOM)?1:0;
var isWin=(navigator.platform.indexOf('Win')!=-1)?1:0;
var isDyn=(isDOM||isIE4||isNS4);

function getRef(id, par)
{
 par = !par ? document : (par.navigator?par.document:par);
 return (isIE ? par.all[id] :
  (isDOM ? (par.getElementById?par:par.ownerDocument).getElementById(id) :
  par.layers[id]));
}

function getSty(id, par)
{
 return (isNS4 ? getRef(id, par) : getRef(id, par).style);
}


if (!window.LayerObj) var LayerObj = new Function('id', 'par',
 'this.ref=getRef(id, par); this.sty=getSty(id, par); return this');
function getLyr(id, par) { return new LayerObj(id, par) }

function LyrFn(fn, fc)
{
 LayerObj.prototype[fn] = new Function('var a=arguments,p=a[0]; with (this) { '+fc+' }');
}

LyrFn('x','if (!isNaN(a[0])) sty.left=p; else return parseInt(sty.left)');
LyrFn('y','if (!isNaN(a[0])) sty.top=p; else return parseInt(sty.top)');
LyrFn('w','if (p) (isNS4?sty.clip:sty).width=p; ' +
 'else return (isNS4?ref.document.width:ref.offsetWidth)');
LyrFn('h','if (p) (isNS4?sty.clip:sty).height=p; ' +
 'else return (isNS4?ref.document.height:ref.offsetHeight)');
LyrFn('vis','sty.visibility=p');
LyrFn('clip','if (isNS4) with(sty.clip) { left=a[0]; top=a[1]; right=a[2]; bottom=a[3] } ' +
 'else sty.clip="rect("+a[1]+"px "+a[2]+"px "+a[3]+"px "+a[0]+"px)" ');


if (!window.page) var page = { win: window, minW: 0, minH: 0, MS: isIE&&!window.opera }

page.winW=function()
 { with (this) return Math.max(minW, MS?win.document.body.clientWidth:win.innerWidth) }
page.winH=function()
 { with (this) return Math.max(minH, MS?win.document.body.clientHeight:win.innerHeight) }



// *** LOAD FILES INTO DIV FUNCTIONS ***


function scrLoad(fName) { with (this)
{
 if (!fName || !loaded || !isDyn) return;

 // Set this as the currently loading file, and fire the 'onbeforeload' event.
 loadingFile = fName;
 if (onbeforeload) onbeforeload();

 // Trigger a file load in IE, that calls the 'fileLoaded()' function when complete.
 if (isIE || isDOM) with (bufRef.document)
 {
  // Nest an Iframe with an onload handler.
  write('<html><body onload="parent.' + myName + '.fileLoaded()">' +
   '<iframe name="nestBuf" src="' + fName + '"></iframe></body></html>');
  close();
  // In early versions of NS6, the nested Iframe is not invoked nor is the onload event fired.
  // So we set the regular frame's location and give it 5 secs to load.
  // Do the same for IE4 on the Macintosh which is generally pathetic.
  if (!bufRef.nestBuf || (isIE4 && !isWin))
  {
   bufRef.location.href = fName;
   setTimeout(myName + '.fileLoaded()', 5000);
  }
 }
 else if (isNS4)
 {
  // Delay load if another file is loading concurrently...
  if (window.ns4LayerLoading)
  {
   setTimeout(myName + '.load("' + fName + '")', 100);
   return;
  }
  window.ns4LayerLoading = true;

  // On load, clear loading flag and scroll to top.
  div.ref.onload = new Function(myName + '.fileLoaded()');
  // Netscape's load(URL, width) method...
  div.ref.load(fName, cWidth);
 }
}}


function scrFileLoaded() { with (this)
{
 // Stop dragging any scroller while we switch files.
 activeScr = null;

 // Clear the loading flag for NS4, clear to load another file!
 if (isNS4) window.ns4LayerLoading = false;

 // In IE or NS6, shift the contents of the IFrame buffer into the DIV.
 // Note this is still an extension of the NS6 kludge, not using the nested IFrame.
 if ((isDOM || isIE) && loadingFile)
 {
  var bufDoc = bufRef.nestBuf ? bufRef.nestBuf.document : bufRef.document;
  if (bufDoc && bufDoc.body) div.ref.innerHTML = bufDoc.body.innerHTML;
  bufRef.location.replace('about:blank');
 }

 // Set the loaded file as the one we've just loaded.
 loadedFile = loadingFile;

 // Set the 'sticky scroll' interval if needed.
 if ((stick != 1) && !stickTimer) stickTimer = setInterval(myName + '.stickScroll()', 30);

 // Scroll back to top... the short delay helps IE4, giving it some time to render
 // the new document to calculate its height. Also fire the 'onload' event.
 setTimeout('with(' + myName + ') { scrollTo(0); if (onload) onload() }', 1);
}}



// *** DIV SCROLLING FUNCTIONS ***


function scrScrollTo(pos, isStick) { with (this)
{
 if (!isDyn || !loaded) return;

 // Assign new top value.
 cTop = parseInt(pos);

 // If this isn't a sticky scroll, set the target position to the current position.
 // Otherwise whenever you click the arrows, the scroller slides back again...
 if (!isStick) stickTop = cTop;

 // Height of div, plus padding - update here as it may change often.
 divHeight = div.h() + padTop + padBot;
 // Stops 'divide by zero'
 if (divHeight == 0) divHeight = 1;

 // Should we check if we're scrolling out of range? If so, return to top/bottom.
 if (checkBounds)
 {
  if (cTop + cHeight > divHeight) cTop = divHeight - cHeight;
  if (cTop < 0) cTop = 0;
 }

 // Move div up/down... 'scrolling' div, and reclip as we do so.
 div.y(eval(divs[0].y) - cTop + padTop);
 div.clip(0, cTop - padTop, cWidth, cTop - padTop + cHeight);


 // Define its height as the percentage of the clipping height vs div height.
 // Best to set it here as divHeight may change as images load etc.
 thmHeight = Math.ceil(barHeight * (cHeight / divHeight));

 // Minimum and maximum heights for thumb...
 if (thmHeight < minThmHeight) thmHeight = minThmHeight;
 if (thmHeight > barHeight) thmHeight = barHeight;

 // Assign the thumb its calculated height.
 thm.h(thmHeight);

 // Now is a good time to fire the 'onscroll' event if it exists.
 if (onscroll) onscroll();

 // Adjust scrollbar thumb position only if we're not already dragging it.
 if (activeScr) return;

 // What fraction is the div of its total scrolling range? 0=top, 1=bottom.
 var fracDivDown = (cTop / (divHeight - cHeight));
 // Now, multiply that by the available space to move and assign its top.
 thm.y(bar.y() + fracDivDown * (barHeight - thmHeight));
}}


function scrScrollBy(amount) { with (this)
{
 // Scroll to the old location plus however much we're scrolling by.
 scrollTo(cTop + amount);

 // If we're looping, set a timeout to scroll by amount again.
 if (loop) setTimeout(myName + '.scrollBy(' + amount + ')', loop);
}}



// *** SCROLL THUMB DRAGGING EVENT HANDLERS ***


function scrThumbDown(evt) { with (this)
{
 // Set the global variable pointing to the active scroller - this scroller object.
 activeScr = this;

 // Offset of mouse cursor within the scrollbar...
 dragOffset = (isIE ? event.offsetY : evt.layerY);

 // Fire the 'onthumbdown' event if it exists.
 if (onthumbdown) onthumbdown();

 return false;
}}


function scrThumbMove(evt)
{
 // Either return true if no scroller is being dragged (so selections work), or if
 // it's NS4 just route the event...
 if (!activeScr) return true;
 else with (activeScr)
 {
  // If it's not scrollable, quit.
  if ((cTop + cHeight > divHeight) || (thmHeight == barHeight)) return true;

  // Calculate the new position of the thumb within the scrollbar (0 = at the top).
  var thmTop = (isIE ? document.body.scrollTop + event.clientY : evt.pageY) - dragOffset - bar.y();
 
  // Test if the thumb is out of range, if so, bring it back, then assign its position.
  if (thmTop < 0) thmTop = 0;
  if (thmTop + thmHeight > barHeight) thmTop = barHeight - thmHeight;
  thm.y(bar.y() + thmTop);

  // Set the new position as the target top value for the sticky scroll routine.
  stickTop = (divHeight - cHeight) * (thmTop / (barHeight - thmHeight));
  
  // If sticky scrolling is off, scroll to it now, if it's on, the setInterval() will do it.
  if (stick == 1) scrollTo(stickTop);

  return false;
 }
}


function scrStickScroll() { with (this)
{
 // If we're way off, scroll by the stickiness factor in the correct direction.
 if (Math.abs(cTop - stickTop) > 2)
 {
  cTop += (stickTop - cTop) * stick;
  scrollTo(cTop, true);
 }
 else if (cTop != stickTop)
 {
  // Otherwise, scroll to the exact point, and call it done.
  cTop = stickTop;
  scrollTo(cTop, true);
 }
}}


function scrThumbUp(evt)
{
 // Fire the 'onthumbup' event if it exists.
 if (activeScr) with (activeScr) if (onthumbup) onthumbup();

 // Clear the active scroller global variable.
 activeScr = null;
}



// *** SCROLLBAR BACKGROUND CLICK EVENT HANDLER ***


function scrBarClick(evt) { with (this)
{
 if (isIE) clickPos = document.body.scrollTop + event.clientY;
 else clickPos = evt.pageY;

 // Page up, or page down?
 if (clickPos < thm.y()) scrollBy(0 - cHeight);
 if (clickPos > (thm.y() + thmHeight)) scrollBy(cHeight);

 if (isNS4) return document.routeEvent(evt);
}}



// *** LAYOUT HANDLER FOR WINDOW RESIZE ETC ***


function scrLayout() { with (this)
{
 if (!isDyn || !loaded) return;

 // Loop through divs array, positioning/sizing controls.
 for (var i = 0; i < divs.length; i++) with (divs[i].lyr)
 {
  // Don't let the width and height get below 0.
  x(eval(divs[i].x)); w(Math.max(0,eval(divs[i].w)));
  // Only set Y and height if it's not the scrolling div.
  if (i) { y(eval(divs[i].y)); h(Math.max(0,eval(divs[i].h))) }
 }

 // Bar height and clipping dimensions, accessed often so stored as object properties.
 barHeight = eval(divs[1].h);
 cWidth = eval(divs[0].w);
 cHeight = eval(divs[0].h);

 // Might as well fire the onlayout event if it exists.
 if (onlayout) onlayout();

 // Now, display it using updated variables...
 scrollBy(0);
}}


// *** ON LOAD: CAPTURE EVENTS & MISC. SETUP ***


function scrSetup(defaultFile) { with (this)
{
 if (!isDyn) return;

 // Get layer objects for all the divs passed to the function somehow...
 for (var i = 0; i < divs.length; i++)
  divs[i].lyr = getLyr(divs[i].id, eval(divs[i].par));
  
 // These get accessed so often we might as well get some short references.
 div = divs[0].lyr;
 bar = divs[1].lyr;
 thm = divs[2].lyr;

 // Buffer frame for IE/NS6 -- same as scroller name, plus 'Buf'.
 // NS6 has troubles with the frames array and iframes, so use a workaround.
 if (!isNS4) bufRef = eval('window.' + myName + 'Buf');

 // Set up event capturing for NS4.
 if (isNS4)
 {
  bar.ref.captureEvents(Event.CLICK);
  thm.ref.captureEvents(Event.MOUSEDOWN);
 }

 // Pass events to this scroller.
 bar.ref.onclick = new Function('evt', 'return ' + myName + '.barClick(evt)');
 thm.ref.onmousedown = new Function('evt', 'return ' + myName + '.thumbDown(evt)');

 // For IE4+/NS6, create a new function that stops selections being made when dragging.
 var noSel = new Function('if (activeScr) return false');
 if (isIE) document.onselectstart = noSel;
 else if (isDOM) document.onselect = noSel;


 // It's now ready to go, call resize function to set the positions and variables...
 loaded = true;
 layout();
 // Now is a good time to fire the 'onsetup' event, it's ready to load...
 if (onsetup) onsetup();


 // Get the name of the file to be loaded from a URL query string...
 var fileName = ''
 // Get the string after the question mark.
 var URL = location.search.substring(1);
 if (URL)
 {
  // Split it into an array of scroller/filename pairs.
  URL = URL.split('&');
  // Search through that array looking for this scroller name.
  for (var i = 0; i < URL.length; i++)
   if (URL[i].split('=')[0] == myName) fileName = URL[i].split('=')[1];
 }

 // Contains string '.htm'...? (can be '.html' file of course)
 if (fileName.indexOf('.htm') != -1) load(fileName)

 // Else load default file (if we're passed one) or scroll existing content without loading.
 else if (defaultFile) load(defaultFile);
 else fileLoaded();
}}



// *** SCROLLER OBJECT CONSTRUCTOR FUNCTIONS ***


// This takes arrays of data and names and assigns the values to a specified object.
function addProps(obj, data, names, addNull)
{
 for (var i = 0; i < names.length; i++) if(i < data.length || addNull) obj[names[i]] = data[i];
}


// Main object of which instances are created.
function DHTMLScroller()
{
 // Only the first is actually passed to the function, the rest are just added as 'undefined'.
 var names = ['myName', 'bufRef', 'div', 'bar', 'thm', 'loaded', 'loop', 'divHeight', 'thmHeight',
  'barHeight', 'cHeight', 'cWidth', 'dragOffset', 'onbeforeload', 'onload', 'onscroll', 'onsetup',
  'onlayout', 'onthumbdown', 'onthumbup'];
 addProps(this, arguments, names, true);

 // The top clipping position by default is zero -- the top of the file.
 this.cTop = 0;

 // The file(s) currently loading and displayed in the scroller,
 this.loadingFile = '';
 this.loadedFile = '';

 // Array of objects to move when the window is resized (e.g. scrollbar, arrows).
 this.divs = new Array();
 
 // Minimum height of scrollbar thumb - defaults to 20, set to something else if you want.
 this.minThmHeight = 20;
 // Padding at the top and bottom -- set these manually if you want.
 this.padTop = 0;
 this.padBot = 0;
 // Whether or not to allow scrolling out of the normal region.
 this.checkBounds = true;

 // The 'stickiness' of the scroller, 1 means perfect scrolling, decimals = floating.
 this.stick = 1;
 // Target point to which we scroll, and a timer variable managing sticky scroll.
 this.stickTop = 0;
 this.stickTimer = null;

 // Methods - bound to functions above.
 this.load = scrLoad;
 this.fileLoaded = scrFileLoaded;
 this.scrollTo = scrScrollTo;
 this.scrollBy = scrScrollBy;
 this.thumbDown = scrThumbDown;
 // The other thumb functions are global, associated with document.onevent.
 // They rely on the 'activeScr' global variable to tell them which scroller is being dragged.
 this.stickScroll = scrStickScroll;
 this.barClick = scrBarClick;
 this.setup = scrSetup;
 this.layout = scrLayout;
}


// One global variable that points to the scroller currently being dragged, and some dimensions.
var activeScr = null;

// The 'ScrDiv' function sets up the data structure for the scroller divs.
function ScrDiv()
{
 addProps(this, arguments, ['id','x','y','w','h','par','lyr'], true);
}












// *** SCROLLER OBJECT SETUP -- START EDITING HERE, keep reading until bottom of file ***.

// First, you have to create one or more scroller objects, syntax:
// var name = new DHTMLScroller('name');

var mainDiv = new DHTMLScroller('mainDiv');


// Then, working with its properties, we tell it the names of the relevant divs below we want it
// to use. This is accomplished by the 'divs' array, to which we add new items like so:
//
// divs[number] = new ScrDiv('id of div below', 'x', 'y', 'width', 'height', 'parent');
//
// As you can see, the second through to fourth parameters are the positions and dimensions of the
// divs, declared here rather than as properties to the divs below. They are strings containing
// either plain numbers, or formulae using global variables or functions to calculate
// special positions, e.g. centring or sizing with the window. Pass an empty string '' to tell
// the script not to set that particular parameter.
//   The 'parent' parameter is optional. Use it if you're nesting the scroller divs within other
// divs, by passing a string that when evaluated, returns a reference to the parent layer of the
// div, e.g. 'getRef("containerDiv")', which is similar to 'document.all.containerDiv'. If you're
// just editing this template script, don't bother about it.
//   The first three divs are special -- divs[0] is the scroller itself, 1 = the scrollbar itself
// and 2 = the scrollbar thumb (the draggable bit). Anything after that is positioned and
// sized by the scroller engine on window resize but does not have any special properties.



with (mainDiv)
{

 divs[0] = new ScrDiv('mainDivContent', '(page.winW()/2)-390', '104', '780', '280');
 divs[1] = new ScrDiv('mainDivBar', 'page.winW() - 95', '118', '16', '251');
 divs[2] = new ScrDiv('mainDivThumb', 'page.winW() - 95', '', '13', '');
 divs[3] = new ScrDiv('mainDivUpArrows', 'page.winW() - 95', '102', '', '');
 divs[4] = new ScrDiv('mainDivDownArrows', 'page.winW() - 95', '369', '', '');
 //padTop = 100;
 //padBot = 50;
 //stick = 0.2;
 minThmHeight = 62;
 page.minW = 780;
 page.minH = 280;

 onload = loadFunction; 
 
 // I've also set the onlayout event to hide and show the scrollbar thumb as needed.
 onlayout = thumbVis;
}

// Here's the example onload function, which gets called every time the scroller loads a file
// and shows/hides the appropriate divs. Note it is a property of the scroller and hence we use
// 'with (this)' to get at its other properties. You can just leave this alone, or you can dig
// into the source code and make other functions to show/hide loading messages, light up the
// scroller thumb as it is being dragged, use the onload to build a browsable history etc...

function loadFunction() { with (this)
{
 // Hide loading message...
 getSty('loadMessage').visibility = 'hidden';
 // And show the rest of the divs apart from the scrollbar thumb (which is divs[2]).
 // You could modify this function to do the reverse on the 'onbeforeload' event perhaps...?
 for (var i = 0; i < divs.length; i++) if (i != 2) divs[i].lyr.vis('visible');
 // Now call the thumbVis function below to show/hide thumb depending on content.
 onlayout();
}}

function thumbVis() { with (this)
{ 
 // Only show the thumb when the actual content height exceeds the clipping area.
 if (div.h() > eval(divs[0].h)) divs[2].lyr.vis('visible');
 else divs[2].lyr.vis('hidden');
}}




// Capture events -- make sure you combine this with any other scripts which also capture these
// events e.g. Popup Menus. You call the .setup() function onload with the name of a default file,
// in this case its readme, but you'll probably want something like "home.html". Alternatively,
// you can pass a blank string "" to scroll the content already in the div, but you must manually
// specify a width on the div below via style="width: xyz" for Netscape 4.
// Note we also call a small 'bug check' function to stop Netscape 4 dying when you resize the
// window. Use this one in preference to the one in my Popup Menu script if you're combining them.

// window.onevent=function(){....} is essentially the same as <BODY ONEVENT="....">
// Make sure you don't assign events either way later in your page, otherwise these get overridden.

window.onload = function()
{
 mainDiv.setup('home.html');
}

window.onresize = function()
{
 ns4BugCheck();
 mainDiv.layout();
}

// Capture mouse movement for dragging. Combine this with other scripts if needed!
// Make sure to capture and route these events for NS4 as we should.
if (isNS4) document.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);

document.onmousemove = function(evt)
{
 var ret = scrThumbMove(evt);
 return (ret ? (isNS4?document.routeEvent(evt):true) : false);
}

document.onmouseup = function(evt)
{
 scrThumbUp(evt);
 if (isNS4) return document.routeEvent(evt);
}


// Check for NS4 resize, reload if that's the case and pass current loaded file as query.
var nsWinW = window.innerWidth, nsWinH = window.innerHeight;
function ns4BugCheck()
{
 if (isNS4 && (nsWinW!=innerWidth || nsWinH!=innerHeight))
 {
  // NS4 cannot handle resizes, so reload -- but use URL query mechanism to keep the loaded file.
  var fileName = location.href;

  // Trim existing URL query string out of the current location, if any.
  if (fileName.indexOf('?') != -1) fileName = fileName.substring(0, fileName.indexOf('?'));
  // If you've got multiple scrollers, add the URLs of each and separate with '&' signs.
  location.href = fileName + '?mainDiv=' + mainDiv.loadedFile;
 }
}




