/**
 * TikiCMS
 * Copyright (C) 2009, Tiki Web Inteligente Ltda.
 * @requires jQuery 1.3.2 or latter
 *
 * $Id: application_controller_area_agente.js 338 2012-01-12 12:16:47Z willian $
 */

Application.Controller.AreaAgente = (function() {

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

    function index() {
        $('.areaAgenteIn .esqueci').click(function(){
            $('.areaAgenteIn .form_areaAgente').fadeOut(300, function(){
                $('.areaAgenteIn .form_esqueci').fadeIn(300);
            });
        })
                    
        $('form#post_senhas').submit(function() {
            var speed = 300, $form = $(this);
			$form.find('.bt').fadeOut(speed, function(){
				$form.find('.form_loading').fadeIn(speed, function() {
					$.ajax({
						type: 'post',
						url: $form.attr('action'),
						data: $form.serialize(),
						success: function() {
                            $('.form_success span').html($('#email_senha').val());
							$form.find('input[type=text], textarea').each(function() {
								$(this).val('');
							});
                            
                            $form.find('.form_esqueci_wrap').fadeOut(speed, function(){
                                $form.find('.form_loading').hide();
                                $form.find('.bt').show();
                                
								$form.find('.form_success').fadeIn(speed);
                            });
                            
                            setTimeout(function() {
								$form.find('.form_success').fadeOut(speed, function(){
                                    $('.areaAgenteIn .form_esqueci').hide();
                                    $form.find('.form_esqueci_wrap').show();
                                    
                                    $('.areaAgenteIn .form_areaAgente').fadeIn(speed);                                    
								});
							}, 8000);
                            
						}, error: function(XMLHttpRequest) {
							$form.find('.form_esqueci_wrap').fadeOut(speed, function(){
                                $form.find('.form_loading').hide();
                                $form.find('.bt').show();
                                
								$form.find('.form_error').fadeIn(speed);
							});
							setTimeout(function() {
								$form.find('.form_error').fadeOut(speed, function(){
									$form.find('.form_esqueci_wrap').fadeIn(speed);
								});
							}, 3000);
						}
					});
				});
			});
            return false;
        });
    }

    function cadastro_agencias() {

        $('select[name=uf]').change(function() {
            var uf = $(this).val();
            var $comboCidades = $('select[name=id_cidade]');
            if (uf == 0) {
                $comboCidades.html('<option value="0">Escolha a cidade...</option>');
                return;
            }
            $.getJSON(Application.build_url('sistema/?c=estados&m=cidades_por_estado'), { uf: uf }, function(data) {
                var options = '';
                var dataLength = data.length;
                for (i = 0; i < dataLength; i++) {
                    options += '<option value="'+data[i]['id']+'">'+data[i]['nome']+'</option>';
                }
                $comboCidades.html(options);
            });
        });
    }

    function cadastro_agentes() {

        var anotherRequestInProgress = false;
        
        $('input[name=cpf]').mask('999.999.999-99');

        $('input[name=nome]').val('').focus();

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

            if (anotherRequestInProgress) return false;

            $form = $(this);

            $.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">Agente cadastrado com sucesso.</p>');
                    $('input[name=nome]').val('').focus();
                    $('input[name=cpf]').val('').focus();
                    $('input[name=email]').val('');
                    $('input[name=nascido_em]').val('');
                    $('input[name=telefone]').val('');
                    $('input[name=senha]').val('');
                    $('input[name=_senha_confirmada]').val('');
                },
                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 {
                        errorsStr = 'Um erro inesperado ocorreu no servidor. Seu contato não foi submetido.';
                    }
                    $form.prevAll('p[class=erro], p[class=ok]').remove()
                    $form.before('<p class="erro">'+errorsStr+'</p>');
                }
            });
            return false;
        });
    }

    return {
        'index': index,
        'login': index,
        'cadastro_agencias': cadastro_agencias,
        'cadastrar_agencia': cadastro_agencias,
        'cadastro_agentes': cadastro_agentes
    };
})();

