(function ($) {
	// Default configuration properties.
	var defaults = {
		pageHolder: '#holder',
		arrowPrev: '#arrowPrev',
		arrowNext: '#arrowNext',
		number: 50,
		now: 1,
		perPage: 10,
		pageLinkWrapper: null
	};
	$.pagination = function (opt) {
		this.options = $.extend({}, defaults, opt || {});

		this.current_page = this.options.now;
		this.pages_count = Math.ceil(this.options.number / this.options.perPage);

		this.getPagerContainer = function () {
			return $(this.options.pageHolder);
		};
		this.getPagePrev = function () {
			return $(this.options.arrowPrev);
		};
		this.getPageNext = function () {
			return $(this.options.arrowNext);
		};

		this.setButtons = function () {
			var arrowPrev = this.getPagePrev();
			var arrowNext = this.getPageNext();

			if (this.current_page == 1) {
				arrowPrev.addClass('disabled');
			} else {
				arrowPrev.attr('href', '#p=' + (parseInt(this.current_page) - 1)).removeClass('disabled');
			}
			if (this.current_page == this.pages_count) {
				arrowNext.addClass('disabled');
			} else {
				arrowNext.attr('href', '#p=' + (parseInt(this.current_page) + 1)).removeClass('disabled');
			}
			var showScrollButtons = this.pages_count > 1;
			arrowPrev.css('visibility', showScrollButtons ? 'visible' : 'hidden');
			arrowNext.css('visibility', showScrollButtons ? 'visible' : 'hidden');
		};
		this.pagGeneratePages = function (from, to) {
			var pages = '';
			for (var i = from; i <= to; i++) {
				var active = '';
				if (i == this.current_page) {
					active = 'class="active"';
				}
				if(this.options.pageLinkWrapper) {
					pages += '<' + this.options.pageLinkWrapper + '>'
				}
				pages += '<a ' + active + ' href="#p=' + i + '">' + i + '</a>';
				if(this.options.pageLinkWrapper) {
					pages += '</' + this.options.pageLinkWrapper + '>'
				}
			}
			return pages;
		};
		this.leftPart = function () {
			return (this.current_page < 6) ? this.pagGeneratePages(1, 6) : this.pagGeneratePages(1, 1) + '...';
		};

		this.middlePart = function () {
			var page = parseInt(this.current_page);
			return (page >= 6 && (this.pages_count - page > 3)) ? this.pagGeneratePages(page - 2, page + 2) : '';
		};

		this.rightPart = function () {
			return (this.pages_count - this.current_page <= 3) ? this.pagGeneratePages(this.pages_count - 5, this.pages_count)
				: '...' + this.pagGeneratePages(this.pages_count, this.pages_count);
		};

		this.setPagination = function () {
			var pagin_div = '';
			if (this.pages_count > 10) {
				pagin_div = this.leftPart() + this.middlePart() + this.rightPart();
			} else if (this.pages_count > 1) {
				pagin_div = this.pagGeneratePages(1, this.pages_count);
			}
			this.setButtons();
			this.getPagerContainer().html(pagin_div);
		};
		this.setPagination();
	};
	$.pagination.getCurrentPageFromHash = function () {
		var matches = location.hash.match(/p=([^&]*)/);
		return matches ? matches[1] : null;
	}
})(jQuery);
