/**
 * @jefferson Souza[http://www.jeffersonsouza.com.br]
 */
$(function($){
	$("#aviso, .hide, #detalhesCliente, #indique, #avisoEmail, #consultas").hide();

	
	$('#marca').change(function(){
		$('#modelo').css("backgroundColor", "#f0f0f0").html('<option value="">Carregando modelos...</option>');
		var idmarca = $(this).val();
		$.post('../ajax/pegaModelos.php',{idMarca:idmarca},		
		function(resposta){
			// resposta
			$('#modelo').fadeOut();
			$('#modelo').html(unescape(resposta));
			$('#modelo').fadeIn();
			$('#modelo').css("backgroundColor", "");
		});
	});

        $('#abreConsulta').click(function(){
            $('#consultas').show().dialog({width:300, height:400, resizable:false, draggable : false, buttons:{
                    fechar: function(){
                        $('#consultas').dialog('destroy');
                    },
                    consultar: function(){
                        
                        if($('#placa').val().length == 0){                            
                            $('#erro').html('<h4 style="color: #f00; font-size:12px; ">A placa n&atilde;o pode estar em branco</h4>');
                        }else{
                            $.post('ajax/consultaveiculo.php', {placa : $('#placa').val()}, function(retorno){
                                $('#consultas').dialog('destroy');
                                $('#consultas').html(retorno).show().dialog({width:500, height:400, resizable:false, draggable : false,
                                    buttons:{
                                        fechar: function(){
                                            $('#consultas').html('<h4>Digite a placa do ve&iacute;culo:</h4><input type="text" id="placa" />');
                                            $('#consultas').dialog('destroy');
                                        }
                                    }
                                })
                            })
                        }
                    }
                }
            })
        })
	
	$('#cadastraNovoVeiculo').click(function(){		
		var saida = '<td><label for="marca">Marca do Veículo:</label><br /><input type="text" name="marca" id="marca" />';
		saida += '<br style="margin-bottom:12px;"/><label for="modelo">Modelo:</label><br /><input type="text" name="modelo" id="modelo" /></td>';
		$('#carroPadrao').html(saida);
	});
	$('#cadastraNovoVeiculo').click(function(){		
		var saida = '<div style="float:left; margin-right:50px;"><label for="marca">Marca do Veículo:</label><br /><input type="text" name="marca" id="marca" /></div>';
		saida += '<div style="float:left; margin-right:50px;"><label for="modelo">Modelo:</label><br /><input type="text" name="modelo" id="modelo" /></div>';
		$('#marcaModelo').html(saida);
	});
	
	$('#controles-veiculos').click(function(){
		if ($('#novoVeiculo').css('display') == "block") {
			$('#novoVeiculo').css("display", "none");
		}else{
			$('#novoVeiculo').css("display", "block");
		}
	});
        $('#indicarAmigo').click(function(){
            $('#indique').dialog({
                width:400,
                height:300,
                modal: false,
                buttons: {
                    Fechar: function() {
                        $(this).dialog('destroy');
                    },
                    Enviar: function() {
                        
                        $.get('ajax/indique.php', {
                            nome_indica : $('#nome_indica').val(),
                            email_indica : $('#email_indica').val(),
                            email_indicado : $('#email_indicado').val()
                        }, function(retorno){
                            $('#avisoEmail').fadeIn('slow').html(retorno);
                        })
                    }
                }
            });
        });

            $("#nascimento").mask("99/99/9999");
            $(".data").mask("99/99/9999");
            $(".hora").mask("99:99");
            $(".telefone").mask("(99) 9999-9999");
});
function getEndereco() {  
     
        if($.trim($("#cep").val()) != ""){  
            /* 
                Para conectar no serviço e executar o json, precisamos usar a função 
                getScript do jQuery, o getScript e o dataType:"jsonp" conseguem fazer o cross-domain, os outros 
                dataTypes não possibilitam esta interação entre domínios diferentes 
                Estou chamando a url do serviço passando o parâmetro "formato=javascript" e o CEP digitado no formulário 
                http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+$("#cep").val() 
            */ 
			 
			 if ($("#cep").val().length == 8) {
						 	
			 	$.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep=" + $("#cep").val(), function(){
			 		// o getScript dá um eval no script, então é só ler!  
					//Se o resultado for igual a 1  
					if (resultadoCEP["resultado"] == 1) {
						// troca o valor dos elementos  
						$("#endereco").val(unescape(resultadoCEP["tipo_logradouro"]) + ": " + unescape(resultadoCEP["logradouro"]));
						$("#bairro").val(unescape(resultadoCEP["bairro"]));
						$("#cidade").val(unescape(resultadoCEP["cidade"]));
						$("#estado").val(unescape(resultadoCEP["uf"]));
						$(".hide").show("slow");
						$("#complento").focus();
								
					}
					else {
						alert("Endereço não encontrado");
					}
				});
						
			}
		}
}

function mostraDetalhesCliente(id){
		
	$.post('../ajax/pegaDetalhesCliente.php',{idCliente:id},
		function(resposta){
		// resposta
		/*$('#novaCertificacao').css({
			textAlign: "center",
			fontSize: "14px",
			fontWeight: "bold",
			paddingTop:"30px"
		});*/
		//alert(unescape(resposta));
		$('#detalhesCliente').show('slow');
		$('#detalhesCliente').html(unescape(resposta));
	});
		
}