;(function($) {
	$.widget('ui.paginate', {
		_redraw: function() {
			var _e = this.element, _o = this.options, self = this;
			
			_e.children('a.page, strong.page').remove();
			if (_o.count <= _o.perPage) {
				_e.hide();
				return;
			}
			
			_e.show();
			
			var _content = '',
			_min_dispose = Math.ceil(_o.page - (_o.pagesLength / 2)),
			_min_bound = (_min_dispose < 1) ? 1 : _min_dispose,
			_max_bound = (_min_bound + _o.pagesLength) > _o._max_page ? _o._max_page : (_min_bound + _o.pagesLength);
			
			
			for (var _j = _min_bound; _j <= _max_bound; _j++)
				_content += (_j == _o.page) ? '<strong class="page">' + _j + '</strong>' : '<a href="#" class="page">' + _j + '</a>';
			_e.children('a.prev').after(_content);
		},
		
		_init: function() {
			var _e = this.element, _o = this.options, self = this;
			_e.addClass('list');
			_e.append('<a class="prev" href="#"></a>');
			_e.append('<a class="next" href="#"></a>');
			_o._min_page = 1;
			_o._max_page = Math.ceil(_o.count / _o.perPage)
			
			_e.click(function(_ev) {
				var _t = $(_ev.target);
				if (_t.filter('a.next').length) {
					_ev.preventDefault();
					if ((_o.page + 1) <= _o._max_page) {
						_o.page += 1;
						if (typeof(_o.onSelect) == 'function')
							_o.onSelect.call(self.element, _o.page);
						self._redraw();
					}
				} else if (_t.filter('a.prev').length) {
					_ev.preventDefault();
					if ((_o.page - 1) >= 1) {
						_o.page -= 1;
						if (typeof(_o.onSelect) == 'function')
							_o.onSelect.call(self.element, _o.page);
						self._redraw();
					}
				} else if (_t.filter('a.page').length) {
					_ev.preventDefault();
					var _val = parseInt(_t.text(), 10);
					_o.page = _val;
					if (typeof(_o.onSelect) == 'function')
						_o.onSelect.call(self.element, _o.page);
					self._redraw();
				}
			});
			
			this._redraw();
		},
		setPage: function(_p) {
			this.options.page = parseInt(_p, 10);
			this.options._max_page = Math.ceil(this.options.count / this.options.perPage);
			this._redraw();
		},
		setCount: function(_c) {
			this.options.count = parseInt(_c, 10);
			this.options._max_page = Math.ceil(this.options.count / this.options.perPage);
			this._redraw();
		},
		setPerPage: function(_pp) {
			this.options.perPage = parseInt(_pp);
			this.options._max_page = Math.ceil(this.options.count / this.options.perPage);
			this.redraw();
		}
	});
})(jQuery);

$.extend($.ui.paginate.prototype, {
	options: {
		page: 1,
		count: 1,
		perPage:1,
		onSelect: function(_v){},
//		nextLabel: 'Ñþäà',
//		prevLabel: 'Òóäà',
		pagesLength: 20
	}
});
