/**
 * TikiCMS
 * Copyright (C) 2009, Tiki Web Inteligente Ltda.
 * @requires jQuery 1.3.2 or latter
 *
 * $Id: application_controller_seguros.js 154 2010-04-26 19:02:38Z caio $
 */

Application.Controller.Seguros = (function() {

    // gambiarra enquanto não consigo mandar o objeto jQuery como argumento desta função
    var $ = jQuery;

    function index() {

        var anotherRequestInProgress = false;

        $('input[name$=_em]').mask('99/99/9999');
        $('input[name=cpf]').mask('999.999.999-99');
        $('input[name=cep]').mask('99.999-999');

        $('form#formReserva').submit(function() {

            if (anotherRequestInProgress) return false;

            $form = $(this);

            // limpa erros anteriores
            $form.find('.error')
                .removeClass('error')
                .find('.error_message')
                    .remove();

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

            $.ajax({
                type: 'POST',
                url: $(this).attr('action'),
                data: $(this).serialize(),
                beforeSend: function() {
                    anotherRequestInProgress = true;
                    $form.find('.loader').show();
                },
                success: function() {
                    anotherRequestInProgress = false;
                    $form.find('.loader').hide();
                    $form.prevAll('p[class=erro], p[class=ok]').remove();
                    $form.before('<p class="ok">Dados submetidos com sucesso.</p>');
                    $form.clearForm();
                    $form.find('[name=empresa]:first').attr('checked', true);
                    $form.find('[name=sexo]:first').attr('checked', true);
                    $form.find('[name=id_estado] option:first').attr('selected', true);
                    $form.find('[name=agencia_material]:first').attr('checked', true);
                    $.scrollTo('p.ok');
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    anotherRequestInProgress = false;
                    $form.find('.loader').hide();
                    var errorsStr = '';
                    if (XMLHttpRequest.status == 403) {
                        var jsonErrors = eval('('+XMLHttpRequest.responseText+')');
                        var errors = [];
                        for (field in jsonErrors) {
                            errors.push(jsonErrors[field]);
                        }
                        errorsStr = errors.join('<br />');
                    }
                    else {
                        alert('Um erro inesperado ocorreu no servidor. Seu dados não foram submetidos.');
                    }
                    $form.prevAll('p[class=erro], p[class=ok]').remove()
                    $form.before('<p class="erro">'+errorsStr+'</p>');
                    $.scrollTo('p.erro');
                }
            });
            return false;
        });
    }

    return {
        'index': index
    };
})();

