//-------------------------------------------------
//		Quick Pager jquery plugin
//		Created by dan and emanuel @geckonm.com
//		www.geckonewmedia.com
// 
//		v1.1 + proposal
//		18/09/09 * bug fix by John V - http://blog.geekyjohn.com/
//      16/10/09 * proposal to uncouple page changing and selector by fairsayan@gmail.com
//-------------------------------------------------

(function($) {
    $.fn.selectPage = function(page) {
		return this.each(function() {
			if(($('.'+this.pagerOptions.paginationClassName).find('.disabled a').attr('rel')) == page){
				return; // user clicked 'next' or 'prev' and they are currently disabled
			}
			if(($('.'+this.pagerOptions.paginationClassName).find('.currentPage a').attr('rel')) == page){
				return; //user clicked the current page link
			}
			
			$('.'+this.pagerOptions.paginationClassName).find(".prev").removeClass('disabled');
			$('.'+this.pagerOptions.paginationClassName).find(".next").removeClass('disabled');
			
			if(page == 'prev'){
				page = this.pagerOptions.currentPage-1;
			}else if(page == 'next'){
				page = this.pagerOptions.currentPage+1;
			}else{
				page = parseInt(page);
			}
			// change current page in options
			this.pagerOptions.currentPage = page;
			// make 'selecter' $(this)
   			var selector = $(this);

			var pager = '';
			if(this.pagerOptions.pageCounter > this.pagerOptions.paginationShowLimit){
				pager += $(selector)._buildPagination(this.pagerOptions,this.pagerOptions.pageCounter);
			}else{

				for (i=1;i<=this.pagerOptions.pageCounter;i++){
					if (i==this.pagerOptions.currentPage) {
						pager += "<li class='currentPage simplePageNav"+i+"'><a rel='"+i+"' href='Javascript:;'>"+i+"</a></li>";	
					}
					else {
						pager += '<li class="simplePageNav'+i+'"><a rel="'+i+'" href="Javascript:;">'+i+'</a></li>';
					}
				}
			}
			pager='<li class="prev"><a class="prev_span" href="Javascript:;" rel="prev">'+this.pagerOptions.previousText+'</a></li>'+pager+'<li class="next"><a class="next_span" href="Javascript:;" rel="next">'+this.pagerOptions.nextText+'</a></li>';
			
			
			$('.'+this.pagerOptions.paginationClassName).html(pager);
			
			$(this)._setClick($(this),this.pagerOptions);

			if(page == this.pagerOptions.pageCounter){//if going to the last page
				$('.'+this.pagerOptions.paginationClassName).find(".next").addClass('disabled');
			}else if (page == 1){ // if going to the first page
				$('.'+this.pagerOptions.paginationClassName).find(".prev").addClass('disabled');
			}
			
			//grab the REL attribute
   			
			if(this.pagerOptions.holder) {
				$('.'+this.pagerOptions.paginationClassName).find("li.currentPage").removeClass("currentPage");
				$('.'+this.pagerOptions.paginationClassName).find("a[rel='"+page+"']").parent("li").addClass("currentPage");
			} else {
				//remove current current (!) page
				$('.'+this.pagerOptions.paginationClassName).find("li.currentPage").removeClass("currentPage");
				//Add current page highlighting
				$('.'+this.pagerOptions.paginationClassName).find("a[rel='"+page+"']").parent("li").addClass("currentPage");
			}

			// show/hide the appropriate regions 
			selector.children().hide();
			selector.children().removeClass('pageVisible');
			selector.children().removeClass('pageVisible_first');
			selector.children().removeClass('pageVisible_first_row');
			selector.children().removeClass('pageVisible_last_row');
			selector.children(".simplePagerPage"+page).show();
			selector.children(".simplePagerPage"+page).addClass('pageVisible');
			selector.children(".pageVisible:eq(0)").addClass('pageVisible_first');
			selector.children(".pageVisible:eq(0)").addClass('pageVisible_first_row');
			selector.children(".pageVisible:eq(1)").addClass('pageVisible_first_row');
			selector.children(".pageVisible:eq(2)").addClass('pageVisible_first_row');
			
			var totalShowing = $(".simplePagerPage"+page).length;
			var firstShowing = $(".simplePagerPage"+page+":first").index();
			var lastShowing = $(".simplePagerPage"+page+":last").index();
			
			//Build 1 of X 
			var pagesDisplayedHtml = $(selector)._templateReplace(this.pagerOptions.pageCounterTemplate,{END:lastShowing+1, START:firstShowing+1, TOTAL:this.pagerOptions.totalItems});
			$(this).parent().find('.'+this.pagerOptions.pageCounterClass).html(pagesDisplayedHtml);
			
			
			// add pageVisible_last_row to last row of items
			var lastShowing = totalShowing-1;
			if(totalShowing>this.pagerOptions.itemsPerRow){
				while(totalShowing>this.pagerOptions.itemsPerRow){
					totalShowing = totalShowing-this.pagerOptions.itemsPerRow;
					if(totalShowing<=this.pagerOptions.itemsPerRow){
						var itemIndex = lastShowing;
						while(totalShowing>0){
							selector.children(".pageVisible:eq("+itemIndex+")").addClass('pageVisible_last_row');
							totalShowing = totalShowing-1;
							var itemIndex = lastShowing-totalShowing;
						}
					}
				}
			}else{
				selector.children(".pageVisible").addClass('pageVisible_last_row');
			}
        });
    }

	$.fn._templateReplace = function(template,replacements){
		if(template){
			for(var r in replacements){
				var reg= new RegExp('\\[\\$\\$'+r+'\\]','g');
				template=template.replace(reg,replacements[r])
			}		
		}
		return template;

	}

	$.fn._setClick = function(selector,options){
		
		//pager navigation behaviour
		selector.parent().find("."+options.paginationClassName+" a").click(function (){
			var this_val = $(this).attr("rel");
			if(this_val.match(/^\d+$/)){ // ^= begining of string $=end of string REGEX checks that everything in string is digit
				this_val = parseInt(this_val);
			}
            $(selector).selectPage(this_val);
        });
	}

	$.fn._buildPagination = function(options,pageCounter){
			var pager = '';
			// lowtest is the next page minus the limit allowed to show
			var lowtest = options.currentPage +1 - options.paginationShowLimit;
			// hightest is the previos page plus the limit allowed to show
			var hightest = options.currentPage -1 + options.paginationShowLimit;
			if(lowtest < 0){
				var numGoal = options.currentPage-lowtest;
				for (i=1;i<=numGoal;i++){
					if (i==options.currentPage) {
						pager += "<li class='currentPage simplePageNav"+i+"'><a rel='"+i+"' href='Javascript:;'>"+i+"</a></li>";	
					}
					else {
						pager += '<li class="simplePageNav'+i+'"><a rel="'+i+'" href="Javascript:;">'+i+'</a></li>';
					}
				}
				pager += '<li class="simplePageNav-dots">...</li><li class="simplePageNav'+pageCounter+'"><a rel="'+pageCounter+'" href="Javascript:;">'+pageCounter+'</a></li>';
			}else if(hightest > pageCounter){
				var numGoal = pageCounter-options.paginationShowLimit+2;
				pager += '<li class="simplePageNav1"><a rel="1" href="Javascript:;">1</a></li><li class="simplePageNav-dots">...</li>';
				
				for (i=numGoal;i<=pageCounter;i++){
					if (i==options.currentPage) {
						pager += "<li class='currentPage simplePageNav"+i+"'><a rel='"+i+"' href='Javascript:;'>"+i+"</a></li>";	
					}
					else {
						pager += '<li class="simplePageNav'+i+'"><a rel="'+i+'" href="Javascript:;">'+i+'</a></li>';
					}
				}
			}else{
				var numStart = options.currentPage - Math.floor(options.paginationShowLimit/2)+1;
				var numEnd = numStart + options.paginationShowLimit-3;
				pager += '<li class="simplePageNav1"><a rel="1" href="Javascript:;">1</a></li><li class="simplePageNav-dots">...</li>';
				for (i=numStart;i<=numEnd;i++){
					if (i==options.currentPage) {
						pager += "<li class='currentPage simplePageNav"+i+"'><a rel='"+i+"' href='Javascript:;'>"+i+"</a></li>";	
					}
					else {
						pager += '<li class="simplePageNav'+i+'"><a rel="'+i+'" href="Javascript:;">'+i+'</a></li>';
					}
				}
				pager += '<li class="simplePageNav-dots">...</li><li class="simplePageNav'+pageCounter+'"><a rel="'+pageCounter+'" href="Javascript:;">'+pageCounter+'</a></li>';
			
			}
			return pager;
			//if lowtest fails, go up to total-to-show minus one, add dots, show last
			//if hightest fails, show first, calculate first to show, add dots, show first-to-show until last
			//otherwise, show first, calc 1st to show, dots, show 1st-to-show until total-to-show minus 2, dots, show last
			//for (i=1;i<=pageCounter;i++){
				//var pg = i + 1;
				// if on the 1st page or the last page or we're greater than the lowtest AND less than the hightest
				//if (((pg == 1) || (pg == pageCounter) || ((pg > lowtest) && (pg < hightest)))) {
			
	}
    $.fn.quickPager = function(options) {
	
		var defaults = {
			pageSize: 10,
			currentPage: 1,
			holder: null,
			pagerLocation: "after",
			previousText: "prev",
			nextText: "next",
			itemsPerRow: 3,
			pagedContainerName: 'simplePagerContainer',
			paginationContainerName: 'simplePagerPagination',
			paginationClassName: 'simplePagerNav',
			pageCounterClass: 'simplePagerCounter', //displays either page 1 of X or showing 1-10 of 24
			pageCounterType: 'ITEMS', //can be either PAGE or ITEMS (corresponds to above)
			pageCounterTemplate: 'Displaying [$$START]-[$$END] of [$$TOTAL]',  //replacement variables are START, END, TOTAL
			paginationShowLimit: 6
		};
		
		var options = $.extend(defaults, options);
		
		
		return this.each(function() {
            this.pagerOptions = options;
						
			var selector = $(this);	
			var pageCounter = 1;
			
			selector.wrap('<div class="'+options.pagedContainerName+'"></div>');
			this.pagerOptions.totalItems = selector.children().length;
			//  
			selector.children().each(function(i){ 
					
				if(i < pageCounter*options.pageSize && i >= (pageCounter-1)*options.pageSize) {
					$(this).addClass("simplePagerPage"+pageCounter);
				}else {
					$(this).addClass("simplePagerPage"+(pageCounter+1));
					pageCounter ++;
				}	
			});
			this.pagerOptions.pageCounter = pageCounter;
			
			// show/hide the appropriate regions 
			selector.children().hide();
			selector.children().removeClass('pageVisible');
			selector.children().removeClass('pageVisible_first');
			selector.children().removeClass('pageVisible_first_row');
			selector.children(".simplePagerPage"+options.currentPage).show();
			selector.children(".simplePagerPage"+options.currentPage).addClass('pageVisible');
			selector.children(".pageVisible:eq(0)").addClass('pageVisible_first');
			selector.children(".pageVisible:eq(0)").addClass('pageVisible_first_row');
			selector.children(".pageVisible:eq(1)").addClass('pageVisible_first_row');
			selector.children(".pageVisible:eq(2)").addClass('pageVisible_first_row');
			
			var pageNav ='';
			var firstPageSize = this.pagerOptions.pageSize;
			if(pageCounter <= 1) {
				firstPageSize = selector.children(".pageVisible").length;
			}
			//Build 1 of X 
			var startNum = (this.pagerOptions.totalItems == 0)? 0:1;
			var pagesDisplayedHtml = $(selector)._templateReplace(this.pagerOptions.pageCounterTemplate,{END:firstPageSize, START:startNum, TOTAL:this.pagerOptions.totalItems});
			pageNav += '<p class="'+options.pageCounterClass+'">'+pagesDisplayedHtml+'</p>';
			
			
			
			// add pageVisible_last_row to last row of items
			var totalShowing = $(".simplePagerPage"+options.currentPage).length;
			var firstShowing = $(".simplePagerPage"+options.currentPage+":first").index();
			var lastShowing = $(".simplePagerPage"+options.currentPage+":last").index();
			
			if(totalShowing>options.itemsPerRow){
				while(totalShowing>options.itemsPerRow){
					totalShowing = totalShowing-options.itemsPerRow;
					if(totalShowing<=options.itemsPerRow){
						var itemIndex = lastShowing;
						while(totalShowing>0){
							selector.children(".pageVisible:eq("+itemIndex+")").addClass('pageVisible_last_row');
							totalShowing = totalShowing-1;
							var itemIndex = lastShowing-totalShowing;
						}
					}
				}
			}else{
				selector.children(".pageVisible").addClass('pageVisible_last_row');
			}
			
			if(pageCounter > 1) {
			//Build pager navigation
			var pager='';
			var i;
			var paginationShowLimit = 1;
			//NATH: THIS IS WHERE YOU ARE
			// 1...15 16 17 18 ... 2
			if(pageCounter > options.paginationShowLimit){
				pager += selector._buildPagination(options,pageCounter);
			}else{

				for (i=1;i<=pageCounter;i++){
					if (i==options.currentPage) {
						pager += "<li class='currentPage simplePageNav"+i+"'><a rel='"+i+"' href='Javascript:;'>"+i+"</a></li>";	
					}
					else {
						pager += '<li class="simplePageNav'+i+'"><a rel="'+i+'" href="Javascript:;">'+i+'</a></li>';
					}
				}
			}
			pager='<li class="prev disabled"><a class="prev_span" href="Javascript:;" rel="prev">'+options.previousText+'</a></li>'+pager+'<li class="next"><a class="next_span" href="Javascript:;" rel="next">'+options.nextText+'</a></li>';
				
			pageNav += '<ul class="'+options.paginationClassName+'">'+pager+'</ul>';
			
				//return;
			}
			
			if(!options.holder) {
				switch(options.pagerLocation)
				{
				case "before":
					pageNav = '<div class="'+options.paginationContainerName+' '+options.paginationContainerName+'-before">'+pageNav+'</div>';
					selector.before(pageNav);
				break;
				case "both":
					pageNav = '<div class="'+options.paginationContainerName+' '+options.paginationContainerName+'-before">'+pageNav+'</div>';
					selector.before(pageNav);
					pageNav = '<div class="'+options.paginationContainerName+' '+options.paginationContainerName+'-after">'+pageNav+'</div>';
					selector.after(pageNav);
				break;
				default:
					pageNav = '<div class="'+options.paginationContainerName+' '+options.paginationContainerName+'-after">'+pageNav+'</div>';
					selector.after(pageNav);
				}
			}
			else {
				$(options.holder).append(pageNav);
			}
			
			selector._setClick(selector,options);
			
		});
	}
	

})(jQuery);


