/* Paginator plugin for jQuery
- http://www.doubleclique.com
- 2009 Kyle Beattie

Minimum CSS:


Ideal markup example:

 */

(function($){
	$.fn.paginator = function(options) {
		var settings = $.extend(
			{
				sectionsPerPage:1
			},
			options
		);
		return this.each(function(index, el) {
			var nextBttn = $(this).closest('.column').find('.next');
			var prevBttn = $(this).closest('.column').find('.prev');
			var pageIconHolder = $(this).closest('.column').find('.pages div');
			var inc = $(this).width();
			var $liner = $(this).children();
			var pages = $(this).find('ul').length;
			var position = 0;
			var numOfPages = Math.ceil(($(this).find('ul').length)/settings.sectionsPerPage);
			var maxPosition = numOfPages-1;

			for(i=0;i<numOfPages;i++){
				$(pageIconHolder).append('<span></span>');
			}

			$liner.width(($(this).find('ul').outerWidth()+parseInt($(this).find('ul').css('margin-right'))+parseInt($(this).find('ul').css('margin-left')))*$(this).find('ul').length);

			$(this).height($liner.outerHeight());
			$liner.height($liner.outerHeight());

			var updatePageIcons = function() {
				$(pageIconHolder).find('span').each(function(i){
					if(i==position){
						$(this).addClass('current');
					}else{
						if($(this).hasClass('current')) $(this).removeClass('current');
						$(this).bind('click',function(){
							animateIt(i*(-inc));
							position = i;
						})
					}
				});
			};

			var animateIt = function(left) {
				$liner.animate(
				{
					left: left
				},
				{
					queue: false,
					duration: 350
				}
				);
				updatePageIcons();
			};

			var rightAnimate = function() {
				if (position < maxPosition) {
					position++;
					animateIt(position * (-inc));
				}
			};

			var leftAnimate = function() {
				if (position > 0) {
					position--;
					animateIt(position * (-inc));
				}
			};

			nextBttn.bind('click',function(ev){
				ev.preventDefault();
				rightAnimate();
			});

			prevBttn.bind('click',function(ev){
				ev.preventDefault();
				leftAnimate();
			});
			updatePageIcons();

		});
	};
})(jQuery);

