// $Id: recomendacao.js 4 2010-03-31 13:04:31Z caio $

// processa a requisição do formulário de recomendação de artigo
jQuery(function($) {

    var anotherRequestInProgress = false;

    $('form.recomendar_artigo').submit(function() {

        if (anotherRequestInProgress) return false;

        $form = $(this);

        // limpa erros anteriores
        $form.find('.erro').hide();
        $form.find('.sucesso').hide();

        $form.find('p.success').hide();

        $.ajax({
            type: 'POST',
            url: $form.attr('action'),
            data: $form.serialize(),
            beforeSend: function() {
                anotherRequestInProgress = true;
                $form.find('.sending').show();
                $form.find('input[type=text], textarea').removeClass('erro_validacao');
            },
            success: function() {
                anotherRequestInProgress = false;
                $form.find('.sending, p[class=erro], p[class=sucesso]').hide();
                $form.find('.sucesso').show();
                $form.find('input[name=nome], input[name=email], input[name=nome_amigo], input[name=email_amigo], textarea[name=mensagem]').val('');
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                anotherRequestInProgress = false;
                $form.find('.sending, p[class=erro], p[class=sucesso]').hide();
                $form.find('.erro').show();
                if (XMLHttpRequest.status == 403) {
                    var jsonErrors = eval('('+XMLHttpRequest.responseText+')');
                    for (field in jsonErrors) {
                        $form.find('[name='+field+']').addClass('erro_validacao');
                    }
                }
                else {
                    alert('Um erro inesperado ocorreu no servidor. Seu contato não foi submetido.');
                }
            }
        });
        return false;
    });
});

