var Pager = function(list, length) {
	this.$list = $(list);
	
	this.itemsCount = this.$list.children().length;
	this.pageLength = length;
	this.pagesCount = Math.ceil(this.itemsCount / this.pageLength);
	if(this.pagesCount > 1) {
		this.$container = this.$list.after('<div id="pager"></div>');
		this.construct($('#pager'));
		this.setPage(0);
	}
};

Pager.prototype.setPage = function(page) {
	this.$list.children().hide();
	
	var first = page * this.pageLength;
	for(var i=first; i<first + this.pageLength; i++) {
		$(this.$list.children().get(i)).show();
	}
	
	if(page <= 0) {
		$('#pager a.prev').hide();
		$('#pager a.next').show();
		this.currentPage = 0;
	} else if(page >= this.pagesCount - 1) {
		$('#pager a.prev').show();
		$('#pager a.next').hide();
		this.currentPage = this.pagesCount - 1;
	} else {
		$('#pager a.prev').show();
		$('#pager a.next').show();
		this.currentPage = page;
	}
	
	$('#pager p.pages a').removeClass('current');
	$('#pager p.pages a:eq(' + page + ')').addClass('current');
};

Pager.prototype.construct = function($container) {
	var self = this;
	
	$container.append('<a class="prev">Précédent</a>');
	$container.append('<p class="pages"></p>');
	$container.append('<a class="next">Suivant</a>');
	
	var $pages = $container.children('p.pages');
	
	for(var i=0; i < this.pagesCount; i++) {
		if(i > 0) $pages.append('-');
		$pages.append('<a>&nbsp;&nbsp;' + (i+1) + '&nbsp;&nbsp;</a>');
	}
	
	$pages.children('a').each(function(index) {
		$(this).click(function() {
			self.setPage(index);
		});
	});
	
	$container.children('a.prev').click(function() {
		self.setPage(self.currentPage - 1);
	});
	
	$container.children('a.next').click(function() {
		self.setPage(self.currentPage + 1);
	});
};
