/**
 * tablePagination - A table plugin for jQuery that creates pagination elements
 *
 * http://neoalchemy.org/tablePagination.html
 *
 * Copyright (c) 2009 Ryan Zielke (neoalchemy.com)
 * licensed under the MIT licenses:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @name tablePagination
 * @type jQuery
 * @param Object settings;
 *      firstArrow - Image - Pass in an image to replace default image. Default: (new Image()).src="./images/first.gif"
 *      prevArrow - Image - Pass in an image to replace default image. Default: (new Image()).src="./images/prev.gif"
 *      lastArrow - Image - Pass in an image to replace default image. Default: (new Image()).src="./images/last.gif"
 *      nextArrow - Image - Pass in an image to replace default image. Default: (new Image()).src="./images/next.gif"
 *      rowsPerPage - Number - used to determine the starting rows per page. Default: 5
 *      currPage - Number - This is to determine what the starting current page is. Default: 1
 *      optionsForRows - Array - This is to set the values on the rows per page. Default: [5,10,25,50,100]
 *      ignoreRows - Array - This is to specify which 'tr' rows to ignore. It is recommended that you have those rows be invisible as they will mess with page counts. Default: []
 *
 * @author Ryan Zielke (neoalchemy.org)
 * @requires jQuery v1.2.3 or above
 */

 (function($){

	$.fn.tablePagination = function(settings) {
		var defaults = {  
			firstArrow : (new Image()).src="/PORTAIL_FAMILLES_WEB/controle_debut_16.png",  
			prevArrow : (new Image()).src="/PORTAIL_FAMILLES_WEB/controle_precedent_16.png",
			lastArrow : (new Image()).src="/PORTAIL_FAMILLES_WEB/controle_fin_16.png",
			nextArrow : (new Image()).src="/PORTAIL_FAMILLES_WEB/controle_suivant_16.png",
			rowsPerPage : 5,
			currPage : 1,
			optionsForRows : [2,5,10,15,20],
			ignoreRows : []
		};  
		settings = $.extend(defaults, settings);
		
		return this.each(function() {
      var table = $(this)[0];
      var totalPagesId, currPageId, rowsPerPageId, firstPageId, prevPageId, nextPageId, lastPageId
      if (!table.id) {
		table.id = Math.floor(Math.random() * 9999 )+1; // s'il n'y a pas d'id sur la table, on lui en attribu un aléatoire
	  }
        
		//totalPagesId 	= '#'+table.id+' + .tablePagination .tablePagination_totalPages';
		
		//totalEnregId 		= '#'+table.id+' + .tablePagination .tablePagination_totalEnreg';		
		//currPageId 		= '#'+table.id+' + .tablePagination .tablePagination_currPage';
		//rowsPerPageId 	= '#'+table.id+' + .tablePagination .tablePagination_rowsPerPage';        
		//controlerId 		= '#'+table.id+' + .tablePagination .tablePagination_controler';
		//spanPagesId 		= '#'+table.id+' + .tablePagination .tablePagination_Pages';
		//firstPageId 		= '#'+table.id+' + .tablePagination .tablePagination_firstPage';
        //prevPageId 		= '#'+table.id+' + .tablePagination .tablePagination_prevPage';
		//numPageId 		= '#'+table.id+' + .tablePagination .tablePagination_numPage'
        //nextPageId 		= '#'+table.id+' + .tablePagination .tablePagination_nextPage';
        //lastPageId 		= '#'+table.id+' + .tablePagination .tablePagination_lastPage';

        totalEnregId 	= '#tablePagination_totalEnreg_'+table.id;
        currPageId 		= '#tablePagination_currPage_'+table.id;
		rowsPerPageId 	= '#tablePagination_rowsPerPage_'+table.id;
	    controlerId 	= '#tablePagination_controler_'+table.id;		
		spanPagesId 	= '#tablePagination_Pages_'+table.id;
		firstPageId 	= '#tablePagination_firstPage_'+table.id;
        prevPageId 		= '#tablePagination_prevPage_'+table.id;
		numPageId 		= '[name="tablePagination_numPage_'+table.id+'"]';
        nextPageId 		= '#tablePagination_nextPage_'+table.id;
        lastPageId 		= '#tablePagination_lastPage_'+table.id;
		
      // }else{
		// table.id 		= '';
        // // totalPagesId 	= '.tablePagination .tablePagination_totalPages';
		// totalEnregId 	= '.tablePagination .tablePagination_totalEnreg';
        // currPageId 		= '.tablePagination .tablePagination_currPage';
        // rowsPerPageId 	= '.tablePagination .tablePagination_rowsPerPage';
        // controlerId 	= '.tablePagination .tablePagination_controler';		
		// spanPagesId 	= '.tablePagination .tablePagination_Pages';
        // firstPageId 	= '.tablePagination .tablePagination_firstPage';
        // prevPageId 		= '.tablePagination .tablePagination_prevPage';
		// numPageId 		= '.tablePagination .tablePagination_numPage'
        // nextPageId 		= '.tablePagination .tablePagination_nextPage';
        // lastPageId 		= '.tablePagination .tablePagination_lastPage';
      // }
      
      var possibleTableRows = $.makeArray($('tbody tr', table));
      var tableRows = $.grep(possibleTableRows, function(value, index) {
        return ($.inArray(value, defaults.ignoreRows) == -1);
      }, false)
      
      var numRows = tableRows.length;
	  
      var totalPages = resetTotalPages();
      var currPageNumber = (defaults.currPage > totalPages) ? 1 : defaults.currPage;
      if ($.inArray(defaults.rowsPerPage, defaults.optionsForRows) == -1)
        defaults.optionsForRows.push(defaults.rowsPerPage);
      
      
      function hideOtherPages(pageNum) {
        if (pageNum==0 || pageNum > totalPages)
          return;
        var startIndex = (pageNum - 1) * defaults.rowsPerPage;
        var endIndex = (startIndex + defaults.rowsPerPage - 1);
        $(tableRows).show();
        for (var i=0;i<tableRows.length;i++) {
          if (i < startIndex || i > endIndex) {
            $(tableRows[i]).hide()
          }
        }
		
		$(numPageId).removeClass("tablePagination_currPage");
		$(numPageId+"[numPage='"+pageNum+"']").addClass("tablePagination_currPage");
      }
      
      function resetTotalPages() {
        var preTotalPages = Math.round(numRows / defaults.rowsPerPage);
        var totalPages = (preTotalPages * defaults.rowsPerPage < numRows) ? preTotalPages + 1 : preTotalPages;
        return totalPages;
      }
      
	  function resetListPages(pNbEnr){
		var xList="";
		if (pNbEnr) defaults.rowsPerPage = pNbEnr;
        totalPages = resetTotalPages();

		//var xCurrentPage = parseInt($(currPageId).val(),10);
		
		//alert(xCurrentPage);
		
		if (totalPages>1){
			for (var i=1;i<=totalPages;i++){
			
				if (totalPages<=7){	
					xList+="<span class='tablePagination_numPage' name='tablePagination_numPage_"+table.id+"' numPage='"+i+"'><a>"+i+"</a></span>";
				}else{
					if ((  i == 1 ) || ( i == totalPages ) ) {
						xList+="<span class='tablePagination_numPage' name='tablePagination_numPage_"+table.id+"' numPage='"+i+"'><a>"+i+"</a></span>";
					
					}else if ( (i - currPageNumber) == (-3)  || (i - currPageNumber ) == (3) ) {
							xList+="<span class='tablePagination_numPage' name='tablePagination_numPage_"+table.id+"' numPage=''> ... </span>";
					}else if ( (i - currPageNumber) > (-3) && (i - currPageNumber) < (3)) {
							xList+="<span class='tablePagination_numPage' name='tablePagination_numPage_"+table.id+"' numPage='"+i+"'><a>"+i+"</a></span>";						
					}
				}
			}

			$(spanPagesId).html(xList);
			$(numPageId).bind('click', function (e) {				
				if ($(this).attr("numPage")!= "") resetCurrentPage(parseInt($(this).attr("numPage"),10))
			});
			
			$(controlerId).show().disableTextSelect();
			
		}else{
			$(controlerId).hide()
		}
        //resetCurrentPage(1)

	  }
	  
      function resetCurrentPage(currPageNum) {
        if (currPageNum < 1 || currPageNum > totalPages)
          return;
        currPageNumber = currPageNum;
		$(currPageId).val(currPageNumber)
		if (totalPages>7) resetListPages();

        hideOtherPages(currPageNumber);
		
      }
      
      function resetPerPageValues() {
        var isRowsPerPageMatched = false;
        var optsPerPage = defaults.optionsForRows;
        optsPerPage.sort(function (a,b){return a - b;});
        var perPageDropdown = $(rowsPerPageId).get(0); //[0];
		
		//alert(rowsPerPageId)
		//$(test).hide();
		
		//$(".tablePagination_rowsPerPage").css("color","green");
		//$(rowsPerPageId).css("color","red");
		
        perPageDropdown.length = 0;
        for (var i=0;i<optsPerPage.length;i++) {
          if (optsPerPage[i] == defaults.rowsPerPage) {
            perPageDropdown.options[i] = new Option(optsPerPage[i], optsPerPage[i], true, true);
            isRowsPerPageMatched = true;
          }
          else {
            perPageDropdown.options[i] = new Option(optsPerPage[i], optsPerPage[i]);
          }
        }
        if (!isRowsPerPageMatched) {
          defaults.optionsForRows == optsPerPage[0];
        }
      }
	  
      function createPaginationElements() {
        var htmlBuffer = [];
        htmlBuffer.push("<div class='tablePagination ui-state-default' id='tablePagination_"+table.id+"'>");

        htmlBuffer.push("<div class='tablePagination_perPage' id='tablePagination_perPage_"+table.id+"'>");
        htmlBuffer.push("Afficher ");
		htmlBuffer.push("<select class='tablePagination_rowsPerPage' id='tablePagination_rowsPerPage_"+table.id+"'><option value='5'>5</option></select>");	
        htmlBuffer.push("&eacute;l&eacute;ments");
        htmlBuffer.push("</div>");
		htmlBuffer.push("<div class='tablePagination_totalEnreg' id='tablePagination_totalEnreg_"+table.id+"'>");
		htmlBuffer.push("</div>");
		htmlBuffer.push("<div class='tablePagination_controler' id='tablePagination_controler_"+table.id+"'>");
        htmlBuffer.push("<a class='tablePagination_firstPage' id='tablePagination_firstPage_"+table.id+"' 'title='Premi&egrave;re page'> &nbsp;</a>");
        htmlBuffer.push("<a class='tablePagination_prevPage' id='tablePagination_prevPage_"+table.id+"' title='Page pr&eacute;c&eacute;dente'> &nbsp;</a>");
        
		htmlBuffer.push("<span class='tablePagination_Pages' id='tablePagination_Pages_"+table.id+"'>");
		htmlBuffer.push("</span>");

        htmlBuffer.push("<a class='tablePagination_nextPage' id='tablePagination_nextPage_"+table.id+"' title='Page suivante'> &nbsp;</a>");
        htmlBuffer.push("<a class='tablePagination_lastPage' id='tablePagination_lastPage_"+table.id+"' title='Dermi&egrave;re page'> &nbsp;</a>");
        htmlBuffer.push("</div>");
        
		htmlBuffer.push("</div>");

        return htmlBuffer.join("").toString();
      }
      
      //if ($(totalPagesId).length == 0) {
        $(this).after(createPaginationElements());
      //}
      //else {
      //  $('#tablePagination_currPage').val(currPageNumber);
      //}
	  
	  resetPerPageValues();
	  resetListPages();
	  resetCurrentPage(1);
      hideOtherPages(currPageNumber);
	  $(totalEnregId).html(numRows+" &eacute;l&eacute;ments");
      
      $(firstPageId).bind('click', function (e) {
        resetCurrentPage(1)
      });
      
      $(prevPageId).bind('click', function (e) {
        resetCurrentPage(currPageNumber - 1)
      });	  	  
      
      $(nextPageId).bind('click', function (e) {
        resetCurrentPage(currPageNumber + 1)
      });
      
      $(lastPageId).bind('click', function (e) {
        resetCurrentPage(totalPages)
      });
      

      
      $(rowsPerPageId).bind('change', function (e) {
		resetListPages(parseInt(this.value, 10));
		resetCurrentPage(1);
     });
      
		})
	};		
})(jQuery);
