$(document).ready(function() {
	
	$('textarea[maxlength]').keyup(function(){
        var max = parseInt($(this).attr('maxlength'));
        if($(this).val().length > max){
            $(this).val($(this).val().substr(0, $(this).attr('maxlength')));
        }
        $(this).parent().find('span.resta').html('Restam ' + (max - $(this).val().length) + ' caracteres');
    });
	
	$("form#recados").validate({
		messages:{
			nome			: 'Informe seu nome',
			email			: 'Informe seu e-mail corretamente',
			cidade			: 'Informe sua cidade',
			estado			: 'Escolha um estado',
			mensagem		: 'Informe a mensagem'
		},
		submitHandler: function() {
						
			var query = $('form#recados').formSerialize();
			$.ajax({
				url: 'mural-de-recados/enviar',
				data: query,
				type: 'POST',
				dataType: 'text',
				cache: false,
				beforeSend: function(){
					$('#bt_enviar').attr('disabled','disabled').html('Enviando...').after(' <img id="bt_carregando" src="img/carregando.gif" alt="" />');
				},
				error: function(){
					$('#bt_enviar').attr('disabled','').html('Enviar');
					$('#bt_carregando').remove();
					alert('Erro na requisição, tente novamente');
				},				
				success: function(retorno){
					var partes = retorno.split('$$');
					if ( partes[0] == '1' ){
						$('#bt_enviar').attr('disabled','').html('Enviar');
						$('#bt_carregando').remove();
						//alert("Seu pedido de oração foi enviado com sucesso!\nObrigado!");
						
						var p = partes[1].split('##');
						
						$("ul.lista_recados li:first-child").before('<li style="display:none;"><span class="data">'+p[4]+'</span><span class="nome">'+p[0]+'</span><br/><span class="cidade">'+p[1]+' - '+p[2]+'</span><p>'+p[3]+'</p></li>');
						
						$("ul.lista_recados li:first-child").fadeIn("slow");
						
						$('#bt_enviar').after('<p class="ok">Recado enviado com sucesso!</p>').hide();
						setTimeout(function(){
							$('p.ok').fadeOut('slow',function(){
								$('#bt_enviar').fadeIn();
							});
						},2000);
						
						$('form#recados').trigger('reset');
					} else {
						if ( partes[0] == '0' ){
							alert("Erro!\n"+partes[1]);
						} else {
							$('#bt_enviar').attr('disabled','').html('Enviar');
							$('#bt_carregando').remove();
							alert(retorno);
						}
					}
				}
			});
			return false;
		}
	});
			
});

