/*
 * SelecionAll
 * Simples plugin para jQuery para marcar/desmarcar checkbox em uma lista
 *
 * Examples and documentation at: http://eduardostuart.wordpress.com
 * 
 * Copyright (c) 2010 - Eduardo Stuart
 *
 * Requires: jQuery v1.3+
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(function($){
		  
	$.fn.selecionall = function(opt){
		var checks,novo_valor = '',label = '',checado = false,e=this,selecionados,total = 0;
		var options = $.extend({
			btnPrincipal: null,
			btnLabel: 'Apagar %n%',
			checkPrincipal:null,
			checksSelecionar:null,
			defaultLabel:null
		},opt);
				
		this.iniciar = function(e){
			checks = $("input[name="+options.checksSelecionar+"]");
			this.allCheck(checks);
			this.eachCheck(checks);
			this.atualizarBtn(checks);
		}
		
		this.allCheck = function(checks){
			var el = this;
			$(options.checkPrincipal).click(function(){
				var chk = $(this);
				if(chk.attr("checked") == true){
					el.selTodos(checks);
				}else{
					el.desTodos(checks);
				}
				el.atualizarBtn(checks);
			});
		}
		
		this.eachCheck = function(c){
			var el = this;
			jQuery.each(c,function(){
				$(this).click(function(){
					el.atualizarBtn(c);
				});
			});
		}

		this.atualizarBtn = function(c){
			var bt = $(options.btnPrincipal);
			label = jQuery.trim(bt.attr("value"));
			total = this.getTotalSelecionados(c).toString();
			novo_valor = options.btnLabel.replace(/\%n\%/i,total);
			if(total >= 1){
				if(total > 1){
					novo_valor = novo_valor.replace(/\%p\%/i,"s");
				}else{
					novo_valor = novo_valor.replace(/\%p\%/i,"");					
				}
				bt.removeAttr("disabled");
			}else{
				if(options.defaultLabel==null)
					novo_valor = novo_valor.replace(/\%p\%/i,"");					
				else
					novo_valor = options.defaultLabel;
				bt.attr("disabled",true);
			}
			bt.attr("value",novo_valor);
		}
		
		
		this.selTodos = function(c){
			jQuery.each(c,function(){
				$(this).attr("checked",true);
			});
		}
		
		this.desTodos = function(c){
			jQuery.each(c,function(){
				$(this).removeAttr("checked");
			});
		}
		
		this.getTotalSelecionados = function(c){
			selecionados = 0;
			jQuery.each(c,function(){
				if($(this).attr("checked") == true) selecionados+=1;
			});
			return selecionados;
		}
		return e.iniciar();
	}
})(jQuery);
