/**
 * Creates paging
 */
function ApOnPager(list, idPrefix, navigator, itemsPerPage)
{
    this.list = list;
    this.idPrefix = idPrefix;
    this.navigator = navigator;
    this.itemsPerPage = itemsPerPage;
    this.init();
}

ApOnPager.prototype.computePages = function()
{
    var count = 0;
    this.nodeList = new Array();
    for (var i = 0; i < this.list.childNodes.length; i++) {
        var node = this.list.childNodes[i];
        if (node.nodeType == 1) {
            if (this.idPrefix == "" || (node.id && node.id.substr(0, this.idPrefix.length) == this.idPrefix)) {
                if (!node.hidden) {
                    count++;
                    this.nodeList[this.nodeList.length] = node;
                }
            }
        }
    }
    this.totalItems = count;
    this.numberOfPages = Math.floor(this.totalItems/this.itemsPerPage);
    if (this.numberOfPages * this.itemsPerPage < this.totalItems) {
        this.numberOfPages++;
    }
}



ApOnPager.prototype.init = function()
{
    this.computePages();
    this.navigator.empty();
    if (this.numberOfPages <= 1) {
        return;
    }

    this.currentPage = 1;

    this.pager = this.navigator.appendDiv("pager")
    var parent = this;
    //prev page
    this.left = this.pager.appendDiv("left");
    this.left.onclick = function () {
        parent.prev();
    }
    //show the pagers
    this.pages = new Array();
    for (var i = 1; i <= this.numberOfPages; i++) {
        this.pages[i] = this.pager.appendDiv(i == this.currentPage ? "pageSelected" : "page");
        eval("var switchFunction = function () { parent.switchTo(" + i + "); }");
        this.pages[i].onclick = switchFunction;
    }
    //next page
    this.right = this.pager.appendDiv("right");
    this.right.onclick = function () {
        parent.next();
    }
}

ApOnPager.prototype.switchTo = function(page)
{
    if (page < 1 || page > this.numberOfPages) {
        return;
    }
    this.pages[this.currentPage].className = "page";
    this.currentPage = page;
    this.pages[this.currentPage].className = "pageSelected";
    for (var i = 0; i < this.nodeList.length; i++) {
        var inPage = (i >= (this.currentPage - 1) * this.itemsPerPage && i <= this.currentPage * this.itemsPerPage);
        this.nodeList[i].style.display = inPage ? "block" : "none";
    }
}

ApOnPager.prototype.prev = function()
{
    if (this.currentPage > 1) {
        this.switchTo(this.currentPage - 1);
    }
}

ApOnPager.prototype.next = function()
{
    if (this.currentPage < this.numberOfPages) {
        this.switchTo(this.currentPage + 1);
    }
}

