/* Copyright 2003-2008 Emergent Music LLC  All rights reserved.
$Id$
*/

// Paging class - handles the counting of items

FLYFI.Paging = function (defaultPageSize) {
    var self = this;
    
    self.DEFAULT_ITEMSTOSHOW = defaultPageSize === undefined ? 50 : defaultPageSize;
    
    self.available = 0;     // total number that can be shown
    self.start = 0;         // first item to show
    self.end = 0;           // one more than the last item showing
    self.itemsToShow = self.DEFAULT_ITEMSTOSHOW;  // desired number to show (if user changes this then temporarily this.start + this.count may not equal this.end)
    
    self.clear = function() {
        self.available = 0;
        self.start = 0;
        self.end = 0;
    };

    self.setItemsShown = function(count) {
        // call after showing a page to record how many were shown
        self.end = self.start + count;
    };
    
    self.getPageEnd = function() {
        // return the end count for the current page.  Note: does NOT set the end (on the assumption that the
        // calling code may not actually be able to supply the items), so after showing the items, call
        // self.setItemsShown()
        return Math.min(self.available, self.start + self.itemsToShow);
    };
    
    self.allOnOnePage = function() {
        // return whether all of the available items fit on a single page
        return (self.start === 0) && (self.available <= self.itemsToShow);
    };
    
    self.prev = function() {
        // changes start to the beginning of the new page.  Does NOT change end - call this.setItemsShown to set end.
        // returns whether the paging changed
        if (self.start === 0) {
            return false; // already at start
        }
        
        if (self.start <= self.itemsToShow) {
            self.start = 0;
        } else {
            self.start -= self.itemsToShow;
        }
        return true;
    };

    self.next = function() {
        // changes start to the beginning of the new page.  Does NOT change end - call this.setItemsShown to set end.
        // returns whether the paging changed
        if (self.available <= self.end) {
            return false; // already at end
        }
        self.start = self.end;
        return true;
    };
};

