/*****************************
/* Tools for scroll handling
/*****************************

/**
 * Saves the state of the scroll into cookies
 */
function saveScroll()
{
    var pageScroll = document.documentElement.scrollTop;
    var licensesScroll = 0;

    // The listOfLicenses element is created only in DocReview mode.
    // We need to check if this element exists before getting its scroll state.
    var listOfLicensesElement = document.getElementById( "listOfLicenses" );
    if ( listOfLicensesElement != null )
        licensesScroll = listOfLicensesElement.scrollTop;

    setCookieImpl( "pageScroll", pageScroll.toString() );
    setCookieImpl( "licensesScroll", licensesScroll.toString() );

    // Save also the current URL
    setCookieImpl( "currentURL", document.URL );
}

/**
 * Retrieves and sets the scroll state using cookies values
 */
function restoreScroll()
{
    // If the URL of the page hasn't changed, we retrieve the state of the scrolling
    if ( getCookieImpl( "currentURL" ) ==  document.URL )
    {
        var pageScroll = Number( getCookieImpl("pageScroll") );
        var licensesScroll = Number( getCookieImpl("licensesScroll") );

        if ( pageScroll != NaN )
            document.documentElement.scrollTop = pageScroll;

        if ( licensesScroll != NaN )
        {
            // We set the scroll state of "listOfLicenses" only if it exists (DocReview mode)
            var listOfLicensesElement = document.getElementById( "listOfLicenses" );
            if ( listOfLicensesElement != null )
                listOfLicensesElement.scrollTop = licensesScroll;
        }
    }
}

/**
 * Calls a function when the scroll state of the object changes
 * @param object is the object to listen
 * @param action is the function to call when the state of the scroll changes
 */
function addScrollListener( object, action )
{
    if ( object.addEventListener )
        object.addEventListener( 'scroll', action, false );
    // IE compatibility
    else if ( object.attachEvent )
        object.attachEvent( 'onscroll', action );
}

/**
 * Calls a function when the object is reloaded
 * @param object is the object to listen
 * @param action is the function to call when the object is reloaded
 */
function addReloadListener( object, action )
{
    if ( object.addEventListener )
        object.addEventListener( 'load', action, false );
    // IE compatibility
    else if ( object.attachEvent )
        object.attachEvent( 'onload', action );
}

addScrollListener( window, saveScroll );
addReloadListener( window, restoreScroll );
