function replaceAll(str, de, para){
    var pos = str.indexOf(de);
    while (pos > -1){
		str = str.replace(de, para);
		pos = str.indexOf(de);
	}
    return (str);
}

$().ready(function(){
	
	prototipo = $('<div class="fonte-contador-textarea">Caracteres digitados: <span class="contador"></span>. Máximo: <span class="maximo"></span></div>');
	
    $('.pergunta').live("keyup", function (event){
    	var numChar = $(this).val().length;
    	var texto = $(this).val();
    	
    	var numParag = 0;
    	var index = texto.search("([\n])");
    	while(index!=-1){
    		numParag++;
    		texto = texto.substring(index+1, texto.length);
    		index = texto.search("([\n])");
    	}
    	numChar = numChar + numParag;
    	var aux = $("#controle" + replaceAll($(this).attr("id"), ":", "_"));
        aux.children('.contador').text(numChar);
    });
        
    $('.pergunta').each(function() {
    	var maxText = $(this).attr('title');
    	var tokens = maxText.split(' ');
    	var i;
    	for (i = 0; i < tokens.length; i++){
    		if (!isNaN(tokens[i])) break;
    	}
    	
    	var maximo = tokens[i];
    	var numChar = $(this).val().length;
    	
    	var aux = prototipo.clone();
    	aux.attr("id", 'controle' + replaceAll($(this).attr("id"), ":", "_"));
    	aux.children('.contador').text(numChar);
    	aux.children('.maximo').text(maximo);
    	$(this).after(aux);
	});
	
	
});

