/**
 * This jQuery muestra la cantidad de elementos deseados de los seleccionados
 *
 * @author Pedro Enrique  http://ktinformatica.com
 * @version 1.0

 * @param {Object} opts Several options (see README for documentation)
 * @return {Object} jQuery Object
 */
jQuery.fn.pagination = function(opts){
	opts = jQuery.extend({
		items_per_page:3,
		current_page:0,
		id_next:"next",
		id_prev:"prev",
		items_class:"element",
		item_active:"activo",
		move_page:true,
		callback:function(){return false;}
	},opts||{});
	
	return this.each(function() {
		
		function numPages() {
			if(opts.move_page){			
				return Math.ceil(panel.find("." + opts.items_class).length/opts.items_per_page);
			}else{

				return Math.ceil(panel.find("." + opts.items_class).length -opts.items_per_page)+1;
			}
		}
		
		//seleccionar pagina concreta
		function pageSelected(page_id, evt){

			current_page = page_id;
			drawLinks();
			var continuePropagation = opts.callback(page_id, panel);
			if (!continuePropagation) {
				if (evt.stopPropagation) {
					evt.stopPropagation();
				}
				else {
					evt.cancelBubble = true;
				}
			}
			return continuePropagation;
		}
		
		//redibujar listado
		function drawLinks() {
				var i = 0			
			if(opts.move_page || primera){
				primera = false;
				panel.find("." + opts.items_class).hide();
	

				panel.find("." + opts.items_class).each(function(){
						if(((current_page* opts.items_per_page)<=i ) && (((current_page + 1 ) * opts.items_per_page ) > i ) ){
							$(this).show();
				}
						i = i+1;				   
				});
			}else{

				panel.find("." + opts.items_class).each(function(){

						if(i>=current_page && i< opts.items_per_page + current_page){
							$(this).show(800);
						}else{
							$(this).hide(800)	
						}
i = i+1;			
																		 
				});
				
			}
			
			

		}
		
		
		
		// Saca pagina actual de las opciones

		var panel = jQuery(this);
		var primera = true;

		var current_page = opts.current_page;
		if(panel.find("." + opts.items_class + "." +opts.item_active).length >0){
			var i = 1;
			panel.find("." + opts.items_class).each(function(){
				if($(this).hasClass(opts.item_active)){
					current_page=Math.ceil(i/opts.items_per_page)-1;
				}
				i = i+1;
			});
	
		}
		
		$('#' + opts.id_prev).click(function(evt){ 

			if (current_page > 0) {
				pageSelected(current_page - 1, evt);
				return true;
			}
			else {
				return false;
			}
		});

			$('#' + opts.id_next).click( function(evt){ 
			if(current_page < numPages()-1) {
				pageSelected(current_page+1, evt);
				return true;
			}
			else {
				return false;
			}
		});
		
					panel.find("." + opts.items_class).hide();

drawLinks();
       
        opts.callback(current_page, this);
		

	});
}



