var createPagination = function ($) {

    // public functions
    return {
        //main function
        page: 1,
        url: '/paginate/',
        selector: "ul.pagination li a",
        init: function () {
            var self = this;
            $('body').on("click", this.selector, function (e) {
                e.preventDefault();
                if( $(this).parent().hasClass('disabled')) {
                    return false;
                }
                var url = $(this).attr("href");
                var page = $(this).data("page");
                var container = $(this).parents('.pagination-container');
                self.paginate(url, page, container);
            });

            this.onChange.add(function () {
                $('[data-toggle="popover"]').popover();
            });
        },
        paginate: function (url, page, container, callBack) {

            this.page = page;
            this.url = url;
            var self = this;

            if(typeof page == 'undefined') {
                var queryParams = $.unparam(url.substring(url.indexOf('?')+1));

                if(queryParams.hasOwnProperty('page')) {
                    page      = queryParams.page;
                    this.page = page;
                }
            }

            $.ajax({
                url: url,
                dataType: "html",
                method: "GET",
                data: {page: page},
                beforeSend: function(){
                    ComitiumUtils.showSpinner();
                },
                success: function(data){
                    container.fadeOut(200, function () {

                        var element = $(data);
                        var extraData = {
                            element: element,
                            page: page
                        };

                        container
                          .replaceWith(element)
                          .fadeIn(500);

                        self.onChange.dispatch(element, extraData);
                    });
                },
                complete: function(){
                    ComitiumUtils.hideSpinner();
                    if (typeof callBack === 'function') {
                        callBack.call(this);
                    }
                }
            });
        },
        setUrl: function (url) {
            this.url = url;

            return this;
        },
        setDomSelector: function (selector) {
            this.selector = selector;

            return this;
        },
        onChange: new signals.Signal(),
        getPage: function() {
            return this.page;
        }
    };
};

var Pagination = createPagination($);


