/**
 * jQuery divPager plugin.
 *
 * Version 0.7 (21/01/2009)
 * @requires jQuery v1.2.6 or later
 * Copyright (c) 2008-2009 <GX> Creative Online Development
 *
 * This plugin divides divs over several pages. The user can select a page
 * number or a previous/next link. Also the number of items per page can be selected.
 *
 * Options:
 *	currentPage  :      Start page. Advise not to change this value. The page may not 
 *			      exist(depends on the numPerPage option).
 *	numPerPage   :      Value for the number of divs that should be shown per page. 
 *	pageNumbersVisible: Set this option to reduce the pagenumbers that are visible at a time.
 *			      setting it to -1 will ignore this feature. An odd number is advisable, because
 *                            the number of the pages to the left and right of the selected page will be the same.
 *      totalPages:         Set to true when total pages number should be shown. In the html a span with class 
 *                            'totalPages' should be added.
 *      pageDivClass :      Class for each div(within the pager) that needs to be paged. Default:'sort-column'
 *
 * Example:
 *     $('div.pager').divPager(); In this case the DOM structure should be:
 *			<div class="pager">
 * 			    <div class="sort-column">
 * 			    </div> 
 * 			    <div class="sort-column">
 * 			    </div> 
 * 			    <div class="sort-column">
 * 			    </div> 
 *                           .... 			
 *			</div> 
 *                      <ul>
 *                        <li class="prev"><a href="#">Vorige</a></li>
 *                        <li class="next"><a href="#">Volgende</a></li>
 *                        <li><span class="totalPages"></span></li>
 *                      </ul>
 * 
 * Notes:
 *     - The prev option should be a 'li' with class 'prev'.
 *     - The next option should be a 'li' with class 'next'.
 *	 e.g.:
 *         <ul>
 *           <li class="first"><a href="#">&lt;&lt;</a></li>
 *           <li class="prev"><a href="#">Vorige</a></li>
 *           <li class="next"><a href="#">Volgende</a></li>
 *	     <li class="last"><a href="#">&gt;&gt;</a></li>
 *         </ul>
 *     - The paging numbers will be inserted as 'li' before the li.next.
 *     - When the number of items per page should be adjustable by the user
 *          a strucure like the following one should be used(this is an example;
 *          only the 'a' is needed with the class 'numberofpages', within the element
 *          there should be a numeric value, so without additional elements surrounding it):
 *            <dl>
 *              <dt>Title</dt>
 *              <dd><a href="#" class="numberofpages">2</a></dd>
 *              <dd><a href="#" class="numberofpages">3</a></dd>
 *              <dd><a href="#" class="numberofpages">5</a></dd>
 *              <dd><a href="#" class="numberofpages">8</a></dd>
 *             </dl>
 *     
 * Limitations:
 *     - Only one divPager per page.
 *
 * Known issues:
 *	-
 *
 * @author erikvl
 * 
 */
(function($) {

	$.fn.divPager = function(options) {
		
		// Extend the default options with the provided ones.
		// First argument is an empty object to prevent overriding the default.
		var settings = $.extend({}, $.fn.divPager.defaults, options);

		return this.each(function() {
			
			$('li.first').unbind('click');
			$('li.last').unbind('click');
			$('li.prev').unbind('click');
			$('li.next').unbind('click');
			$('a.numberofpages').unbind('click');
			$('a.numberofpagesall').unbind('click');
			
			// Adjustable settings.
			var currentPage = settings.currentPage;
			var numPerPage = settings.numPerPage;
			var pageNumbersVisible = settings.pageNumbersVisible;
			var pageDivClass = settings.pageDivClass;
			var totalPages = settings.totalPages;
			var showNumberOfResults = settings.showNumberOfResults;
			var useAjaxForPaging = settings.useAjaxForPaging;
				
			// The div where the 'divPager' is active on.
			var $div = $(this);
			
			if (useAjaxForPaging && applicationData.prdproducts.prdlistinfo != undefined) {
				numRows = applicationData.prdproducts.prdlistinfo[0].numberofproducts;
			} else {
				numRows = $div.find('div.' + pageDivClass).length;
			}
			
			numPages = Math.ceil(numRows / numPerPage);
			
			// Determine number of page-options to the left and right of the selected page.
			leftRightNumber = Math.floor(pageNumbersVisible / 2);

			// Bind click event to the 'First'-option. Call adjustView to adjust the
			// view to the correct page.
			$('li.first').bind('click', function(event) {
				currentPage = 0;
				adjustView(true);
				reInitPageNumbers();
			});
			
			// Bind click event to the 'Last'-option. Call adjustView to adjust the
			// view to the correct page.
			$('li.last').bind('click', function(event) {
				currentPage = numPages-1;
				adjustView(true);
				reInitPageNumbers();
			});
			
			// Bind click event to the 'Previous'-option. Call adjustView to adjust the
			// view to the correct page.
			$('li.prev').bind('click', function(event) {
				if (currentPage > 0) {
					currentPage--;
					adjustView(true);
					reInitPageNumbers();
				}			
			});
					
			// Bind click event to the 'Next'-option. Call adjustView to adjust the
			// view to the correct page.
			$('li.next').bind('click', function(event) {
				if (currentPage < (numPages-1)) {
					currentPage++;
					adjustView(true);	
					reInitPageNumbers();
				}
			});
			
			// Bind click event to the number of items per page.
			$('a.numberofpages').bind('click', function() {
				// We remove the page numbers and rebuild them with the 'buildPageNumbers'.
				$('li.pagenumber').remove();
				// Reset current page to the first one. It could happen when selecting
				// a larger number of items per page, the page number we are on does not
				// excist anymore.
				currentPage = 0;	
				
				// Setup the new number of items per page.
				numPerPage = $(this).text();
				setNumPerPageSelectedDefault();
				
				buildPageNumbers();
				setTotal();
				// Adjust the view with the new number of items.
				adjustView(true);
				$('li.totalpages').show();
			});
			
			// Bind click event to the allpages
			$('a.numberofpagesall').bind('click', function() {
				$div.find('div.' + pageDivClass).show();
				$('li.pagenumber').remove();
				$('li.prev').hide();
				$('li.first').hide();
				$('li.next').hide();
				$('li.last').hide();
				$('li.totalpages').hide();
				$('a.numberofpages').removeClass('current');
				
				$('a.numberofpagesall').each(function() {
					$(this).addClass('current');
				});
			});
			
			// Sets the total number of pages into a span. It depends on the
			// number of divs per page and the total number of divs.
			function setTotal() {
				if (totalPages) {
					$('span.totalPages').text(numPages);
				}
			}
			
			// Sets the total number of results into a span. 
			function setNumberOfResults() {
				if (showNumberOfResults) {
					$('span.numberOfResults').text(numRows);
				}
			}
			
			// Add class current to the selected number divs per page.
			function setNumPerPageSelectedDefault() {
				$('a.numberofpages').removeClass('current');
				$('a.numberofpagesall').removeClass('current');
				
				$('a.numberofpages').each(function() {
					if ($(this).text()==numPerPage) {		
						$(this).addClass('current');
					}
				});
			}
			   
			// This function shows the page the user has selected(it shows the correct divs
			// and hides the rest). Furthermore it hides the 'Next'-option when there are
			// no more pages and it hides the 'Previous'-option when there are no previous pages.
			function adjustView(clicked) {
			
				// When using AJAX the initial data is loaded and after that the
				// pager is bound. Onclick we want to reload data. However not
				// bind the pager again. Which is normally done in the load function.
				// This would cause recursion, because this method is called in the init.
				// Just a switch for useAjaxForPaging would cause the recursion.
				if (clicked && useAjaxForPaging) {
					from = (currentPage * numPerPage);
					to = ((currentPage + 1) * numPerPage); //PR edit

					from = from + 3; //skip the popular 3
					to = to + 2;
					
					loadData(false);
				} else {
					var validDivs = $div.find('div.' + pageDivClass);
					var validDivsLength = validDivs.length;
					var lowerLimit = (currentPage * numPerPage);
					var upperLimit = ((currentPage + 1) * numPerPage - 1);

					for (i=0;i<validDivs.length;i++) {
						if (i<lowerLimit||i>upperLimit) {
							$(validDivs[i]).hide();
						} else {

							$(validDivs[i]).show();
							//$(validDivs[i]).find('img').attr(src) = 
						}
					}

					//$div.find('div.' + pageDivClass).show();
					//$div.find('div.' + pageDivClass + ':lt(' + (currentPage * numPerPage) + ')').hide();
					//$div.find('div.' + pageDivClass + ':gt(' + ((currentPage + 1) * numPerPage - 1) + ')').hide(); 
				}
				// Set up the next- and previous-options.
				// First the 'previous'.
				(currentPage > 0) ? $('li.prev').show() : $('li.prev').hide();
				(currentPage > 0) ? $('li.first').show() : $('li.first').hide();
				// Then the 'next'.
				(currentPage == (numPages-1) || numPages<=1) ? $('li.next').hide() :$('li.next').show();
				(currentPage == (numPages-1) || numPages<=1) ? $('li.last').hide() :$('li.last').show();

				setNumberOfResults();
			}
			
			// Setup the page numbers the user can select. It adds the numbers before the 'li' with
			// classname 'next'.
			function buildPageNumbers() {
				// Reset the pager pages.
				$('li.pagenumber').remove();
				$pager = $('li.next');
				if (useAjaxForPaging && applicationData.prdproducts.prdlistinfo != undefined) {
					numRows = applicationData.prdproducts.prdlistinfo[0].numberofproducts;
				} else {
					numRows = $('div.' + pageDivClass).length;
				}
				numPages = Math.ceil(numRows / numPerPage);
				if (currentPage == 0){ //exception, because first page shows numPerPage + 3 items!
					numPages = Math.ceil(numRows / (numPerPage + 3));
				}
			
				for (var page = 0; page < numPages; page++) {
				
					// NOTE: closure. 
					// The click handler refers to the page variable, which is defined outside the function. 
					// This means all clicks would refer to the same value(last value of the loop).
					// So we use the 'data' option in JQuery.

					$('<li class="pagenumber num' + (page + 1) + '"><a href="#">' + (page + 1) + '</a></li>')
					.bind('click', {'newPage': page}, function(event) {
						currentPage = event.data['newPage'];
						adjustView(true);
						reInitPageNumbers();
					})
					.insertBefore($pager).addClass('clickable');		
				}
				reInitPageNumbers();
			}
			
			// Setup the max number of pagenumbers to show.
			function reInitPageNumbers() {
				// Set current class.
				$('li.pagenumber').parent('ul').children('li').removeClass('current');
				
				// Foreach so we can use more than one pager(for example top and bottom).
				$('li.pagenumber').parent('ul').each(function() {
					currentSelector = 'li.num'+ (currentPage+1);
					
					$(this).find(currentSelector).addClass('current');
					if (pageNumbersVisible != -1 && numPages > pageNumbersVisible) {
						// Lower boundary.
						if ((currentPage - leftRightNumber) <= 0) {
							$(this).find('li.pagenumber:gt(' + (pageNumbersVisible-1) + ')').hide();
							$(this).find('li.pagenumber:lt(' + (pageNumbersVisible) + ')').show();
						} else {
							// Upper boundary.
							if ((currentPage + leftRightNumber)>=numPages) {
								$(this).find('li.pagenumber:lt(' + (numPages-pageNumbersVisible) + ')').hide();
								$(this).find('li.pagenumber:gt(' + (numPages-pageNumbersVisible) + ')').show();
							} else {
								// Default.
								$(this).find('li.pagenumber').hide();
								for (i=(currentPage - (leftRightNumber-1));i<(currentPage + (pageNumbersVisible-(leftRightNumber-1)));i++) {
									showSelector = 'li.num' + i;
									$(showSelector).show();
								}
							}
						}
					}
				})
			}
			
			// Function to initialize the 'divPager'.
			function init() {
				buildPageNumbers();
				setTotal();
				setNumPerPageSelectedDefault();
				adjustView(false);
			}
			
			init();
		});			
	};	
		
	// Setup the defaults. These can be overridden.
	$.fn.divPager.defaults = {
		currentPage:0,
		numPerPage:8,
		pageNumbersVisible:5,
		totalPages:false,
		useAjaxForPaging:false,
		showNumberOfResults:true,
		pageDivClass:'product'
	};

})(jQuery);



