/*
 * This function let's us scroll to a particular item in a scrollable div.
 */
function scrollToItem(itemID, scrollableContainerID) {
    var item = document.getElementById(itemID);
    if(item) {
        var scrollable = document.getElementById(scrollableContainerID);
        if(scrollable) {
            // Determine the offset of the selected result in relation to the scrollable area
            var pos = getElementTopOffsetFromContainer(item, scrollable);

            if(pos < scrollable.scrollHeight) {
                // Scroll to the current doc!
                scrollable.scrollTop = pos;
                // IE WORKAROUND - Set it again, because sometimes IE doesn't scroll the full distance.
                scrollable.scrollTop = pos;
            } else {
                scrollable.scrollTop = scrollable.scrollHeight;
            }
        }
    }
}

/*
 * Gets the position in pixels of the top of the element relative to a containing
 * element. It is assumed that the element is a decendant of the containing element.
 */
function getElementTopOffsetFromContainer(element, scrollableContainer) {
    // element position relative to browser's view area
    var elementTopPx = getElementTopOffset(element);

    // scrollable div position relative to the browser's view area
    var scrollableTopPx = getElementTopOffset(scrollableContainer);

    // return the top relative to the scrolling container
    var pos = elementTopPx - scrollableTopPx
    return pos;
}

/*
 * Gets the position in pixels of the top of the element in relation to the browser's
 * view area.
 */
function getElementTopOffset(element) {
    var topPosPx = element.offsetTop; //Units of pixels
    var parentElement = element.offsetParent;

    // To find the real offset from the top of the viewable area for the
    // Item, follow up the chain of containment since most modern browsers
    // give the offset relative to the containing element.
    while (parentElement != null) {
        topPosPx += parentElement.offsetTop;
        parentElement = parentElement.offsetParent;
    }

    return topPosPx;
}


