// Requires prototype and script.aculo.us

/* Expects a series of lists with naming convention (id_prefix)_list(listnum),
   the first with standard properties and the others with style="display: none;" set 
   as a node attribute. You should register the number of list items before you
   start paging. The rest of the code should be mainly self-explanatory.
*/

Paginator = function(id_prefix, per_page) {
	this.pages = 1;
	this.current_page = 1;
	this.total_items = 1;
	this.init(id_prefix, per_page);
}
Paginator.prototype.init = function(id_prefix, per_page) {
	this.id_prefix = id_prefix;
	this.per_page = per_page;
	
	this.button_image_prefix = "button_scroll";
	
	this.button_suffix = "button";
	this.paginator_info_suffix = "paginator_info";
	this.list_suffix = "list";
}
	Paginator.prototype.reset = function() {
		this.go_to_page(1);
	}
	Paginator.prototype.register_list_items = function(num_items) {
		this.pages = Math.ceil(num_items/this.per_page);
		this.total_items = num_items;
	}
	Paginator.prototype.previous_page = function() {
		return (this.current_page <= 1)? false : this.go_to_page(this.current_page-1);
	}
	Paginator.prototype.next_page = function() {
		return (this.current_page >= this.pages)? false : this.go_to_page(this.current_page+1);
	}
	Paginator.prototype.go_to_page = function(pagenum) {
		if(0 < pagenum <= this.pages && pagenum != this.current_page) {
			Element.hide(this.id_prefix+"_"+this.list_suffix+"_"+this.current_page);
			this.current_page = pagenum;
			Element.show(this.id_prefix+"_"+this.list_suffix+"_"+pagenum);
			new Effect.Highlight(this.id_prefix+"_"+this.list_suffix+"_"+pagenum);
			this.update_page_info(pagenum);
			this.update_button("up",((pagenum > 1)? "active" : "off"));
			this.update_button("down",((pagenum >= this.pages)? "off" : "active"));
			return true;
		} else {
			return false;
		}
	}
	Paginator.prototype.update_page_info = function(pagenum) {
		$(this.id_prefix+"_"+this.paginator_info_suffix).innerHTML = (((pagenum-1)*this.per_page)+1)+"-"+((this.total_items < pagenum*this.per_page)? this.total_items : (pagenum*this.per_page))+" of "+this.total_items+" items";
	}
	Paginator.prototype.update_button = function(button,state) {
		$(this.id_prefix+"_"+this.button_suffix+"_"+button).src = "/images/"+this.button_image_prefix+"_"+button+"_"+state+".png";
	}