
  $(document).ready( function () {
  	if($("#mainText").find("p.break").length > 0) {
	    var pageLinks = '';
	    $('<p class="break offscreen">page break</p>').prependTo("#mainText");
	    $("#mainText").find("p.break").each( function (i) {
	      var nodes = $(this).nextUntil("p.break");
	      $(nodes).wrapAll('<div id="page'+(i+1)+'" class="page"/>');
	      pageLinks += '<li id="'+(i+1)+'"  class="pageLink">'+(i+1)+'</li>';
	    });
	    var pagination = '<div class="paginationWrapper"><div class="pagination"><ul><li class="prev">&lt; Prev</li>' + pageLinks+ '<li class="next">Next &gt;</li></ul></div></div>'
	    $(pagination).insertAfter("#mainText");
	    $("div.page").hide();
	    var clickFunction = function(obj, type) {
	      var pagebreaks = $("#mainText").find("p.break").length;
	      var currentPage = $(".current").attr('id');
	      $("div.page").hide();
	      $(".pageLink").removeClass("current");
	      $(".pageLink").addClass("pointer");
	      if(type != 'next' &&  type != 'prev') {
	        $("#page" + $(obj).attr('id')).show();
	        $(obj).addClass("current");
	        currentPage = $(obj).attr('id');
	      }
	      else if(type == "prev") {
	          currentPage = Math.round(currentPage) -1;
	          $("#page" + currentPage).show();
	          $("#"+currentPage).addClass("current");
	      }
	      else if(type == "next") {
	          currentPage = Math.round(currentPage) + 1;
	          $("#page" + currentPage).show();
	          $("#"+currentPage).addClass("current");
	      }
	      $("#"+currentPage).removeClass("pointer");
		  if(currentPage > 1) {
		    $(".prev").unbind("click");
	    	$(".prev").bind("click", function(e) {
		        clickFunction($(this),'prev');
			});
			$(".prev").unbind("mouseover");	        
			$(".prev").unbind("mouseout");
		    $(".prev").bind("mouseover mouseout", function(e) {
				$(this).toggleClass('pointer');
	      	});
	        $(".prev").addClass("nextprevon");
	      }
	      else {
	        $(".prev").removeClass("nextprevon");
	        $(".prev").unbind("click");
			$(".prev").unbind("mouseover");	        
			$(".prev").unbind("mouseout");
	      }
          
	      if(currentPage < pagebreaks) {
	        $(".next").unbind("click");
			$(".next").bind("click", function(e) {
	        	clickFunction($(this),'next');
	        });
			$(".next").unbind("mouseover");	        
			$(".next").unbind("mouseout");
		    $(".next").bind("mouseover mouseout", function(e) {
				$(this).toggleClass('pointer');
	      	});
	        $(".next").addClass("nextprevon");
	      }
	      else {
	        $(".next").removeClass("nextprevon");
	        $(".next").unbind("click");
			$(".next").unbind("mouseover");	        
			$(".next").unbind("mouseout");
	      }
	    }
	    $(".pageLink").each( function(i) {
	      $(this).bind("click", function(e) {
	        clickFunction($(this), "link");
	      });
	    });
	    $("#1").click();
	}
  });

