/* Paginator.js - Requires JQuery */
function Paginator(target, url, options) {
	this.init(target, url, options);
}

$.extend(Paginator.prototype, {
	target : '',
	url : '',
	page : 0,
	limit : 100,
	load : true,
	params : '',
	count : -1,
	total : -1,
	pages : -1,

	init : function(target, url, options) {
		this.target = target;
		this.url = url;
		if (options) {
			if (options.page) this.page = options.page - 1;
			if (options.limit) this.limit = options.limit;
			if (options.load || options.load === false) this.load = options.load;
			if (options.params) this.params = options.params;
		}

		if (this.load) {
			this.go(this.page);
		} else {
			this.count = $(this.target + ' input[name=search_results_count]').val();
			this.total = $(this.target + ' input[name=search_results_total]').val();
			this.pages = Math.ceil(this.total / this.limit);
			this.renderControls();
		}
	},
	
	go : function(page) {
		var _obj = this;
		if (page < 0) page = 0;
		if (this.pages != -1 && page >= this.pages) page = this.pages - 1;
		this.page = page;
		var params = 'page='+page+'&limit='+this.limit;
		if (this.params != '') params += '&'+this.params;
		if (this.total == -1) params += '&count=true';
		$(this.target).load(this.url, params, function() {
			_obj.count = $(_obj.target + ' input[name=search_results_count]').val();
			if (_obj.total == -1) {
				_obj.total = $(_obj.target + ' input[name=search_results_total]').val();
				_obj.pages = Math.ceil(_obj.total / _obj.limit);
			}
			_obj.renderControls();
		});
	},
	
	next : function() {
		this.go(this.page+1);
	},
	
	previous : function() {
		this.go(this.page-1);
	},
	
	renderControls : function() {
		if (this.pages > 1) {
			var _obj = this;
			
			var content = '<div style="text-align: center;">';
			if (this.page > 0) {
				content += '<a class="prev_button" href="#">&lt; Previous</a> '
			}
			content += 'Page <form style="display: inline;" class="page_input"><input type="text" size="3" value="'+(this.page+1)+'" /></form> of '+this.pages;
			if (this.page + 1 < this.pages) {
				content += ' <a class="next_button" href="#">Next &gt;</a>'
			}
			content += '</div>';
			$(this.target).prepend(content);
			$(this.target).append(content);
			
			$(this.target + ' form.page_input').submit(function(event) {
				_obj.go(parseInt(event.target.elements[0].value)-1);
				event.preventDefault();
			});
			
			$(this.target + ' a.prev_button').click(function(event) {
				_obj.previous();
				event.preventDefault();
			});
			
			$(this.target + ' a.next_button').click(function(event) {
				_obj.next();
				event.preventDefault();
			});
		}
	}
});