/**
 * paging.js
 *
 * Methods for handling AJAX paging
 *
 * @author     Daniel Z
 * @copyright  2007 Comet Information Systems Ltd, All Rights Reserved.
 * @requires   common.js
 */



/*
 * Initiates an AJAX request to retrieve paged data
 * @param {String} baseLink The url which returns the data
 * @param {String} containerId The ID of the html element to be updated with the retrieved data
 */
function ajaxPaging(baseLink, containerId) {
    new Ajax.Updater(containerId, baseLink, {});
    window.location.href="#top";
}


/*
 * Get the vertical distance in pixels the user had scrolled
 */
function getScrollTop() {
    try {
        var scrollTop = document.body.scrollTop;
        if (scrollTop == 0) {
            if (window.pageYOffset) {
                scrollTop = window.pageYOffset;
            } else {
                scrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
            }
        }
        return scrollTop;
    } catch(ex) {
        return 0;
    }
}

// Global variables for using the auto-paging widget
var autoPagingActive = false;
var autoPagingLink;
var autoPagingContainer;
var autoPagingPageNumber = 1;
var autoPagingPageSize;
var autoPagingTotalResults;


/*
 * Initiates the auto paging widget
 * @param {String} baseLink The url which returns the data
 * @param {String} containerId The ID of the html element to be appended with the retrieved data
 */
function autoPagingInit(baseLink, containerId, pageSize, totalResults) {
    autoPagingLink = baseLink;
    autoPagingContainer = containerId;
    autoPagingPageSize = pageSize;
    autoPagingTotalResults = totalResults;

    window.onscroll = autoPagingScroll;
}


/*
 * This method is bound to the window.onscroll event and will require the next page if needed
 */
function autoPagingScroll() {
    if(!autoPagingActive && Math.ceil(autoPagingTotalResults/autoPagingPageSize) >= autoPagingPageNumber){
        var scrolled = getScrollTop();
        if(document.body.clientHeight - window.innerHeight - scrolled < 50) autoPagingGet();
    }
}

/*
 * Updates the container with the next page
 */
function autoPagingGet() {
    autoPagingActive = true;
    gebi('autoPagingLoader').style.display = 'block';  
    //
    new Ajax.Updater(autoPagingContainer, autoPagingLink, {
        parameters: {pageSize: autoPagingPageSize, pageNumber: autoPagingPageNumber+1},
        insertion: Insertion.Bottom,
        onException:generalAJAXFailure,
        onFailure:generalAJAXFailure,
        onSuccess:function() {
           autoPagingPageNumber++;
        },
        onComplete: function() {
            autoPagingActive = false;
            gebi('autoPagingLoader').style.display = 'none';
        }
    });
}