

function Pager(containerName, itemsPerPage) {
    this.containerName = containerName;
    this.itemsPerPage = itemsPerPage;
    this.currentPage = 1;
    this.pages = 0;
    this.inited = false;
    this.items = "";
    this.containerType = document.getElementById(containerName).nodeName;

    this.getItems = function(containerName) {
        if (this.containerType == "TABLE"){
            var items = document.getElementById(containerName).rows;
        } else {
            var items = document.getElementById(containerName).getElementsByTagName('div');
        }
        return items;
    }

    this.showRecords = function(from, to) {
        start = 1;
        if (this.containerType != "TABLE") {
            // allow for TH row
            from -= 1;
            to -= 1;
            start = 0;
        }

        for (var i = start; i < this.items.length; i++) {
            if (i < from || i > to)
                this.items[i].style.display = 'none';
            else
                this.items[i].style.display = '';
        }
        window.scrollTo(0,0);
    }

    this.showPage = function(pageNumber) {
    	if (!this.inited) return;
        
        var oldPageAnchor = document.getElementById('pg'+this.currentPage);
        oldPageAnchor.className = 'pg-normal';

        this.currentPage = pageNumber;
        var newPageAnchor = document.getElementById('pg'+this.currentPage);
        newPageAnchor.className = 'pg-selected';

        var from = (pageNumber - 1) * itemsPerPage + 1;
        var to = from + itemsPerPage - 1;
        this.showRecords(from, to);
    }

    this.prev = function() {
        if (this.currentPage > 1) {
            this.showPage(this.currentPage - 1);
        }
    }

    this.next = function() {
        if (this.currentPage < this.pages) {
            this.showPage(this.currentPage + 1);
        }
    }

    this.init = function() {
        this.items = this.getItems(this.containerName);
        var records = (this.items.length);
        if (this.containerType == "TABLE") records -= 1; // allow for TH row
        this.pages = Math.ceil(records/itemsPerPage);
        this.inited = (this.pages > 1) ? true : false;
    }

    this.showPageNav = function(pagerName, positionId) {
    	if (!this.inited) return;
    	var element = document.getElementById(positionId);
    	var pagerHtml = '<span onclick="'+pagerName+'.prev();" class="pg-normal">&#171; </span>';
        for (var page = 1; page <= this.pages; page++) {
            //pagerHtml += '<a href="#' + page + '" id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');">' + page + '</a>';
            pagerHtml += '<a href="#' + page + '" id="pg' + page + '" class="pg-normal">' + page + '</a>';
            if (page < this.pages) pagerHtml += ' ';
        }
        pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal"> &#187;</span>';
        element.innerHTML = pagerHtml;
    }
}