var emailValido = false;

function validaCampos(){
	var totalCampos = document.envioForm.elements.length;
	var obrigaVazios = 0;
	for (var i=0;i<totalCampos;i++){
		cssClass = document.envioForm.elements[i].className;
		if ((cssClass.match("required-entry")) && (document.envioForm.elements[i].value=="")) {
			document.envioForm.elements[i].className = cssClass + " validation-failed";
			obrigaVazios += 1;
		}else if ((cssClass.match("required-entry")) && (document.envioForm.elements[i].value!="")){
			document.envioForm.elements[i].className = cssClass.replace(" validation-failed","");
		}
	}
	if (obrigaVazios>0){
		$("advice-required-entry-name").innerHTML = "Preencha os campos obrigat&oacute;rios";
		$("advice-required-entry-name").show();
	}else{
		emailcerto = validaEmail("email_contato");
		if (emailcerto){
			sitecerto = true;
			if ($('cnpj')) {
				cnpjcerto = validaCnpj();
			}else{
				cnpjcerto = true;	
			}
			if (cnpjcerto){
				$("advice-required-entry-email").hide();
				if($("advice-required-entry-cnpj")) $("advice-required-entry-cnpj").hide();
				if ($('site')) {
					sitecerto = validaUrl();
				}else{
					sitecerto = true;
				}
				if (!sitecerto){
					$('site').className = $('site').className + " validation-failed";
					$("advice-required-entry-url").innerHTML = "URL inv&aacute;lida!";
					$("advice-required-entry-url").show();
				}else{
					$("advice-required-entry-name").hide();
					$("advice-required-entry-email").hide();
					telefonecerto = validaTelefone();
					if (telefonecerto!=""){
						$(telefonecerto).className = $(telefonecerto).className + " validation-failed";
						$("advice-required-entry-name").innerHTML = "Os campos Telefone Fixo e Celular devem ter n&uacute;meros de telefone v&aacute;lidos";
						$("advice-required-entry-name").show();
					}else{
						$('telefone').className = $('telefone').className.replace(" validation-failed","");
						$('celular').className = $('celular').className.replace(" validation-failed","");
						$("advice-required-entry-name").hide();
						document.envioForm.submit();
					}
				}
			}else{
				$("advice-required-entry-email").hide();
				$('cnpj').className = $('cnpj').className + " validation-failed";
				$("advice-required-entry-cnpj").innerHTML = "CNPJ inv&aacute;lido!";
				$("advice-required-entry-cnpj").show();
			}
		}else{
			$('email_contato').className = $('email_contato').className + " validation-failed";
			$("advice-required-entry-email").innerHTML = "Campo e-mail inv&aacute;lido!";
			$("advice-required-entry-email").show();
		}
	}
}

function validaEmail(campo) {
	var email = $(campo);
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email.value)) {
		return false;
	}else{
		var sufixo = email.value.split('@');
		var url = '/cadastro/valida_tld.php?site=' + sufixo[1]; 
		var valida = validaTld(url);
		return(valida);
	}
}

function validaTld(url){
	new Ajax.Request(url, {
			asynchronous: false,
			method:'get',
			onSuccess: function(transport){
				var retorno = parseInt(transport.responseText);
				if (retorno>0){
					emailValido = true;
				}else{
					emailValido = false;
				}
			}
	});
	return emailValido;
}


function validaUrl() {
	var site = $('site');
	if (site.value!=''){
		var filter = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
		if (!filter.test(site.value)) {
			return false;
		}else{
			return true;
		}
	}else{
		return true;
	}
}

function validaTelefone(){
	var telefone = $('telefone');
	var celular = $('celular');
	if (telefone.value!=''){
	     if (telefone.value.length < 11){
	     	return 'telefone';
	     }else{
	     	if (celular.value!=''){
	     		if (celular.value.length < 11){
	     			return 'celular';
	     		}else{
	     			return '';
	     		}
	     	}else{
				return '';
			}
	     }
	}else{
				return '';
			}
}

function validaCnpj(){
                CNPJ = $('cnpj').value;
                 erro = new String;
                 if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! "; 
                 if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
                 if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! ";
                 }
                 //substituir os caracteres que não são números
               if(document.layers && parseInt(navigator.appVersion) == 4){
                       x = CNPJ.substring(0,2);
                       x += CNPJ. substring (3,6);
                       x += CNPJ. substring (7,10);
                       x += CNPJ. substring (11,15);
                       x += CNPJ. substring (16,18);
                       CNPJ = x; 
               } else {
                       CNPJ = CNPJ. replace (".","");
                       CNPJ = CNPJ. replace (".","");
                       CNPJ = CNPJ. replace ("-","");
                       CNPJ = CNPJ. replace ("/","");
               }               var nonNumbers = /\D/;
               if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! "; 
               var a = [];
               var b = new Number;
               var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
               for (i=0; i<12; i++){
                       a[i] = CNPJ.charAt(i);
                       b += a[i] * c[i+1];
		}
               if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
               b = 0;
               for (y=0; y<13; y++) {
                       b += (a[y] * c[y]); 
               }
               if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
               if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
                       erro +="Dígito verificador com problema!";
               }
               if (erro.length > 0){
                       return false;
               }
               return true;
}

function buscaCep(){
	cepL = $('zip').value;
	if (cepL!=''){
		cep = cepL.replace("-","");
		url = "/cadastro/DataCareClient.php?service=checkCEP&cep=" + cep;
		new Ajax.Request(url, {   
			method: 'get',   
			onSuccess: processCepXml
		}); 
	}else{
		alert('Preencha o CEP, por favor.');
	}
}

function processCepXml(transport) {
	
	// Esconde mensagem de loading
	$('advice-first-zip').innerHTML = '';
	$('advice-first-zip').hide();
	
	var xml = transport.responseXML;
	var dataArray   = xml.getElementsByTagName("registro");
    if(dataArray.length > 0) {
    	var item = dataArray[0];
        var codigoRetorno = item.getElementsByTagName("codigoRetorno")[0].firstChild.nodeValue;
        if (codigoRetorno == 0) // cep completo
        {
        	var bairro    		  	=  item.getElementsByTagName("bairro")[0].firstChild.nodeValue;			 
			var nomeLogradouro    	=  item.getElementsByTagName("nomeLogradouro")[0].firstChild.nodeValue;
			var tipoLogradouro    	=  (item.getElementsByTagName("tipoLogradouro")[0].firstChild != null) ? item.getElementsByTagName("tipoLogradouro")[0].firstChild.nodeValue : "";
			var cidade    		  	=  item.getElementsByTagName("cidade")[0].firstChild.nodeValue;			
			var estado    			=  item.getElementsByTagName("estado")[0].firstChild.nodeValue;
			
			$('street_1').value = tipoLogradouro + ' ' + nomeLogradouro;
			$('city').value = cidade;
			$('bairro').value = bairro;
			$('region').value = estado
			$('advice-first-zip').hide();
					
			jQuery("#bairro").attr("readonly", "readonly"); 
			jQuery("#street_1").attr("readonly", "readonly");
			jQuery("#numero").focus();
        }
        else if (codigoRetorno == 100) //cep generico 
        {
        	var cidade  =  item.getElementsByTagName("cidade")[0].firstChild.nodeValue;			
			var estado  =  item.getElementsByTagName("estado")[0].firstChild.nodeValue;
			
			$('city').value = cidade;
			$('region').value = estado;
			$('advice-first-zip').hide();
			
     	   	if (jQuery("#bairro").val() != "")   jQuery("#bairro").val("");
     	   	if (jQuery("#street_1").val() != "") jQuery("#street_1").val("");
           
     	   	jQuery("#street_1").removeAttr("readonly");
     	   	jQuery("#bairro").removeAttr("readonly");
     	   	jQuery("#street_1").focus();
        }
        else if (codigoRetorno == 1 ||codigoRetorno == 2 || codigoRetorno == 3) //não encontrou
        {
			$('advice-first-zip').innerHTML = "N&atilde;o foi poss&iacute;vel localizar o CEP informado.";
			$('advice-first-zip').show();
			
			jQuery("#street_1").val("");
			jQuery("#bairro").val("");
			jQuery("#city").val("");
			jQuery("#region").val("");
			
			jQuery("#zip").focus();
        }
    }
}

function buscaCepAdm(form_id){
	cepL = $(form_id + 'postcode').value;
	if (cepL!=''){
		cep = cepL.replace("-","");
		url = "/cadastro/cep.php?cep=" + cep;
		new Ajax.Request(url, {   
			method: 'get',   
			onSuccess: function(transport) { 
				endereco = transport.responseText.replace(/^\s\s*/, '').replace(/\s\s*$/, '').split('|');
				if (endereco[0].length<2){
					$('advice-first-zip').innerHTML = "Endere&ccedil;o n&atilde;o encontrado.";
					$('advice-first-zip').show();
				}else{
					if ($(form_id + 'street1'))
						$(form_id + 'street1').value =endereco[0] + ' ' + endereco[1];
					else
						$(form_id + 'street0').value =endereco[0] + ' ' + endereco[1];
					$(form_id + 'city').value =endereco[3];
					for (var i=0; i<$(form_id + 'region').options.length; i++){
						if ($(form_id + 'region').options[i].value == endereco[4]){
							$(form_id + 'region').options[i].selected=true;
						}
					}
					$('advice-first-zip').hide();
				}
			}
		}); 
	}else{
		alert('Preencha o CEP, por favor.');
	}
}

function buscaCepBilling(){
	cepL = $('billing:postcode').value;
	if (cepL!=''){
		cep = cepL.replace("-","");
		url = "/cadastro/cep.php?cep=" + cep;
		new Ajax.Request(url, {   
			method: 'get',   
			onSuccess: function(transport) { 
				endereco = transport.responseText.replace(/^\s\s*/, '').replace(/\s\s*$/, '').split('|');
				if (endereco[0].length<2){
					$('advice-first-zip').innerHTML = "Endere&ccedil;o n&atilde;o encontrado.";
					$('advice-first-zip').show();
				}else{
					$('billing:street1').value =endereco[0] + ' ' + endereco[1];
					$('billing:city').value =endereco[3];
					for (var i=0; i<$('billing:region').options.length; i++){
						if ($('billing:region').options[i].value == endereco[4]){
							$('billing:region').options[i].selected=true;
						}
					}
					$('advice-first-zip').hide();
				}
			}
		}); 
	}else{
		alert('Preencha o CEP, por favor.');
	}
}

function validaCaptcha(){
	var captchaField = $('autentica');
	v = captchaField.value;
	if (v!=''){
              	   var url = "/cadastro/captcha/auth.php?codigoimg=" + v;
		   new Ajax.Request(url, {   
			method: 'get',   
			onSuccess: function(transport) { 
				retorno = transport.responseText;  
				if (retorno!='Codigo OK'){
					captchaField.className="input-text required-entry validation-failed";
					captchaField.value="";
					$('advice-first-autentica').innerHTML = 'O c&oacute;digo digitado est&aacute; incorreto!';
					$('advice-first-autentica').show();
				}else{
					captchaField.className="input-text required-entry";
					$('advice-first-autentica').hide();
				}
				
			}
   		  }); 
   	}
}

function validaCaptchaSubmit(){
	var captchaField = $('autentica');
	v = captchaField.value;
	if (v!=''){
              	   var url = "/cadastro/captcha/auth.php?codigoimg=" + v;
		   new Ajax.Request(url, {   
			method: 'get',   
			onSuccess: function(transport) { 
				retorno = transport.responseText;  
				if (retorno!='Codigo OK'){
					captchaField.className="input-text required-entry validation-failed";
					captchaField.value="";
					$('advice-first-autentica').innerHTML = 'O c&oacute;digo digitado est&aacute; incorreto!';
					$('advice-first-autentica').show();
				}else{
					captchaField.className="input-text required-entry";
					$('advice-first-autentica').hide();
					    var dataForm = new VarienForm('form-validate', true);
					        if (dataForm.validator.validate()) {
					                        dataForm.submit();         
			                        }
				}
				
			}
   		  }); 
   	}else{
   		captchaField.className="input-text required-entry validation-failed";
   		$('advice-first-autentica').innerHTML = 'Este &eacute; um campo obrigat&oacute;rio.';
		$('advice-first-autentica').show();
   	}
}


function validaUnico(v){
	if (v.id=="cnpj"){
                   cnpj = v.value;
		   cnpj = cnpj. replace (".","");
                   cnpj = cnpj. replace (".","");
                   cnpj = cnpj. replace ("-","");
                   cnpj = cnpj. replace ("/","");
                   url = "/cadastro/checa_cpf.php?cnpj=" + cnpj;
                   aviso = "advice-first-cnpj";
        }else{           
                   cpf = v.value;
                   cpf = cpf.replace("-","");
		   cpf = cpf.replace(".","");
              	   cpf = cpf.replace(".","");
              	   url = "/cadastro/checa_cpf.php?cpf=" + cpf;
              	   aviso = "advice-first-cpf";
        }      	   
              	   
		   new Ajax.Request(url, {   
			method: 'get',   
			onSuccess: function(transport) { 
				retorno = transport.responseText;  
				if (retorno=='0'){
					$(aviso).style.display='none';
					$(aviso).innerHTML='';
					//$(v.id).className = 'required-entry input-text validate-cpf';
				}else{
					$(aviso).style.display='block';
					$(aviso).innerHTML='J&aacute; existe um usu&aacute;rio cadastrado com este CPF: ' + v.value;
					v.value = '';
					$(v.id).focus();
				}
			}
   		  }); 
}

function entraSenha(){
	if($('loginhsphere').value==""){
		$('advice-first-loginhsphere').innerHTML = 'Preencha o login';
		$('advice-first-loginhsphere').show();
		$('senhahsphere').value = '';
		$('loginhsphere').className = 'required-entry input-text validation-failed';
		$('loginhsphere').focus();
	}
}

/*
 * Método para validação do 'número'.
 */
function validaNumero() {
	if ($('numero').value == "" || parseInt($('numero').value) == 0) {
		$('numero').className = 'required-entry input-text validation-failed';
		$('advice-first-numero').innerHTML = "Digite um n&uacute;mero v&aacute;lido.";
		$('advice-first-numero').show();
	}
	else
	{
		$('numero').className = 'required-entry input-text';
		$('advice-first-numero').innerHTML = '';
		$('advice-first-numero').hide();
	}
}

function validaSenha(campo, id){
	var senha = campo.value;
	var valid = true;
	var message = "";
	
	if (senha.length < 5 || senha.length > 12)
	{
		valid = false;
		message = 'A senha deve conter de 5 a 12 caracteres.';
	}
	else if (senha.indexOf("1234") != -1)
	{
		valid = false;
		message = 'A senha n&atilde;o pode conter a sequ&ecirc;ncia "1234".';
	}
	else if (senha.indexOf($('loginhsphere').value) != -1 && $('loginhsphere').value != "") 
	{
		valid = false;
		message = 'A senha n&atilde;o pode conter o nome de usu&aacute;rio.';
	}
	else if (senha.match( /[A-Za-z0-9]+/ ) != senha) 
	{
		valid = false;
		message = 'A senha s&oacute; pode conter letras e n&uacute;meros.';
	}
	else
	{
		$(id).className = 'required-entry input-text';
		$('advice-first-' + id).innerHTML = '';
		$('advice-first-' + id).hide();
	}
	if (!valid) 
	{
		$(id).className = 'required-entry input-text validation-failed';
		$('advice-first-' + id).innerHTML = message;
		$('advice-first-' + id).show();
		//$(id).focus();
	}
}

function preencheLogin(){
	/* Executa validação de acordo com as regras de negócio. */
	if (!jQuery("#loginhsphere").attr("readonly")) 
	{
		if (validaLoginHsphere($('loginhsphere').value)) {
			
			// Exibe mensagem "carregando..."
			$('loginhsphere').className = 'required-entry input-text validation-failed';
			$('advice-first-loginhsphere').innerHTML = 'Aguarde, carregando...';
			$('advice-first-loginhsphere').show();
			
			url = "/TSP/checa_login.php?loginhsphere=" + $('loginhsphere').value;
			new Ajax.Request(url, {   
				method: 'get',   
				onSuccess: function(transport) { 
					$codigo = transport.responseText;
					if ($codigo==300){
						$('loginhsphere').className = 'required-entry input-text';
						$('advice-first-loginhsphere').innerHTML = '';
						$('advice-first-loginhsphere').hide();
					}else{
						$('loginhsphere').className = 'required-entry input-text validation-failed';
						$('advice-first-loginhsphere').innerHTML = 'Este login j&aacute; est&aacute; sendo utilizado, por favor escolha outro.';
						$('advice-first-loginhsphere').show();
						$('loginhsphere').focus();
					}
				}
			}); 
		}
		else {
			$('loginhsphere').className = 'required-entry input-text validation-failed';
			$('advice-first-loginhsphere').innerHTML = 'O login digitado &eacute; inv&aacute;lido. Deve conter de 5 a 20 caracteres, sendo letras ou n&uacute;meros, n&atilde;o podendo iniciar com n&uacute;meros.';
			$('advice-first-loginhsphere').show();
			$('loginhsphere').focus();
		}
	}
}

function validaLoginHsphere(login) {
	var valid = false;
	if (login != "") {
		return (login.length >= 5 && login.length <= 20 && login.match( /[A-Za-z][A-Za-z0-9/:.]+/ )==login);
	}
	return valid;
}

// MASCARAS
function Mascara(tipo, campo, teclaPress) {
	if (window.event)
	{
		var tecla = teclaPress.keyCode;
	} else {
		tecla = teclaPress.which;
	}
 
	var s = new String(campo.value);
	// Remove todos os caracteres ? seguir: ( ) / - . e espa?o, para tratar a string denovo.
	s = s.replace(/(\.|\(|\)|\/|\-| )+/g,'');
 
	tam = s.length + 1;
 
	if ( tecla != 9 && tecla != 8 ) {
		switch (tipo)
		{
		case 'CPF' :
			if (tam > 3 && tam < 7)
				campo.value = s.substr(0,3) + '.' + s.substr(3, tam);
			if (tam >= 7 && tam < 10)
				campo.value = s.substr(0,3) + '.' + s.substr(3,3) + '.' + s.substr(6,tam-6);
			if (tam >= 10 && tam < 12)
				campo.value = s.substr(0,3) + '.' + s.substr(3,3) + '.' + s.substr(6,3) + '-' + s.substr(9,tam-9);
		break;
 
		case 'CNPJ' :
 
			if (tam > 2 && tam < 6)
				campo.value = s.substr(0,2) + '.' + s.substr(2, tam);
			if (tam >= 6 && tam < 9)
				campo.value = s.substr(0,2) + '.' + s.substr(2,3) + '.' + s.substr(5,tam-5);
			if (tam >= 9 && tam < 13)
				campo.value = s.substr(0,2) + '.' + s.substr(2,3) + '.' + s.substr(5,3) + '/' + s.substr(8,tam-8);
			if (tam >= 13 && tam < 15)
				campo.value = s.substr(0,2) + '.' + s.substr(2,3) + '.' + s.substr(5,3) + '/' + s.substr(8,4)+ '-' + s.substr(12,tam-12);
		break;
 
		case 'TEL' :
			if (tam >= 5 && tam < 11)
				campo.value = s.substr(0,4) + '-' + s.substr(4,tam-2);
		break;
		
		case 'TELDDD' :
			if (tam >= 3 && tam < 4)
				campo.value = '(' + s.substr(0,2) + ')' + s.substr(2, tam);		
			if (tam >= 8 && tam < 14)
				campo.value =  '(' + s.substr(0,2) + ')' + s.substr(2,4) + '-' + s.substr(6,tam-2);
		break;
		
		case 'CEP' :
			if (tam >= 6 && tam < 9)
				campo.value = s.substr(0,5) + '-' + s.substr(5,tam-2);
		break;

		break;
 
		case 'DATA' :
			if (tam > 2 && tam < 4)
				campo.value = s.substr(0,2) + '/' + s.substr(2, tam);
			if (tam > 4 && tam < 11)
				campo.value = s.substr(0,2) + '/' + s.substr(2,2) + '/' + s.substr(4,tam-4);
		break;
		}
	}
}

function mudaCadastro(tipo){
	if (tipo=='pf'){
		$('dadosempresa').style.display='none';
	}else{
		$('dadosempresa').style.display='block';
	}
}

function checaNumero( e )
{
	charcode = window.event ? e.keyCode : e.which;
	charvalue = String.fromCharCode( charcode );
	
	validate = inArray( [ 0, 8, 9, 16, 17, 18 ], charcode ) ? true : charvalue.match( /[0-9]+/ ) ? true : false;
	
	return validate;
}
	
// Fun??o que verifica a exist?ncia do valor no array
function inArray ( array, value )
{
	for( var i = 0; i < array.length; i++ )
		if( array[ i ] == value )
			return true;
		return false;
}

function checaNome(e){

	charcode = window.event ? e.keyCode : e.which;
	charvalue = String.fromCharCode( charcode );
	
	validate = inArray( [ 0, 8, 9, 16, 17, 18 ], charcode ) ? true : charvalue.match( /[^!-@]+/ ) ? true : false;
	
	return validate;
}

function checaUrl(e){

	charcode = window.event ? e.keyCode : e.which;
	charvalue = String.fromCharCode( charcode );
	
	validate = inArray( [ 0, 8, 9, 16, 17, 18 ], charcode ) ? true : charvalue.match( /[A-Za-z0-9/:.]+/ ) ? true : false;
	
	return validate;
}


function forcaSenha(campo, aviso){
        var senha = campo.value;
        if (senha!=""){
		var entrada = 0;
		var resultado;

		if(senha.length < 7){
			entrada = entrada - 1;
		}

		if(!senha.match(/[a-z_]/i) || !senha.match(/[0-9]/)){
			entrada = entrada - 1;
		}

		if(!senha.match(/\W/)){
			entrada = entrada - 1;
		}

		if(entrada == 0){
			resultado = 'A seguran&ccedil;a de sua senha &eacute;: <font color=\'#99C55D\'>EXCELENTE</font>';
		} else if(entrada == -1){
			resultado = 'A seguran&ccedil;a de sua senha &eacute;: <font color=\'#7F7FFF\'>BOM</font>';
		} else if(entrada == -2){
			resultado = 'A seguran&ccedil;a de sua senha &eacute;: <font color=\'#FF5F55\'>BAIXA</font>';
		} else if(entrada == -3){
			resultado = 'A seguran&ccedil;a de sua senha &eacute;: <font color=\'#A04040\'>MUITO BAIXA</font>';
		}

		$(aviso).innerHTML = resultado;
		$(aviso).show();
	}else{
		$(aviso).innerHTML = '';
	}
}
function checkAlphaNum(e)
{
	charcode = window.event ? e.keyCode : e.which;
	charvalue = String.fromCharCode( charcode );
	
	validate = (inArray( [ 0, 8, 9, 16, 17, 18 ], charcode ) || charvalue.match( /[A-Za-z0-9]+/ )) ? true : false;
	
	return validate;
}

function checkDomain( e, enter )
{
	charcode = window.event ? e.keyCode : e.which;
	charvalue = String.fromCharCode( charcode );
	
	enter = ( enter == true ) ? true : false;
	
	// Executa a a??o de busca ao pressionar o 'enter'
	if( charcode == 13 && enter )
		searchSuggest();
	
	validate = inArray( [ 0, 8, 9, 16, 17, 18 ], charcode ) ? true : charvalue.match( /[A-Za-z0-9-]+/ ) ? true : false;
	
	return validate;

}

function checaEmail( e, enter )
{
	charcode = window.event ? e.keyCode : e.which;
	charvalue = String.fromCharCode( charcode );
	
	enter = ( enter == true ) ? true : false;
	
	// Executa a a??o de busca ao pressionar o 'enter'
	if( charcode == 13 && enter )
		searchSuggest();
	
	validate = inArray( [ 0, 8, 9, 16, 17, 18 ], charcode ) ? true : charvalue.match( /[A-Za-z0-9_.@]+/ ) ? true : false;
	
	return validate;

}

function openWindow(url, name, width, height){ 
	var winWidth = width;
	var winHeight = height;
	var winTop = parseInt((screen.availHeight - winHeight) / 2);
	var winLeft = parseInt((screen.availWidth - winWidth) / 2);
	
	popupWin = window.open(url,name,"width=" + winWidth + ",height=" + winHeight + ",top=" + winTop + ",left=" + winLeft + ",resizable=no,scrollbars=yes,statusbar=yes");
	if (popupWin.opener == null) popupWin.opener = self;
}

function preencheCC(){
	$('cartaocredito_cc_number').value = $('cc_number_part1').value + $('cc_number_part2').value + $('cc_number_part3').value + $('cc_number_part4').value;
}

function vaiProximo(campoatual, proximocampo){
	if (campoatual.value.length==2){
		$(proximocampo).focus();
	}
}

function checkCep(field) 
{
	if (field.value.length == 9) {
		
		// Exibe mensagem "carregando..."
		$('advice-first-zip').innerHTML = 'Aguarde, carregando...';
		$('advice-first-zip').show();
		
		buscaCep();
	}
}