var PSCROLLER = {};

PSCROLLER.IMAGE_DIR = '/prd/image/';
PSCROLLER.GRAPHIC_DIM = 5;
PSCROLLER.PADDING = 20;
PSCROLLER.PREFIX = 'vpbreaker';
PSCROLLER.PREFIXRE = new RegExp( '^' + PSCROLLER.PREFIX + '\\d{1,2}$' );
PSCROLLER.CALCULATEPADDINGWITHNAV = 4;
PSCROLLER.CALCULATEPADDINGTABLE = 3;
PSCROLLER.CALCULATEPADDINGBODY = 2;
PSCROLLER.CALCULATEPADDINGSTYLESHEET = 1;
PSCROLLER.CALCULATEPADDINGNONE = 0;
PSCROLLER.NAVWIDTH = 310;
PSCROLLER.initialized = false;
PSCROLLER.calculatePaddingMethod = PSCROLLER.CALCULATEPADDINGWITHNAV;
PSCROLLER.calculatedPadding = (2*PSCROLLER.PADDING);
PSCROLLER.scrollerDivs = [];
PSCROLLER.resizeTimeoutId = null;

PSCROLLER.getStyle = function( el )
{
    if( window.getComputedStyle )
    {
        return window.getComputedStyle( el );
    }
        
    return el.currentStyle;
}

// Gets the parent of a passed node
PSCROLLER.getParent = function( el )
{
    return el.parentElement || el.parentNode;
};

PSCROLLER.resize = function( e )
{
    if( PSCROLLER.resizeTimeoutId )
        window.clearTimeout( PSCROLLER.resizeTimeoutId );
    PSCROLLER.resizeTimeoutId = setTimeout( PSCROLLER.processScrollerDivs, 100 );
}

// Create scrolled graphics for a particular iScroll object. Takes an event
// event argument that isn't really necessary for these particular events
// but kept in because it's passed automatically by iScroll. May find a use
// for it later.
PSCROLLER.addScrolledGraphics = function ( e )
{
    var scroller = this;

    if( !scroller )
    {
        return;
    }

	if( scroller.hScroll )
	{
		if( scroller.x >= 0 )
        {
			PSCROLLER.removeMoreGraphic( scroller.wrapper, 'left' );
		}
        else
        {
			PSCROLLER.addMoreGraphic( scroller.wrapper, 'left' );
		}
		if( scroller.x <= scroller.maxScrollX )
        {
			PSCROLLER.removeMoreGraphic( scroller.wrapper, 'right' );
		}
        else
        {
			PSCROLLER.addMoreGraphic( scroller.wrapper, 'right' );
		}
	}

	if( scroller.vScroll )
	{
		if( scroller.y >= 0 )
        {
			PSCROLLER.removeMoreGraphic( scroller.wrapper, 'top' );
		}
        else
        {
			PSCROLLER.addMoreGraphic( scroller.wrapper, 'top' );
		}
		if( scroller.y <= scroller.maxScrollY )
        {
			PSCROLLER.removeMoreGraphic( scroller.wrapper, 'bottom' );
		}
        else
        {
			PSCROLLER.addMoreGraphic( scroller.wrapper, 'bottom' );
		}
	}
};

// Adds a graphic showing that there is more. Currently creates an img that
// is stretched across the length. It's cheap to have a few small png's but
// also would like an option for a repeat. TODO: add a repeated version
PSCROLLER.addMoreGraphic = function ( wrapper, orientation )
{
	var moreGraphic;

    moreGraphic = document.getElementById( wrapper.id + orientation );

    if( !moreGraphic )
    {

    	moreGraphic = document.createElement( 'img' );
	    moreGraphic.id = wrapper.id + orientation;
	    moreGraphic.style.position = 'absolute';
    }

	if( orientation === 'left' || orientation === 'right' )
	{
		moreGraphic.height = wrapper.offsetHeight;
		moreGraphic.width = PSCROLLER.GRAPHIC_DIM;
	}
	if( orientation === 'top' || orientation === 'bottom' )
	{
		moreGraphic.height = PSCROLLER.GRAPHIC_DIM;
		moreGraphic.width = wrapper.offsetWidth;
	}

	switch( orientation )
	{
		case 'left':
			moreGraphic.src = PSCROLLER.IMAGE_DIR + 'morexleft.png';
			moreGraphic.style.left = '0';
			moreGraphic.style.top = '0';
			break;
		case 'right':
			moreGraphic.src = PSCROLLER.IMAGE_DIR + 'morexright.png';
			moreGraphic.style.left = (wrapper.offsetWidth - PSCROLLER.GRAPHIC_DIM) + 'px';
			moreGraphic.style.top = '0';
			break;
		case 'top':
			moreGraphic.src = PSCROLLER.IMAGE_DIR + 'moreytop.png';
			moreGraphic.style.left = '0';
			moreGraphic.style.top = '0';
			break;
		case 'bottom':
			moreGraphic.src = PSCROLLER.IMAGE_DIR + 'moreybottom.png';
			moreGraphic.style.top = (wrapper.offsetHeight - PSCROLLER.GRAPHIC_DIM) + 'px';
			moreGraphic.style.left = '0';
			break;
		default:
			break;
	}
	wrapper.appendChild( moreGraphic );
};

// These creates a scroller and adds the graphics calls. Requires the element
// that contains the element to be scrolled. Scrolled element must be the
// the first child for the parent element referred to from here. 
PSCROLLER.createScroller = function ( scrollerDiv, options )
{
	var myScroll;

	if( scrollerDiv )
	{
		if( ! scrollerDiv.iscroll )
		{
			scrollerDiv.iscroll = new iScroll( scrollerDiv.id, options );
			scrollerDiv.iscroll.options.onScrollMove = PSCROLLER.addScrolledGraphics;
			scrollerDiv.iscroll.options.onScrollEnd = PSCROLLER.addScrolledGraphics;
            // The below allows for the function to bubble up so you can still
            // scroll the application normally.
			scrollerDiv.iscroll.options.onBeforeScrollStart = null;
		}
	}
};

// Removes the graphics showing wether there is more on a side
PSCROLLER.removeMoreGraphic = function ( wrapper, orientation )
{
	var moreGraphic;

	if( moreGraphic = document.getElementById( wrapper.id + orientation ) )
	{
		wrapper.removeChild( moreGraphic );
		moreGraphic = null;
	}
};

// Create a div to encapsulate whatever element needs to be scrollable
PSCROLLER.encapsulateElement = function ( breakerEl )
{
	var breakerDiv;

    if( breakerEl.offsetWidth <= (window.innerWidth - (PSCROLLER.calculatedPadding)) )
    {
        return null;
    }

    if( !PSCROLLER.hasScrollerDiv( breakerEl ) )
    {
        breakerDiv = document.createElement( 'div' );
	    PSCROLLER.setBreakerId( breakerDiv );
	    breakerDiv.style.position = 'relative';
        breakerDiv.style.display = 'block';
        breakerDiv.style.margin = '0 auto';
        breakerDiv.style.zIndex = '3';
	    PSCROLLER.getParent( breakerEl ).insertBefore( breakerDiv, breakerEl );
	    breakerDiv.appendChild( breakerEl );
    }
    else
    {
        breakerDiv = PSCROLLER.getParent( breakerEl );
    }
    breakerEl.style.width = breakerEl.offsetWidth + "px";
	breakerDiv.style.width = (window.innerWidth - (PSCROLLER.calulatedPadding)) + "px";
    return breakerDiv;
};

// Remove an iScroll and any enveloping div.
PSCROLLER.removeScroller = function ( breakerEl )
{
    var breakerDiv = null;

    breakerDiv = PSCROLLER.getParent( breakerEl );
	if( PSCROLLER.hasScrollerDiv( breakerEl ) )
	{
        PSCROLLER.unsetBreakerId( breakerDiv );
        PSCROLLER.getParent( breakerDiv ).insertBefore( breakerEl, breakerDiv );
    }
    if( breakerDiv.iscroll )
    {
        PSCROLLER.removeMoreGraphic( breakerDiv.iscroll, 'left' );
        PSCROLLER.removeMoreGraphic( breakerDiv.iscroll, 'right' );
        breakerDiv.iscroll.destroy();
        breakerDiv.iscroll = null;
    }
    PSCROLLER.getParent( breakerDiv ).removeChild( breakerDiv );
    breakerDiv = null;
};

// Encapsulates the menu in a div so that it can be scrolled
PSCROLLER.encapsulateMenu = function ()
{
	var i,
        menuTable,
        menuDiv = null,
        sideNav;

	// If a large window is available, it's probably useful just to use it
	// normally without a scroller
	if( window.innerHeight > 800 && window.innerWidth > 800 )
    {
		return null;
    }

	if( sideNav = document.getElementById( 'sideNav' ) )
	{
        if( sideNav.children )
        {
            for( i = sideNav.children.length ; i-- ; )
            {
                if( sideNav.children[i].className.indexOf( 'sideContainer' ) >= 0 )
                {
		            menuTable = sideNav.children[i];
		            menuDiv = document.createElement( 'div' );
		            menuDiv.id = 'navDiv';
		            // TODO: find a way to measure chrome that gets
		            // scrolled up anyway. Chrome is really not
		            // applicable to the iPhone.
		            menuDiv.style.height = '320px';
		            menuDiv.style.position = 'relative';
		            PSCROLLER.getParent( menuTable ).insertBefore( menuDiv, menuTable );
		            menuDiv.appendChild( menuTable );
		            break;
                }
            }
        }
	}
    return menuDiv;
};

// Adds breaker id's to a single place so we don't have to search the entire
// Document for this just to find an unused one.
PSCROLLER.setBreakerId = function ( breakerDiv )
{
    var maxCount = PSCROLLER.scrollerDivs.length,
        id;

    for( id = 0 ; id < maxCount ; id++ )
    {
        if( PSCROLLER.scrollerDivs[id] === null )
        {
            break;
        }
    }
    breakerDiv.id = PSCROLLER.PREFIX + id;
    PSCROLLER.scrollerDivs[id] = breakerDiv;
};

// Removes a div from the global divs and allowing a new one to be able
// to be added to it's space.
PSCROLLER.unsetBreakerId = function ( breakerDiv )
{
    var id = 0;

    if( breakerDiv.id.match( PSCROLLER.PREFIXRE ) )
    {
        id = parseInt( breakerDiv.id.substring( PSCROLLER.PREFIX.length ), 10 );
        if( id > 0 && PSCROLLER.scrollerDivs.length < id )
        {
            PSCROLLER.scrollerDivs[id] = null;
        }
    }
};

// Calculates the padding by adding the offset
PSCROLLER.calculatePaddingFromElement = function ( breakerEl )
{
    var padding = 0,
        currentEl = breakerEl;

    while( currentEl )
    {
        padding += currentEl.offsetLeft;
        currentEl = currentEl.offsetParent;
    }
    return padding;
}

// Finds the tables that break the viewport and encapsulates them in
// appropriately named div's
PSCROLLER.processScrollerDivs = function ( e )
{
	var docTables = document.getElementsByTagName( 'table' ),
	    breakerDiv,
        breakerEl,
	    i;

    if( PSCROLLER.calculatePaddingMethod === PSCROLLER.CALCULATEPADDINGWITHNAV && window.innerWidth > 599 )
    {
        PSCROLLER.calculatedPadding = ((2*PSCROLLER.PADDING) + PSCROLLER.NAVWIDTH);
    }
	for( i = docTables.length ; i--; ) 
	{
		if( breakerEl = docTables[i] )
		{
            if( PSCROLLER.calculatePaddingMethod === PSCROLLER.CALCULATEPADDINGTABLE )
            {
                PSCROLLER.calculatedPadding = PSCROLLER.calculatePaddingFromElement( breakerEl ) + PSCROLLER.PADDING;
            }
			// Check to see wether it's already encapsulated and no longer
            // requires scrolling.
			if( breakerEl.offsetWidth <= (window.innerWidth - (PSCROLLER.calculatedPadding)) )
            {
			    if( PSCROLLER.hasScrollerDiv( breakerEl ) )
                {
                    PSCROLLER.removeScroller( breakerEl );
                }
			}
            else
            {
			    if( !PSCROLLER.hasScrollerDiv( breakerEl ) )
                {
                    breakerDiv = PSCROLLER.encapsulateElement( breakerEl );
                }
                else
                {
                    breakerDiv = PSCROLLER.getParent( breakerEl );
                }
			    if( breakerDiv )
                {
                    breakerDiv.style.width = (window.innerWidth - PSCROLLER.calculatedPadding) + 'px';
                    if( !breakerDiv.iscroll )
                    {
                        if( PSCROLLER.initialized )
                        {
                            PSCROLLER.createScroller( breakerDiv,  { vScroll: false, hScrollbar: false } );
                        }
                    }
                    PSCROLLER.addScrolledGraphics.call( breakerDiv.iscroll );
                }
            }
		}
	}
    breakerEl = null
};

// Checks to see if there is a scroller div associated with the element.
PSCROLLER.hasScrollerDiv = function ( breakerEl )
{
	return PSCROLLER.getParent( breakerEl ).id.match( PSCROLLER.PREFIXRE );
};

// Root function for creating and resizing images.
PSCROLLER.processMenu = function ()
{
    var navTable = null;

    navTable = PSCROLLER.encapsulateMenu()

    if( navTable = document.getElementById( 'navDiv' ) )
    {
        if( !navTable.iscroll )
        {
            navTable.iscroll = new iScroll( 'navDiv', { hScroll: false } );
            navTable.iscroll.options.onScrollMove = PSCROLLER.addScrolledGraphics;
            navTable.iscroll.options.onScrollEnd = PSCROLLER.addScrolledGraphics;
            PSCROLLER.addScrolledGraphics.call( navTable.iscroll );
        }
    }
}

// Refreshes the menu when something in resizes it. Must be called externally.
PSCROLLER.refreshMenuScroller = function()
{
    var navTable = document.getElementById( 'navDiv' );
    if( navTable && navTable.iscroll )
        navTable.iscroll.refresh();
}

var MENUTREE = {};

MENUTREE.collapseChildren = false;
MENUTREE.onBeforeResize = null;
MENUTREE.onAfterResize = null;

// Gets the parent sibling. Needed to take into account difference in how
// this done across browsers
MENUTREE.getParent = function( childEl )
{
   return childEl.parentElement || childEl.parentNode;
};

// Get the sibling previous to the passed element and returns null if there
// one.
MENUTREE.getPreviousSibling = function( el )
{
   var childEls,
       i;

   childEls = MENUTREE.getParent( el ).children;
   for( i = childEls.length ; i-- ; )
   {
       if( childEls[i] === el )
       {
           if( (i-1) >= 0 ) {
               return( childEls[i-1] );
           } else {
               return null;
           }
       }
   }
   return null;
};

// Get the sibling that is next after the passed element and returns null if
// there one.
MENUTREE.getNextSibling = function( el )
{
   var childEls,
       i;

   childEls = MENUTREE.getParent( el ).children;
   for( i = childEls.length ; i-- ; )
   {
       if( childEls[i] === el )
       {
           if( (i+1) < childEls.length ) {
               return( childEls[i+1] );
           } else {
               return null;
           }
       }
   }
   return null;
};

// Collapses a tree
MENUTREE.collapse = function( collapsingElement )
{
    var collapsibleChildren,
        i;

    if( collapsingElement )
    {
        if( MENUTREE.onBeforeResize )
            MENUTREE.onBeforeResize.call();
        // This will collapse elements underneath the element that gets
        // collapsed
        if( MENUTREE.collapseChildren )
        {
            collapsibleChildren = collapsingElement.getElementsByTagName( 'ul' );
            for( i = collapsibleChildren.length ; i-- ; )
            {
                if( (collapsibleChildren[i].tagName.toLowerCase() === 'ul') && (collapsibleChildren[i].className.indexOf( 'tree' ) >= 0) )
                {
                    collapsibleChildren[i].style.display = 'none';
                }
            }
        }
        // End nested collapse
        collapsingElement.style.display = 'none';
        if( MENUTREE.onAfterResize )
            MENUTREE.onAfterResize.call();
    }
};

// Expand an element in a tree
MENUTREE.expand = function ( expandingElement )
{
    if( expandingElement )
    {
        if( MENUTREE.onBeforeResize )
            MENUTREE.onBeforeResize.call();
        expandingElement.style.display = 'block';
        if( MENUTREE.onAfterResize )
            MENUTREE.onAfterResize.call();
    }
};

// Toggle it on or off
MENUTREE.toggle = function( e )
{
   var collapsible,
       collapsibleElement = e.target;

    if( !(collapsible = e.target.menuUL) )
    {
        while( collapsibleElement.tagName.toLowerCase() != 'li' )
        {
            collapsibleElement = MENUTREE.getParent( collapsibleElement );
        }
        collapsible = MENUTREE.getNextSibling( collapsibleElement );
    }
    if( collapsible )
    {
        if( collapsible.className.indexOf( 'tree' ) < 0 ) {
            return true;
        }
        if( collapsible.style.display === '' || collapsible.style.display === 'none' )
        {
            MENUTREE.expand( collapsible );
        }
        else
        {
            MENUTREE.collapse( collapsible );
        }
    }
    e.preventDefault();
    return false;
};

// Get the anchor tag nested within a link
MENUTREE.getNestedLink = function( el )
{
   var currentEl = el;

   while( currentEl.children )
   {
       if( currentEl.children[0].tagName.toLowerCase() === 'a' ) {
           return currentEl.children[0];
       }
       currentEl = currentEl.children[0];
   }
   return null;
};

// Setup collapsibles. This can be ignored if the onclick property is set
// to toggle for each of the links.
MENUTREE.setupCollapsibles = function( collapsibleEl )
{
   var i,
       childEl,
       collapsibles = collapsibleEl.getElementsByTagName( 'li' );

    for( i = collapsibles.length ; i-- ; )
    {
        if( collapsibles[i].className.indexOf( 'tree' ) >= 0 )
        {
            childEl = MENUTREE.getPreviousSibling( collapsibles[i] );
            if( childEl )
            {
                childEl = MENUTREE.getNestedLink( childEl );
                if( childEl ) {
                    childEl.onclick = MENUTREE.toggle;
                    childEl.menuUL = collapsibles[i];
                }
            }
        }
    }
}; 

function setupTree()
{
    var footer,
        sideNav,
        sideNavLink,
        navTable = document.getElementById( 'navTable' );

    if( window.innerWidth < 599 )
    {
        sideNavLink = document.getElementById( 'sideNav' );
	    footer = document.getElementById( 'footer' );
	    sideNav = document.getElementById( 'sideNav' );
	    if( footer && sideNav )
	    {
                PSCROLLER.getParent( footer ).insertBefore( sideNav, footer );
	    }
        if( sideNavLink )
        {
            sideNavLink.style.display = 'block';
        }
    }

    if( navTable )
    {
        MENUTREE.setupCollapsibles( navTable );
        MENUTREE.onAfterResize = PSCROLLER.refreshMenuScroller;
    }
};

var	totalOffset = 95;

function getGlobalOffsets(anElement)
{
    var theElement;

    var totalLeftOffset;
    var totalTopOffset;

    var widthOffset;
    var heightOffset;

    totalLeftOffset = 0;
    totalTopOffset = 0;

    widthOffset = 0;
    heightOffset = 0;
    //  Traverse up the *offset* parent chain of anElement
    theElement = anElement;
    while ( theElement )
    {
        if( theElement.id )
        {
            totalLeftOffset += theElement.offsetLeft;
            totalTopOffset += theElement.offsetTop;

            if (widthOffset == 0)
            {
                widthOffset = theElement.offsetWidth;
            };

            if (heightOffset == 0)
            {
                heightOffset = theElement.offsetHeight;
            };
        }
        theElement = PSCROLLER.getParent( theElement );
    };

    return { left: totalLeftOffset, top: totalTopOffset, width: widthOffset, heigt: heightOffset };
};

function scrollToAnchor(linkElem)
{
	var	globalOffsets, x, header;
	
	globalOffsets = getGlobalOffsets(linkElem);

    x = globalOffsets.top;
    header = parseInt( PSCROLLER.getStyle( document.getElementById("header") ).height, 10 );
    if( x === header )
    {
        x -= header;
    }
	//  If the body doesn't have any value here, that means we're
	//  running in strict mode, which means we need to tweak the
	//  documentElement's scrollTop, not the body's.
    if (window.scrollTo)
    {
        x = x > 0 ? x : 1;
        window.scrollTo( 0, x );
    }
	else if (document.body.scrollTop == 0)
	{
		document.documentElement.scrollTop = x;
	}
	else
	{
		document.body.scrollTop = x;
	};
};

function reorient( e )
{
    //window.scrollTo( 0,0 );
    PSCROLLER.processScrollerDivs( e );
}

function setupPage()
{
	if (navigator.userAgent.indexOf("Opera") != -1)
	{
		// Don't return... Opera will do the right thing here. It's just
		// that Opera also has a 'document.all' property and we need to
		// distinguish between the two.
	}
	else if (document.all)
	{
		//  We're on IE... return now, as IE doesn't do anything here.
		return;
	};

    if( window.orientation ) {
	    window.onorientationchange = reorient;
    } else {
	    window.onresize = PSCROLLER.resize;
    }
    prepLinks();
    if( PSCROLLER.calculatePaddingMethod === PSCROLLER.CALCULATEPADDINGBODY )
    {
        PSCROLLER.calculatedPadding = PSCROLLER.calculatePaddingFromEl( document.getElementById( 'body' ) );
    }
    setupTree();
    PSCROLLER.processMenu();
    PSCROLLER.processScrollerDivs;
    PSCROLLER.initialized = true;
    setTimeout( PSCROLLER.processScrollerDivs, 100 );
    if( PAUTOCOMPLETE.Autocompleter != undefined )
    {
        new PAUTOCOMPLETE.Autocompleter( "searchBox", "acResults", "/cgi-bin/WebObjects/Store.woa/wa/SearchSupport/getTermSuggestions", { paramName: 'query', minChars: '2' });
    }
    scrollOnLoad();
};

var PAUTOCOMPLETE = {};

PAUTOCOMPLETE.arrayToAutocompleteUL = function( ulArray )
{
    var x, formattedResponse = "";

    if( ulArray && ulArray.length > 0 )
    {
        formattedResponse = '<ul>\n';
        for( x = ulArray.length ; x-- ; )
        {
            formattedResponse += '  <li>' + ulArray[x] + '</li>\n';
        }
        formattedResponse += '</ul>';
    }
    return formattedResponse;
};

PAUTOCOMPLETE.autocompleteJSONParse = function( response, element )
{
    var parsedObject,
        reSuggestions = /^\{?[\s]*suggestions:[\s]*.*[\s]*\}?$/m,
        x,
        index,
        suggestionsArray,
        suggestions,
        formattedResponse = "";

    if( !response )
        return;
    suggestionsArray = response.match( reSuggestions );
    if( suggestionsArray && suggestionsArray.length > 0 )
    {
        suggestionsArray = suggestionsArray[0].split( ':', 2 );
        if( suggestionsArray && suggestionsArray.length === 2 )
        {
            suggestions = suggestionsArray[1].replace( /^\[[\s'"]*/, "" ).replace( /['"]?][\s}]*$/, "" ).split( /["',\s]+/ );
            formattedResponse = PAUTOCOMPLETE.arrayToAutocompleteUL( suggestions );
        }
    }
    return formattedResponse;
};

if( this.Ajax != undefined )
{
    //{ query:'figh',
    //suggestions:["fighter","fighting","fight","fighters","fighting system","fighting spirit","fight system","fighter group","fighter's","fighters and"] }

    PAUTOCOMPLETE.Autocompleter = Class.create(Ajax.Autocompleter, {
        initialize: function(element, update, url, options)
        {
            this.baseInitialize(element, update, options);
            this.options.asynchronous  = true;
            this.options.onComplete    = this.onComplete.bind(this);
            this.options.defaultParams = this.options.parameters || null;
            this.url                   = url;
        },
        onComplete: function(request)
        {
            var htmlUL = PAUTOCOMPLETE.autocompleteJSONParse( request.responseText, this.element );
            this.updateChoices( htmlUL || request.responseText);
        }
    } );
}

function scrollOnLoad()
{
	var	windowURL,
	    fragmentIndex,
	    anchorID,
	    anchorElement,

	windowURL = window.location.toString();

    window.scrollTo( 0,1 );
	//	If the windows location URL contains a '#', then we scroll the
	//	top down by 80 pixels from the name of the anchor.
	if ((fragmentIndex = windowURL.indexOf('#')) != -1)
	{
		anchorID = windowURL.slice(fragmentIndex + 2);

		if (anchorElement = document.getElementById(anchorID))
		{
			scrollToAnchor(anchorElement);
		};
	}
};

function prepLinks()
{
	var	linkElems;
	var	i;

	var	fragmentIndex;

	var	anchorID;
	var	anchorElement;

	linkElems = document.getElementsByTagName('a');
	
	for (i = 0; i < linkElems.length; i++)
	{
		if ((fragmentIndex = linkElems[i].getAttribute('href').indexOf('#')) != -1)
		{
			anchorID = linkElems[i].getAttribute('href').slice(fragmentIndex + 1);

			if (anchorElement = document.getElementById(anchorID))
			{
				linkElems[i].onclick = function ()
					{
						//	Capture the anchor in a local
						//	variable to form a closure.
						var	theAnchorElem;
							
						theAnchorElem = this.ourAnchor;
						setTimeout(
							function ()
							{
								scrollToAnchor(theAnchorElem);
							},100);
					};
				linkElems[i].ourAnchor = anchorElement;
			};
		};
	};
};

