var webContextPath = '';
var visibleItems;		   // visible items really depends on font size, so its more of a ratio
var alternateVisibleItems; // alternate visible items really depends on font size, so its more of a ratio
var scrollerMap = new Object();
scrollerMap.lists = new Array(2);

function ScrollState() {
	this.currentTop=0;		// the current Y position of the UL
	this.zInterval = null;	// animation thread interval
	this.directionUp;		// direction we're scrolling the UL. 0==up, 1==down
	this.scrollRate=6;		//6 initial rate of scrolling
	this.scrollTick=0;		// keeps track of long we've scrolled so we can slow it down accordingly
	this.maximumScrollTick;	//4 the maximum value of scrollTick before it's reset
	this.scrollIndexMax;
	this.scrollIndex = 0;
	this.hierarchy = 'none';
	this.setScrollIndexMax = function(length, itemsToBeShown) {
		this.scrollIndexMax = Math.ceil(length / itemsToBeShown);
	}
	this.resetScroller = function() {
		this.currentTop=0;
		this.scrollRate=6;
		this.scrollTick=0;	
		this.scrollIndex = 0;
	}
};

addLoadEvent(function() {
					  if ($('web-context-path'))
						  webContextPath =  $('web-context-path').innerHTML;
						  
                      // MENU SCROLL TRIGGER
					  scrollTrigger = $('scroll-trigger');
					  if (scrollTrigger && parseInt(scrollTrigger.innerHTML) > 0) {
						  visibleItems = parseInt(scrollTrigger.innerHTML);
					  } else {
						  visibleItems = 7;
					  }

					  // ALTERNATE MENU SCROLL TRIGGER
                      alternateScrollTrigger = $('alternate-scroll-trigger');
					  if (alternateScrollTrigger && parseInt(alternateScrollTrigger.innerHTML) > 0) {
						  alternateVisibleItems = parseInt(alternateScrollTrigger.innerHTML);
					  } else {
						  alternateVisibleItems = visibleItems;
					  }
					  
					  if ($('navigation'))
					  	setupScrolling('navigation', 'scrollingMenuContainer');
					  
					  if ($('navigation2'))
					  	setupScrolling('navigation2', 'scrollingMenuContainer2');
					  });

function resetScroller(modifier) {
	theList = 'navigation' + modifier;
	outerScrollingContainer = 'scrollingMenuContainer' + modifier;
	
	var theScroller = scrollerMap.lists[theList];
	if (theScroller) {
		theScroller.resetScroller();
		
		//this fixes when at position 0
		tl = $(theList);
		tl.style.top=theScroller.currentTop + "px";

		//this fixes when user had scrolled a bit
		osc = $(outerScrollingContainer);
		osc.style.position = "relative";
		osc.style.top=theScroller.currentTop + "px"; 
	}
}


/*
	If there are more children in theList than specified in visibleItems: insert scrolling.
*/
function setupScrolling(theList, outerScrollingContainer) {
	var scrollContainer = $(theList);
	var kids = $A(scrollContainer.getElementsByTagName('li'));
	kids = kids.slice(1, kids.length); //to skip the nav-return LI
	totalKids = kids.length;
		
		var scroller = new ScrollState();
		if (theList == 'navigation') {
		    scroller.setScrollIndexMax(totalKids, visibleItems);
		}
		if (theList == 'navigation2') {
		    scroller.setScrollIndexMax(totalKids, alternateVisibleItems);
		}
		scroller.hierarchy = theList;
		
		//----------scrollIndexMax = Math.ceil(totalKids / visibleItems);
		if (theList == 'navigation') {
		    minimumListHeight = visibleItems * getPixelHeightBaseRate();
		}
		if (theList == 'navigation2') {
		    minimumListHeight = alternateVisibleItems * getPixelHeightBaseRate();
		}
		
		//Apply new styles to make scrolling possible
		$(outerScrollingContainer).style.position = "relative";
		/*$(outerScrollingContainer).style.overflow = "hidden";*/
		$(outerScrollingContainer).style.height=minimumListHeight+"px";	
		$(theList).style.position = "absolute";
		
		if (theList == 'navigation') {
            insertUpDownArrows(visibleItems, scroller, totalKids, theList, outerScrollingContainer);
		}
		if (theList == 'navigation2') {
            insertUpDownArrows(alternateVisibleItems, scroller, totalKids, theList, outerScrollingContainer);
		}
		//save scroller
		scrollerMap.lists[theList] = scroller;
		
		//Check to see whether we need to reposition scroll bars
		if (theList == 'navigation') {
		    adjustScrollToArea(kids, theList, visibleItems);
		}
		if (theList == 'navigation2') {
		    adjustScrollToArea(kids, theList, alternateVisibleItems);
		}

}

function getPixelHeightBaseRate() {
    var pixelHeightBaseRate;
    pixelHeightBaseRateForListItem = $('pixel-height-base-rate-for-list-item');
    if (pixelHeightBaseRateForListItem && parseInt(pixelHeightBaseRateForListItem.innerHTML) > 0) {
        pixelHeightBaseRate = parseInt(pixelHeightBaseRateForListItem.innerHTML);
    } else {
        pixelHeightBaseRate = 24 // use 24px as the height base rate for a LI
    }
    return pixelHeightBaseRate;
}

function insertUpDownArrows(visibleItems, scroller, totalKids, theList, outerScrollingContainer) {
    if (visibleItems < 12)
 	    scroller.maximumScrollTick = visibleItems - 2;
    else if (visibleItems < 17)
	    scroller.maximumScrollTick = visibleItems - 3;
    else if (visibleItems < 21)
	    scroller.maximumScrollTick = visibleItems - 4;
    else
	    scroller.maximumScrollTick = visibleItems / 2;
    if (totalKids > visibleItems) {
	    //Insert up and down arrows
	    upScroll = makeScrollLink(true,  theList);
	    $(outerScrollingContainer).parentNode.insertBefore(upScroll, $(outerScrollingContainer));
	    downScroll = makeScrollLink(false,  theList);
	    $(outerScrollingContainer).parentNode.appendChild(downScroll);
    }
}

function makeScrollLink(up, theList) {
	moving = 'up';
	if (!up)
		moving = 'down';
	scrollImage = document.createElement('img');
	scrollImage.setAttribute('src', webContextPath + '/icons/scroll_' + moving + '.gif');
	scrollImage.setAttribute('alt', 'Scroll ' + moving);
	hyperLink = document.createElement('a');
	hyperLink.onclick = function(){scrollMenu(up, theList); return false;};
	hyperLink.setAttribute('title', 'Scroll ' + moving);
	hyperLink.setAttribute('href', '#');
	hyperLink.appendChild(scrollImage);
	scrollContainer = document.createElement('p');
	scrollContainer.setAttribute('class', 'scroll');
	scrollContainer.setAttribute('id', 'scroll-' + moving + '-' + theList);
	scrollContainer.appendChild(hyperLink);
	scrollContainer.style.textAlign = 'center';
	return scrollContainer;
}

function scrollMenu(dir, theList) {
	var theScroller = scrollerMap.lists[theList];
	if(theScroller.zInterval) {
		//window.alert("Still scrolling, please wait.");
		return false; // already scrolling.
	}
	
	theScroller.directionUp = dir;
	
	if (theScroller.directionUp && theScroller.scrollIndex == 0) {
		window.alert("You have already reached the top of the list.");
		return false; // dont scroll up if we're at the top
	}
		
	if(!theScroller.directionUp) {
		theScroller.scrollIndex ++;
	} else {
		theScroller.scrollIndex --;
	}
	theScroller.zInterval=setInterval("animate('" + theList + "')",20);
	return true;
}

function animate(theList) {
	var theScroller = scrollerMap.lists[theList];
	
	// increment or decrement currentTop based on direction
	if(!theScroller.directionUp) {
		theScroller.currentTop-=theScroller.scrollRate;
	} else {
		theScroller.currentTop+=theScroller.scrollRate;
	}
	theScroller.scrollTick++;	
	if(theScroller.scrollTick >= theScroller.maximumScrollTick) {
		theScroller.scrollRate--; // slow the scroll rate down for a little style
		theScroller.scrollTick=0;
	}

	$(theList).style.top=theScroller.currentTop + "px";
	if(theScroller.scrollRate<=0) { // 0 is the REBOUND rate (-4 old value): the value of scrollRate when we stop scrolling
		// scroll is finished. clear the interval and reset vars for the next scroll
		clearInterval(theScroller.zInterval);
		theScroller.zInterval=null;
		theScroller.scrollTick=0;
		theScroller.scrollRate=6;
	}
}
/* When a navigation menu is requested after the user has scrolled, 
	need to return them to the same place on the scrolled menu */
function adjustScrollToArea(listItems, theList, visibleItems) {
	currentURL = window.location.href;
	if (currentURL.indexOf('nodeNum=') > 0) {
		nodeNum = currentURL.substring(	currentURL.indexOf('nodeNum=') + 8);
		//The end of the nodeNum is the first non numeric number
		x = 0;
		while (isInteger(nodeNum.charAt(x)) && x < nodeNum.length)
			x++;
		nodeNum = "nodeNum=" + nodeNum.substring(0, x);
		
		//Search through the <li> to see if any contain this nodeNum parameter
		targetListItem = 0;
		for (y=0; y < listItems.length; y ++) {
			hyperlink = listItems[y].getElementsByTagName('a')[0];
			if (hyperlink.href.indexOf(nodeNum) > 0)
			 	targetListItem = y;

		}
		
		if (targetListItem >= visibleItems) {
			requiredScrolls = parseInt(targetListItem / visibleItems);
			z = 0;
			while (z < requiredScrolls) {
				nonAnimatedScrollDown(theList);
				z ++;
			}
		}
	}
}
/* Similar to animate(), but only moves the position of the list after all the calculations. */
function nonAnimatedScrollDown(theList) {
	var theScroller = scrollerMap.lists[theList];
	theScroller.directionUp = false;
	theScroller.scrollIndex ++;
	
	while (theScroller.scrollRate > 0) {
		// increment or decrement currentTop based on direction
		theScroller.currentTop-=theScroller.scrollRate;
		theScroller.scrollTick++;	
		if(theScroller.scrollTick >= theScroller.maximumScrollTick) {
			theScroller.scrollRate--; // slow the scroll rate down for a little style
			theScroller.scrollTick=0;
		}
	}
	
	$(theList).style.top=theScroller.currentTop + "px";
	
	theScroller.scrollTick=0;
	theScroller.scrollRate=6;

}