(function($){

// Creating the sweetPages jQuery plugin:
$.fn.pageNav = function(opts){

	// If no options were passed, create an empty opts object
	if(!opts) opts = {};

	var resultsPerPage = opts.perPage || 3;

	// The plugin works best for unordered lists,
	// although OLs would do just as well:
	var ul = this;
	var li = ul.find('li');

	li.each(function(){
		// Calculating the height of each li element,
		// and storing it with the data method:

		var el = $(this);
		el.data('height',el.outerHeight(true));
	});

	// Calculating the total number of pages:
	var pagesNumber = Math.ceil(li.length/resultsPerPage);

	// If the pages are less than two, do nothing:
	if(pagesNumber<2) return this;

	// Creating the controls div:
	var pnControls = $('<div class="pnControls">');

	for(var i=0;i<pagesNumber;i++)
	{
		// Slice a portion of the li elements, and wrap it in a pnPage div:
		li.slice(i*resultsPerPage,(i+1)*resultsPerPage).wrapAll('<div class="pnPage" />');

		// Adding a link to the pnControls div:
		pnControls.append('<a href="" class="pnShowPage">'+(i+1)+'</a>');
	}

	ul.append(pnControls);
	
	var maxHeight = 0;
	var totalWidth = 0;

	var pnPage = ul.find('.pnPage');
	pnPage.each(function(){

		// Looping through all the newly created pages:

		var elem = $(this);

		var tmpHeight = 0;
		elem.find('li').each(function(){tmpHeight+=$(this).data('height');});

		if(tmpHeight>maxHeight)
			maxHeight = tmpHeight; 
			
		var bufferWidth = 10;
		totalWidth+=elem.outerWidth() + bufferWidth;

		elem.css('float','left').width(ul.width());
	});

	pnPage.wrapAll('<div class="pnSlider" />');

	// Setting the height of the ul to the height of the tallest page:
	ul.height(maxHeight);

	var pnSlider = ul.find('.pnSlider');
	pnSlider.append('<div class="clear" />').width(totalWidth);

	var hyperLinks = ul.find('a.pnShowPage');

	hyperLinks.click(function(e){

		// If one of the control links is clicked, slide the pnSlider div
		// (which contains all the pages) and mark it as active:

		$(this).addClass('active').siblings().removeClass('active');

		pnSlider.stop().animate({'margin-left': -(parseInt($(this).text())-1)*ul.width()},'slow');
		e.preventDefault();
	});

	// Mark the first link as active the first time the code runs:
	hyperLinks.eq(0).addClass('active');

	// Center the control div:
	pnControls.css({
		'left':'50%',
		'margin-left':-pnControls.width()/2
	});

	return this;

}})(jQuery);

var $kn = jQuery.noConflict();
$kn(document).ready(function(){
	/* The following code is executed once the DOM is loaded */

	// Calling the jQuery plugin and splitting the
	// #holder UL into pages of 3 LIs each:
	$kn('.paginationHolder').pageNav({perPage:4});

	// The default behaviour of the plugin is to insert the
	// page links in the ul, but we need them in the main container:

	var controls = $kn('.pnControls').detach();
	controls.appendTo('.navigationMain');

});

