
(function(jQuery) {

	jQuery.fn.pagination = function(options) {
		return this.each(function() {
			return new jQuery.pagination(this, options);
		});
	};

	jQuery.pagination = function(element,options) {

		//store options etc
		this.element = jQuery(element);
		this.options = jQuery.extend({
			numPages		: null,
			onPageChange	: null, 
			numPagesToShow	: 15,	
			currentPage		: 1,    
			animatedScroll  : true,  
			secondaryElements : [] 
		},options);

		//current page
		this._currentPage = this.options.currentPage;

		//numPages
		this._numPages = this.options.numPages;

		//number of pages to show
		this._numPagesToShow = Math.ceil(this.options.numPagesToShow / 2);

		this._updateElements();
	};

	/**
	 * Protected members
	 */
	jQuery.extend(jQuery.pagination.prototype, {
		_currentPage : null,
		_numPages : null,
		_updateElements : function() {
			var self = this;

			//empty element container
			this.element.html('');

			//previous page
			this.element.append('<a href="javascript:;" class="prev"><</a>');
			if (this._currentPage == 1) {
				jQuery('.prev', this.element).hide();
			}

			this.element.append('<span>'+this._currentPage+' / '+this._numPages+'</span>');
			

			//next
			if (this._currentPage < this._numPages) {
				this.element.append('<a href="javascript:;" class="next">></a>');
			}

			this._addEvents();

		},

		_addEvents : function() {
			var self = this;
			jQuery('a', this.element).bind('click', function() {
				if(jQuery(this).hasClass('prev')) {
					self._currentPage--;
				} else if (jQuery(this).hasClass('next')) {
					self._currentPage++;
				} 
				self._updateElements();
				self._scrollToTop();
				self.options.onPageChange(self._currentPage);
			});
		},

		_scrollToTop : function() {
			var speed = 0;
			if (this.options.animatedScroll) {
				speed = 150;
			}
			jQuery('html, body').animate({
				scrollTop: jQuery("body").offset().top
			}, speed);
		}
	});
})(jQuery);
