/*!
 * Pagination and sorting using CF and Jquery
 * 
 * Builds a table and paging links that display query data returned from CF.
 * Allows for sorting by clicking on table headers.
 * Includes highlighting of current page link and showing of up to 20 page numbers on page at any one time.
 * CF returns only the records needed for each page (ie 10 at a time) rather than the whole record set.
 * Has previous and next links at either end of page links. 
 *
 *
 *
 */


function buildTable(pageNumber,orderBy)
{

	$.getJSON('paginationRealData.cfc?method=pageInfo&pageNumber=' + pageNumber + '&orderBy=' + orderBy, function(data)
	{
		//GOTCHA!! THE JSON VARIABLES RETURNED FROM A CFC ALL SEEM TO BE IN UPPER CASE. 
		//AS JS IS CASE SENSITIVE REMEMBER TO REF THEM IN UPPERCASE IN THE JS CODE OR CODE WILL FAIL; 
		//alert(data.FROM);
		var from = data.FROM;
		var numberOfRecordsOnPage = data.NUMBEROFRECORDSONPAGE;
		var numberOfPages = data.NUMBEROFPAGES;
		var to = data.TO;
		var nextPageNumber = pageNumber + 1;
		var prevPageNumber = pageNumber - 1;
		
		//Display query set info
		var html = '<div>';
		html += '<b>From:</b>' + from + '<br>'; 
		html += '<b>To:</b>' + to + '<br>';
		html += '<b>Number of Records on Page:</b>' + numberOfRecordsOnPage + '<br>';
		html += '<b>Number of Pages:</b>' + numberOfPages + '<br></div>';
		//start string for building record output
		var html2 = '<table id="t1" width="800px" class="pagination" border="1"><thead><tr><th id="name" width="300px">Order by Name</th><th id="region" width="300px">Order by Region</th><th id="area" width="200px">Order by Area (KM sq)</th><th id="population" width="200px">Order by Population</th></tr></thead><tbody>';
		//A CF QUERY PASSES BACK AN OBJ WITH 2 PROPERTIES. COLUMNS AND DATA. COLUMNS IS AN ARRAY. DATA IS AN ARRAY OF ARRAYS.
		//so each array in DATA represents a row in database 
		 $.each(data.RECORDSTOGOBACK.DATA, function(intIndex, objValue) 
		  {
			html2 += '<tr><td><B>Field 1:</B> ' + objValue[0] + '</td><td ><B>Field 2</B> ' + objValue[1] + '</td><td><B>Field 3</B> ' + objValue[2] +  '</td><td><B>Field 4</B> ' + objValue[3] +  '</td></tr>';
		  }
	);
		html2 += '</tbody></table>';
        
		//empty div of data before appending new html or else it adds more tables 
		$('#displayDiv').empty().append(html);
		$('#queryData').empty().append(html2); 
		
		//add click handlers to handle sorting by. T
		//they cause query to be returned in the order selected by the user.
		$('#name').click(function (){buildTable(pageNumber,this.id);});//this.id refers to the id of the dom element the event originates from
		$('#region').click(function (){buildTable(pageNumber,this.id);});
		$('#area').click(function (){buildTable(pageNumber,this.id);});
		$('#population').click(function (){buildTable(pageNumber,this.id);});
		
		
		
		//start build paging links
		var currentPage = 0;
	    //this is where all created page links are added
		var $pager = $('<div class="pager" align="center"></div>');
		for (var page = 1; page < numberOfPages + 1; page++) {
		    	
		 //expression ensures no more than 20 page links are shown at one time   
		 if((pageNumber > (page - 10)) && (pageNumber < (page + 10)))
		 {
		    //for each page link build a span tag and bind a click handler to each one that will call build table each time it is clicked
		      $('<span class="page-number"></span>').html('<span id="' + page + '">' + page + ' </span>').bind('click', {newPage: page}, function(event) {
		          currentPage = event.data['newPage'];
		          buildTable(currentPage,orderBy);//builds table each time a page link is clicked
		        }).appendTo($pager);// append each span tag/link to pager div
		     
		   }
		 }
		    
		    
		  //highlight current pageNumber  
		  $pager.find('#' + pageNumber).addClass('selectedLink');
		   
		  //the links that will take user one place forward and on place back
		  var $previousLink = $('<a href="" id="prev">   Previous   </a>');
		  var $nextLink = $('<a href="" id="next">   Next   </a>');
		  //previous and next links with handler that prevents the default event of hyperlink, and calls buildTable() on each click;
		  $nextLink.appendTo($pager).click(function(event){event.preventDefault();buildTable(nextPageNumber,orderBy);});
          $previousLink.prependTo($pager).click(function(event){event.preventDefault();buildTable(prevPageNumber,orderBy);});
          
           //refers to table with id of t1 just built
   		   var $table = $('#t1');
           //place paging links before and after table
		   $pager.clone(true).insertBefore($table);
           $pager.insertAfter($table);
         
		  
	 });

	
};	


$(document).ready(function()
{
//builds table on page load
buildTable(1,'name');
});





