var paging = Class.create();
paging.prototype = {
    initialize: function(params) {
        var that = this;
        // текущая страница
        this.pageNum = 1;
        // по сколько записей на страницу
        this.perPage = 10;
        // количество записей всего
        this.total = 190;
        // количество страниц всего (вычисляется далее)
        this.pagesCount;
        // листание сразу по клику
        this.quickWrite = true;
        // параметры eval скрипта
        this.scriptParams = {};
        Object.extend(this, params);
        // инициализация
        window[this.name] = this;

        this.pagingBar = $(this.name);

        var tpls = ['pageTpl', 'pageNumTpl', 'dotsTpl', 'prevTpl', 'nextTpl', 'prevDis', 'nextDis', 'pagerTpl'];
        var descendants = this.pagingBar.descendants();
        descendants.each(function(el) {
            tpls.each(function(tplTitle) {
                if (el.id == tplTitle) {
                    that[tplTitle]= el.innerHTML;
                    el.remove();
                }
            });
        });
    },

    write: function() {
        var that = this;
        // получить количество страниц (ссылок) пейджинга
        this.pagesCount = Math.ceil(this.total/this.perPage);
        if (this.pagesCount < 2) {
            this.pagingBar.hide();
            return;
        }
        this.pagingBar.show();
        var pages = this.calc();
        this.pagingBar.innerHTML = "";
        if (this.pagesCount <= 1)
            return;
        var html = "";
        var pager = "";
        var next = "";
        var prev = "";
        pages.each(function(p) {
            var item;
            if (p == that.pageNum)
                item = that.replaceTags(that.pageNumTpl, p);
            else
            if (p == '...')
                item = that.replaceTags(that.dotsTpl, p);
            else
                item = that.replaceTags(that.pageTpl, p);
            pager += item;
        });
        html = this.pagerTpl.replace(/#\{pager\}/g, pager);
        if (this.prevTpl) {
            if ((this.pageNum - 1) >= 1)
                prev = this.prevTpl.replace(/#\{pr\}/g, 'pagePrev'+this.name);
            else
                prev = this.prevDis;
            html = html.replace(/#\{prev\}/g, prev);
        }
        if (this.nextTpl) {
            if ((this.pageNum + 1) <= this.pagesCount)
                next = this.nextTpl.replace(/#\{nx\}/g, 'pageNext'+this.name);
            else
                next = this.nextDis;
            html = html.replace(/#\{next\}/g, next);
        }
        html = html.replace(/#\{total\}/g, this.total);
        this.pagingBar.innerHTML = html;
        // привязка к событию click
        pages.each(function(p) {
            if ($("page"+that.name+p))
                Event.observe($("page"+that.name+p), 'click', that.pagingClick.bindAsEventListener(that, p));
        });
        if ($("pagePrev"+this.name))
            Event.observe($("pagePrev"+this.name), 'click', this.pagingClick.bindAsEventListener(this, (this.pageNum - 1)));
        if ($("pageNext"+this.name))
            Event.observe($("pageNext"+this.name), 'click', this.pagingClick.bindAsEventListener(this, (this.pageNum + 1)));
    },

    replaceTags: function(text, replacement) {
        if (!text)
            return replacement;
        text = text.replace(/#\{elem\}/g, 'page'+this.name+replacement);
        text = text.replace(/#\{p\}/g, replacement);
        return text;
    },

    pagingClick: function(e, p) {
        this.pageNum = p;
        if (this.quickWrite == true)
            this.write();
        if (this.onPageScript) {
            var func = this.onPageScript;
            func = func.replace(/#\{pagenum\}/g, p);
            func = func.replace(/#\{params\}/g, Object.toJSON(this.scriptParams));
            eval(func);
        }
    },

    // вычислить строку навигации
    calc: function () {
        var i, curr, max;
        curr = this.pageNum;
        max = this.pagesCount;
        if (max < 1)
            max = 1;
        if (curr > max)
            curr = max;
        var pages = new Array;
        // начало
        pages.push(1);
        if (max > 1)
            pages.push(2);
        // серединка
        var around = 2;
        i = curr - around;
        i = (i < 1) ? 1 : i;
        while ((i <= max) && (i <= (curr+around))) {
            pages.push(i);
            i++;
        }
        // конец
        if ((max - 1) > 0)
            pages.push(max - 1);
        pages.push(max);
        pages = pages.uniq();
        var res = new Array;
        pages.each(function(s, index) {
            res.push(s);
            if ((pages[index + 1]) && ((s + 1) != pages[index + 1])) {
                if ((s + 2) == pages[index + 1])
                    res.push(s + 1);
                else
                    res.push('...');
            }
        });
        return res;
    }
};