// Limpa espaços em branco no começo e no fim de inputs e textareas
jQuery.fn.trimFields = function(){
	this.each(function(){
		$(this).val( jQuery.trim($(this).val()) );
	});
}

// Verifica se o e-mail informado é válido
function isEmail(pStr){
	var reEmail = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	return reEmail.test(pStr);
}

jQuery.fn.counter = function(qtde) {
  $(this).each(function() {
	var max = qtde;
	var val = $(this).attr('value');
	var cur = 0;
	if(val) //value="", or no value at all will cause an error
	cur = val.length;

	var left = max-cur;
	$(this).after("<div class='counter'>" + left.toString() + " caracteres restantes" + "</div>");
		
		$(this).keyup(function(i) {
		  var max = qtde;
		  var val = $(this).attr('value');
		  var cur = 0;
		  if(val)
		  cur = val.length;
		  var left = max-cur;
			if(left <= 3){
				$('.counter').css('color', '#ff0000');
			} else {
				$('.counter').css('color', '#666666');
			}
			if(left<1){
				$(this).val( ($(this).val()).substring(0,qtde) );	
			}
			if(left>=0){
				$(this).next(".counter").text(left.toString() + " caracteres restantes");
			}
		  return this;
		});
	
  });
  return this;
}
