//// Projeto : RANULFO ALVES PEREIRA - Active Company 
//// Email   : webmaster@activecompany.com.br                    

$( document ).ready( function(){
	fade_m( "in", 6 );
	login_legendas();
	window.setTimeout( "slidegrupo( 0 )", 300 );
} );

function fade_m( dir, qt ){
	if( ( $.browser.msie && $.browser.version>=7 ) || !$.browser.msie ){
		if( qt>0 ){
			qt--;
			if( dir=="in" ){
				$( "#mensagem span" ).animate( { opacity: 0.2 }, "slow", function(){ fade_m( "out", qt ) } );
			}
			else{
				$( "#mensagem span" ).animate( { opacity: 1 }, "slow", function(){ fade_m( "in", qt ) } );
			}
		}
		else{
			window.setTimeout( "fade_m( 'in', 6 )", 10000 );
		}
	}
}

function slidegrupo( indice ){
	var mensagem = [ "Alugue já o seu imóvel.", "Seja você mesmo seu fiador!", "Conheça as vantagens da<br> Fiança Locatícia Social."];
	if( indice>mensagem.length-1 ){
		indice = 0;
	}
	$( "#slidegrupo" ).animate( { textIndent: "-300px" }, 200, function(){
		$( "#slidegrupo" ).css( "text-indent", "200px" );
		$( "#slidegrupo" ).html( mensagem[ indice ] );
		indice++;
		$( "#slidegrupo" ).animate( { textIndent: "0" }, 200, function(){
			window.setTimeout( "slidegrupo( "+indice+" )", 5000 );
		} );
	} );
}

function login_legendas(){
	$( "#usuario" ).val( "Insira seu login" );
	$( "#senha" ).remove();
	$( "#entrar" ).before( "<input type=\"text\" id=\"senha\" name=\"senha\" value=\"Insira sua senha\" style=\"position: relative; top: 0; left: 0;\" />" );
	$( "#usuario, #senha" ).css( { "color": "#aaa", "font-size": "0.8em" }  );
	$( "#usuario, #senha" ).focus( function(){ login_focus( $( this ) ) } );
	$( "#usuario, #senha" ).blur( function(){ login_blur( $( this ) ) } );
}

function login_focus( self ){
	if( self.val()=="Insira seu login" || self.val()=="Insira sua senha" ){
		self.val( "" );
		self.css( "color", "#000" );
		if( self.attr( "id" )=="senha" ){
			$( "#senha" ).remove();
			$( "#entrar" ).before( "<input type=\"password\" id=\"senha\" name=\"senha\" />" );
			$( "#senha" ).focus();
			$( "#senha" ).blur( function(){ login_blur( $( this ) ) } );
		}
	}
}

function login_blur( self ){
	if( self.val()=="" ){
		if( self.attr( "id" )=="usuario" ){
			self.css( "color", "#aaa" );
			self.val( "Insira seu login" );
		}
		else{
			$( "#senha" ).remove();
			$( "#entrar" ).before( "<input type=\"text\" id=\"senha\" name=\"senha\" value=\"Insira sua senha\" style=\"color: #aaa; font-size: 0.8em\" />" );
			$( "#senha" ).focus( function(){ login_focus( $( this ) ) } );
		}
	}
}

function valida(frmNome, url, destino){
  var erro="N";
  if(document.getElementById("usus_login").value=='' || document.getElementById("usus_login").value=='Login'){
    alert("Você precisa informar o Login de usuário.");
    document.getElementById("usus_login").focus();
    erro="S";
    return false;
  }
  if(document.getElementById("usus_senha").value=='' || document.getElementById("usus_senha").value=='Senha'){
    alert("Você precisa informar a Senha.");
    document.getElementById("usus_senha").focus();
    erro="S";
    return false;
  }
  if(erro=="N"){enviaForm(frmNome, url, destino); document.getElementById("usus_login").value="Login"; document.getElementById("usus_senha").value="Senha"}
  return false;
}

window.defaultStatus = "Aluguebens - Alugue Imóveis sem Fiador";


$( document ).ready( function(){
	window.setTimeout( function(){ troca_banner( 1 ) }, 20000 );
	login_senha();
} );

function login_senha(){
	$( "#usus_login" ).val( "Login" );
	$( "#usus_senha" ).val( "Senha" );
	$( "#usus_login" ).focus( function(){
		if( $( this ).val()=="Login" ){
			$( this ).val( "" );
		}
	} );
	$( "#usus_senha" ).focus( function(){
		if( $( this ).val()=="Senha" ){
			$( this ).val( "" );
		}
	} );

	$( "#usus_login, #usus_senha" ).blur( function(){
		if( $( this ).val()=="" ){
			var label = ( $( this ).attr( "id" )=="login" )?"Login":"Senha";
			$( this ).val( label );
		}
	} );
}

function troca_banner( indice ){
	var banners = [ "BANNER.swf", "BANNER2.swf" ];
	$( "#topo div.banner" ).html( object_swf( "../images/"+banners[ indice ], 500, 60 ) );
	if( indice==1 ){ indice = 0; }else{ indice = 1; }
	window.setTimeout( function(){ troca_banner( indice ) }, 20000 );
}

function object_swf( arquivo, width, height ){
	var swf = "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0' width='"+width+"' height='"+height+"'>";
	swf += "<param name='movie' value='"+arquivo+"' />";
	swf += "<param name='quality' value='high' />";
	swf += "<embed src='"+arquivo+"' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' width='"+width+"' height='"+height+"'></embed>";
	swf += "</object>";
	return swf;
}


// bloqueia visualizacao do fonte
function verfonte() {
  if(event.button==2){
    window.alert('O código fonte deste site não pode ser exibido.\n\  Mas solicite você infrmação para o endereço:\n\         webmaster@activecompany.com.br\n\n\     Clique em Ok, para continuar navegando.');
  }
}

// abre janela poup-up de ajuda do sistema
function OpenUpAjuda(pagina,janela) {
   window.open(pagina,janela,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,menubar=no,width=520,height=400')
}

// funcao para impressao
function imprimir(){
   window.print();
}

//funcao voltar campos
function voltar(todoscampos,getoupost,tab){
  enviagenerico(todoscampos,document.getElementById("ultima").value,getoupost,tab)
}

// funcao de validacao login e senha
function validaloginsenha(){
  var pronto="S";
  if(document.getElementById("login").value==""){
	alert("Informe o login.");
	pronto="N";
	document.getElementById("login").focus();			
  }
  if(pronto=="S"){
	enviaForm('verloginsenha','../adm/index.php','pagina');
  }
}

// funcao Ajax
function enviacomfoco(campo,todoscampos,idcampo,getoupost,tab){
  enviagenerico(todoscampos,idcampo,getoupost,tab);
}

function foco_primeiro( id_form ){
  for (var i=0; i<document.getElementById( id_form ).elements.length;i++){
    if(document.getElementById( id_form ).elements[i].type!="hidden"){
      document.getElementById( id_form ).elements[i].focus();
      window.setTimeout(function() { document.getElementById( id_form ).elements[i].focus();},250)
      //alert(document.getElementById( id_form ).elements[i].id)
      return;
    }
  }
}

/*
function click() {
  if (event.button==2) {
    alert('Todos os Direitos Reservados.')
  }
}
document.onmousedown=click

function disableselect(e){
  return false
}
function reEnable(){
  return true
}
document.onselectstart=new Function ("return false")
if (window.sidebar){
  document.onmousedown=disableselect
  document.onclick=reEnable
}
						 */

  
function ajaxupload( config ){
	// BLOQUEIA O FUNCIOAMENTO NO INTERNET EXPLORER 6
	if( $.browser.msie && $.browser.version<7 ){ alert( "Navegador não suportado. Tente novamente com um navegador atual." );return; }

	// VERIFICA O PARÂMETRO
	if( config.url==null ){ config.url = ""; }
	if( config.fileField==null ){ config.fileField = ""; }
	if( config.type==null ){ config.type = ""; }
	if( config.size==null ){ config.size = 0; }
	if( config.onComplete==null ){ config.onComplete = function(){}; }

	// CRIA O IFRAME
	$( "body" ).append( "<iframe id='iajax' name='iajax' name='iajax' width='0' height='0' style='position: absolute;top: 0; left: 0;'></iframe>" );

	// CRIA O FORM
	$( "body" ).append( "<form id='fajax' action='"+config.url+"' method='post' enctype='multipart/form-data' target='iajax' style='position: absolute;top: 0;left: 0;width: 0;height: 0;overflow: hidden;'></form>" );
	$( "#"+config.fileField ).clone( true ).insertAfter( "#"+config.fileField );
	$( "#"+config.fileField ).appendTo( "#fajax" );
	$( "#fajax" ).append( "<input type='text' name='type' value='"+config.type+"' />" );
	$( "#fajax" ).append( "<input type='text' name='size' value='"+config.size+"' />" );

	// ATRIBUI O ON-LOAD AO IFRAME
	$( "#iajax" ).load( function(){
		var contentFrame = ( this.contentWindow )?this.contentWindow.document:this.contentDocument;
		config.onComplete( contentFrame.body.innerHTML );
		$( "#iajax, #fajax" ).remove();
	} );

	// ENVIA O FORMULÁRIO
	$( "#fajax" )[ 0 ].submit();
}

function uti_upload(){
	ajaxupload( {
		url: "uti_upload.php",
		fileField: "arquivo",
		onComplete: function( retorno ){
		  eval( "var resultado="+retorno );
		  alert( resultado["msg"]);
		  enviagenerico(resultado["parametros"].replaceall( "&amp;","&"),'uti_cobranca.php','POST','abaixo');
		}
	} );
}  
  
String.prototype.replaceall = function( token, newtoken){
  var string= this;
  while(string.indexOf(token)!=-1){
    string= string.replace(token, newtoken);
  }
  return string;
}

function conv_upload( gatilho ){
	ajaxupload( {
		url: "uti_convupload.php",
		fileField: "arquivo",
		onComplete: function( retorno ){
			if( retorno.indexOf( "ERRO:" )!=-1 ){
				alert( retorno.replace( "ERRO:", "" ) );
			}
			if( retorno.indexOf( "ARQUIVO:" )!=-1 ){
				$( "#img_tex" ).val( retorno.split( "/" ).last() );
			}
			uti_cad( "tex_cad", "uti_cadtexto.php", "abaixo" );
		}
	} );
}

Array.prototype.last = function(){
	var array = this;
	return array[ array.length-1 ];
};

function horas(){
  var now = new Date();
  var hours = now.getHours();
  var minutes = now.getMinutes();
  var seconds = now.getSeconds()
  if(hours <=9)
    hours="0"+hours;
  if(minutes<=9)
    minutes="0"+minutes;
  if(seconds<=9)
    seconds="0"+seconds;
  var cdate="<span class=style11>"+hours+":"+minutes+":"+seconds+" "+"</span>" 
  document.getElementById("clock").innerHTML= cdate;
  setTimeout("horas()",1000);
}


// mover relogio
function moveRelogio(){
  momentoAtual = new Date()
  hora = momentoAtual.getHours()
  minuto = momentoAtual.getMinutes()
  segundo = momentoAtual.getSeconds()
  str_segundo = new String (segundo)
  if(str_segundo.length == 1)
    segundo = "0" + segundo
    str_minuto = new String (minuto)
    if(str_minuto.length == 1)
      minuto = "0" + minuto
    str_hora = new String (hora)
    if(str_hora.length == 1)
       hora = "0" + hora
	if(document.getElementById('campoteste2').value==""){
 	  document.getElementById('campoteste2').value=segundo;
	  var tempofinal=document.getElementById('campoteste2').value+3;
	}		
	document.getElementById('campoteste').value=tempofinal;
	if(document.getElementById('campoteste2').value==tempofinal){
	  document.getElementById('palav').value='00000';
	}
    setTimeout("moveRelogio()",1000)
}

// estracao de scrit de texo
function extraiScript(texto){
  //Maravilhosa função feita pelo SkyWalker.TO do imasters/forum
  // inicializa o inicio ><
  var ini = 0;
  // loop enquanto achar um script
  while (ini!=-1){
    // procura uma tag de script
    ini = texto.indexOf('<script', ini);
    // se encontrar
    if(ini >=0){
      // define o inicio para depois do fechamento dessa tag
      ini = texto.indexOf('>', ini) + 1;
      // procura o final do script
      var fim = texto.indexOf('</script>', ini);
      // extrai apenas o script
      codigo = texto.substring(ini,fim);
      //  alert(codigo);
	  // executa o script
      // eval(codigo);	 
      novo = document.createElement("script")
	  // Define parâmetro language=javascript para o objeto de script
  	  novo.setAttribute('language', 'javascript');
      novo.text = codigo;
	  document.body.appendChild(novo);	 
    }
  }
}

// funcao envia formulario com id para validar/gravar/alterar (AJAX)
function enviaForm(frmNome, url, destino){
  var query='';
  // Captura o form
  f = document.getElementById(frmNome);
  for (i=0;i<f.elements.length;i++){
    // concatena a variavel na query
    if(f.elements[i].type=='radio'||f.elements[i].type=='checkbox'){
      if(f.elements[i].checked){
        query +=  '&'+f.elements[i].name + '=' + f.elements[i].value;
      }
    } else {
      query +=  '&'+f.elements[i].name + '=' + escape( f.elements[i].value.replace("&","@@@@@@") );
    }
  }
  // envia o formulario
  //alert(query);
  if(arguments[3]==null){
    enviagenerico(query,url,'POST',destino);
  } else {
    enviagenerico(query,url,'POST',destino,arguments[3]);    
  }
}

// funcao loading (aguarde)
function Loading(a,tab){
  if(a=='on'){
    document.getElementById(tab).innerHTML = "<img src='../images/aguarde.gif'><br>aguarde...";
  } else {
    document.getElementById(tab).innerHTML = "";
  }
}		

// funcao start do AJAX
function startAjax(){
  try { xmlhttp = new XMLHttpRequest(); } 
    catch(e) {
    try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } 
      catch(ee) {	
      try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");} 
        catch(E){
        xmlhttp = false;
      }
    }
  } 
  return xmlhttp;
}	
		
// funcao enviar link  (AJAX)
function enviagenerico(todoscampos,enderecourl,getoupost,tab){
  if(arguments[4]!=null){ var callback=arguments[4];}
  var maiscampos=todoscampos;
  var ajax = startAjax();			
  if(ajax){
    Loading('on', tab);
    ajax.open(getoupost,enderecourl,true)
    ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    ajax.onreadystatechange = function(){		
      if(ajax.readyState==4){
	Loading('off', tab);
	//var get = ajax.responseText.replace(/\+/g," ");
	extraiScript(ajax.responseText);
	//alert (ajax.responseText);
	document.getElementById(tab).innerHTML = ajax.responseText;
	if(callback!=null){
	  callback();
	}      
      }
    }
    maiscampos=maiscampos+"&navegador="+document.getElementById('navegador').value;		
    ajax.send(maiscampos);
    /*
    if(document.getElementById("atual").value!=enderecourl){
	  document.getElementById("ultima").value=document.getElementById("atual").value;
	  document.getElementById("atual").value=enderecourl;
    }*/
  } 
}


function buscaPorCEP(url){
	$.ajax( {
//		url: "../sys_sys/adm_cadfuncionario.php?cep=true",
		url: url,
		type: "POST",
		data: "cli_cep="+$( "#cli_cep" ).val(),
		success: function( response ){ 

			eval( "var dadosCEP="+response );
			for( var i=0;i<$( "#cmbbxn11_0" )[ 0 ].options.length;i++ ){
				if( $( "#cmbbxn11_0" )[ 0 ].options[ i ].value==dadosCEP[ "uf" ].toUpperCase() ){
					$( "#cmbbxn11_0" )[ 0 ].options[ i ].selected = true;
				}
			}
			
			
			list_dados_1( $("#cmbbxn11_0").parents( "form")[0],0,1,1);

                        window.setTimeout( function(){
			for( var i=0;i<$( "#cmbbxn11_1" )[ 0 ].options.length;i++ ){
				if( $( "#cmbbxn11_1" )[ 0 ].options[ i ].value==dadosCEP[ "cidade_cod" ].toUpperCase() ){
					$( "#cmbbxn11_1" )[ 0 ].options[ i ].selected = true;
				}
			}
			},1000);
			
			$( "#cender" ).val( dadosCEP[ "logradouro" ] );
			$( "#cbairr" ).val( dadosCEP[ "bairro" ] );
		}
	} );
}


function buscaPorCEP02(url){
	$.ajax( {
//		url: "../sys_sys/adm_cadfuncionario.php?cep=true",
		url: url,
		type: "POST",
		data: "c__cep="+$( "#c__cep" ).val(),
		success: function( response ){
		  		  
			eval( "var dadosCEP02="+response );			
			for( var i=0;i<$( "#cmbbx1_0" )[ 0 ].options.length;i++ ){
				if( $( "#cmbbx1_0" )[ 0 ].options[ i ].value==dadosCEP02[ "uf" ].toUpperCase() ){
					$( "#cmbbx1_0" )[ 0 ].options[ i ].selected = true;
				}
			}			
			list_dados( $("#cmbbx1_0").parents( "form")[0],0,1,1);
                        window.setTimeout( function(){
			for( var i=0;i<$( "#cmbbx1_1" )[ 0 ].options.length;i++ ){
				if( $( "#cmbbx1_1" )[ 0 ].options[ i ].value==dadosCEP02[ "cidade_cod" ].toUpperCase() ){
					$( "#cmbbx1_1" )[ 0 ].options[ i ].selected = true;
				}
			}
			
		      
			
			},1000);
			
			$( "#cenderr" ).val( dadosCEP02[ "logradouro" ] );
			$( "#cbairrr" ).val( dadosCEP02[ "bairro" ] );
		}
	} );
}


// formata campos diversos
function formatar(mascara, documento){
  var i = documento.value.length;
  var saida = mascara.substring(0,1);
  var texto = mascara.substring(i)  
  if (texto.substring(0,1) != saida){
	documento.value += texto.substring(0,1);
  }
}

// formata campo de mes referencia
function mascara_referencia(nascimento,campoesp){ 
  var mynascimento = ''; 
  mynascimento = mynascimento + nascimento; 
  if(mynascimento.length == 2){ 
    mynascimento = mynascimento + '-'; 
    campoesp.value = mynascimento; 
  } 
  if(mynascimento.length == 7){ 
    verifica_referencia(campoesp); 
  } 
} 

// verifica mes referencia
function verifica_referencia (campoesp) { 
  mes = (campoesp.value.substring(0,2)); 
  ano = (campoesp.value.substring(3,7)); 
  situacao = ""; 
  // verifica se o mes e valido 
  if(mes < "01" || mes > "12" ) { 
    situacao = "falsa"; 
  } 
  // verifica se e ano bissexto 
  if(mes == "2" && ( dia < "01" || dia > "29" || ( dia > "28" && (parseInt(ano / 4) != ano / 4)))) { 
    situacao = "falsa"; 
  }     
  if(campoesp.value == "") { 
    situacao = "falsa"; 
  }     
  if(situacao == "falsa") { 
    alert("A Referencia "+campoesp.value+" é inválida!\nInsira uma referência correta!"); 
	campoesp.value=""; 
    campoesp.focus(); 
  } 
}		  

// formata campo data
function mascara_nascimento(nascimento,campoesp){ 
  var mynascimento = ''; 
  mynascimento = mynascimento + nascimento; 
  if(mynascimento.length == 2){ 
    mynascimento = mynascimento + '-'; 
    campoesp.value = mynascimento; 
  } 
  if(mynascimento.length == 5){ 
    mynascimento = mynascimento + '-'; 
    campoesp.value = mynascimento; 
  } 
  if(mynascimento.length == 10){ 
    verifica_nascimento(campoesp); 
  } 
} 

// verifica campo data
function verifica_nascimento (campoesp) { 
  dia = (campoesp.value.substring(0,2)); 
  mes = (campoesp.value.substring(3,5)); 
  ano = (campoesp.value.substring(6,10)); 
  situacao = ""; 
  // verifica o dia valido para cada mes 
  if((dia < "01")||(dia < "01" || dia > "30") && (  mes == "04" || mes == "06" || mes == "09" || mes == "11" ) || dia > "31") { 
    situacao = "falsa"; 
  } 
  // verifica se o mes e valido 
  if(mes < "01" || mes > "12" ) { 
    situacao = "falsa"; 
  } 
  // verifica se e ano bissexto 
  if(mes == "2" && ( dia < "01" || dia > "29" || ( dia > "28" && (parseInt(ano / 4) != ano / 4)))) { 
    situacao = "falsa"; 
  }     
  if(campoesp.value == "") { 
    situacao = "falsa"; 
  }     
  if(situacao == "falsa") { 
    alert("A Data "+campoesp.value+" é inválida!\nInsira uma data correta!"); 
	campoesp.value=""; 
    campoesp.focus(); 
  } 
} 

// mascara para campo telefone
function mascara_telefone(fone,campo){ 
  var mytelefone = ''; 
  mytelefone = mytelefone + fone; 
  if(mytelefone.length == 2){ 
	 mytelefone = '('+mytelefone + ')'; 
	 campo.value = mytelefone; 
  } 
  if(mytelefone.length == 8){ 
	 mytelefone = mytelefone + '-'; 
	 campo.value = mytelefone; 
  } 
} 

// mascara para cep
function mascara_cep(cep,campo){ 
  var mycep = ''; 
  mycep = mycep + cep; 
  if(mycep.length == 5){ 
	 mycep = mycep + '-'; 
	 campo.value = mycep; 
  } 
}

// verifica CPF/CNPJ
function ver_cpf_cnpj(numcpf,campo){
  //Filtragem da entrada do CPF - Filtra caracteres ""-"" ou ""/"" ou "".""\
  var wcgccalc; var wsoma;
  cleancpf = "";
  tamcpf = numcpf.length;
  for(i = 0; i < tamcpf;i++){
    carac = numcpf.substring(i,i+1);
	if(carac != "1" && carac != "2" && carac != "3" && carac !="4" && carac != "5" && carac != "6" && carac != "7" && carac != "8" && carac!= "9" && carac != "0"){
	  carac = "";
	}
	cleancpf = cleancpf + carac;
  }
  numcpf = cleancpf;
  if(numcpf.length == 11){
	x=0; soma=0; dig1=0; dig2=0; texto=""; numcpf1="";
	len = numcpf.length; x = len -1;
	for(var i=0; i <= len - 3; i++){
	  y = numcpf.substring(i,i+1); soma = soma + ( y * x);
	  x = x - 1; texto = texto + y;
	}
	dig1 = 11 - (soma % 11);
	if(dig1 == 10) dig1=0 ; 
	  if(dig1 == 11) dig1=0 ;
	    numcpf1 = numcpf.substring(0,len - 2) + dig1 ;
	    x = 11; soma=0;
		for(var i=0; i <= len - 2; i++){
		  soma = soma + (numcpf1.substring(i,i+1) * x); 
		  x = x - 1;
		}
		dig2= 11 - (soma % 11);
		if(dig2 == 10) dig2=0;
		if(dig2 == 11) dig2=0;
	    if((dig1 + "" + dig2) == numcpf.substring(len,len-2)){
		return true;
	  } else {
		alert("O cpf que digitou está incorreto");
		campo.focus();
		campo.value="";
		return false;
	  }
	} else {
	  if(numcpf.length == 14){  
		wcgccalc= (numcpf.substring(0,12));
		wsoma=0;
		for(var i=0; i<=3; i++){
		  wnum=parseInt(wcgccalc.substring(i,i+1));
		  wsoma= wsoma + wnum * (5-i);
		}
		for(var x=0; x<=7; x++){
		  wnum=parseInt(wcgccalc.substring(x+4,x+5));
		  wsoma=wsoma + wnum * (9-x);
		}
	    wcgcdigit= 11-(wsoma%11);
		if((wcgcdigit == 10) || (wcgcdigit == 11)){
		  wcgccalc= wcgccalc + '0';
		} else {
		  wcgccalc= wcgccalc + wcgcdigit;
		}	
		wsoma=0;
		for(var y=0; y<=4; y++){
		  wnum=parseInt(wcgccalc.substring(y,y+1));
		  wsoma= wsoma + wnum * (6-y);
		}
		for(var z=0; z<=7; z++){
		  wnum=parseInt(wcgccalc.substring(z+5,z+6));
		  wsoma=wsoma + wnum *(9-z);
		}
		wcgcdigit= 11 - (wsoma%11);
		if((wcgcdigit == 10)||(wcgcdigit == 11)){
	      wcgccalc= wcgccalc + '0';
		} else {
		  wcgccalc= wcgccalc + wcgcdigit;
		}
		if(numcpf==wcgccalc){
		  return true;
		} else {
		  alert("O Cnpj que digitou está incorreto");
		  campo.value="";
		  campo.focus();	
	      return false;
		}
      } else {
		alert("O Cnpj/Cnpj que digitou está incorreto");
		campo.value="";
		campo.focus();
		return false;
	  }
	}
}

// formata valores de moedas, percentuais
function FormataValor2(campo,tammax,casas){
  var vr=document.getElementById(campo).value
  // var vrss=document.getElementById(campo).value	
  while (vr.indexOf(".")>=0) {
	vr=vr.replace(".","");
  }
  while (vr.indexOf(",")>=0) {
	vr=vr.replace(",","");
  }	
  if(isNaN(vr)){
	alert ("Foi Digitado uma Letra. Este campo aceita só numeros com virgula ou ponto");
	document.getElementById(campo).value=vr.substring(0,vr.length-1); 
  } else {
    if(vr.length<tammax){	 	
	  if(vr.length>casas){
		vr=vr.substr(0,vr.length-casas)+","+vr.substr(vr.length-casas,vr.length);
		document.getElementById(campo).value=vr;
	  }
	  vrteste=vr.substr(0,vr.length-casas);
	  numero=vrteste.length;
	  if(numero>0){
		comparador=5;
		var numero=0;
		while (numero<=vrteste.length){
		  if(numero==comparador){
			var anterior=numero-1;
			vrteste=vrteste.substr(0,vrteste.length-anterior)+"."+vrteste.substr(vrteste.length-anterior,vr.length);
			comparador=comparador+4;
		  }
		  numero++;
		}
		vr=vrteste+vr.substr(vr.length-casas,vr.length);
	  }
	  document.getElementById(campo).value=vr.substr(0,tammax);
	}
  }
}

// abre janelas poup-u
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

//saber qual browser é 
String.prototype.contains = function(){
 var resu = false;
 for(var i=0; i < arguments.length; i++){
  if(this.toLowerCase().indexOf(arguments[i].toLowerCase()) > -1){
   resu = i + 1;
   break;
  }
 }
 return resu;
}

var _ua = navigator.userAgent;
var _vd = navigator.vendor;
var _pd = navigator.product;
var _browser_rv = ( _ua.indexOf('rv:') > -1 );
var _browser_op = ( _ua.indexOf('Opera') > -1 );
var _browser_ie = ( _ua.indexOf('MSIE') > -1 );
var _browser_pd = ( _pd == 'Gecko' );
var _browser_ff = ( _vd == 'Firefox' || ( _browser_pd && _ua.contains('Firefox','BonEcho','Paradiso') && ! _ua.contains('Flock')));
var _browser_fk = ( _browser_pd && _ua.contains('Flock') && ! _browser_ff );
var _browser_ns = ( _vd == 'Netscape' );
 
function isMozilla(){ // Mozilla Suite Browser
  return ( _browser_pd && _browser_rv && ! _browser_ff && ! _browser_ns && ! _browser_fk);
}

function isFirefox(){ // Mozilla Firefox
  return ( _browser_pd && ( _browser_ff || ! _browser_rv ) && ! _browser_fk);
}

function isFlock(){
  return ( _browser_pd && _browser_fk);
}

function isNetscape(){ // Netscape 6 or higher
  return( _browser_pd && _browser_ns ) ;
}

function isIE(){ // Internet Explorer
  return( _browser_ie && ! _browser_pd && ! _browser_op);
}

function isOpera(){ // Opera browser
  return( ! _browser_pd && _browser_op);
}

function otherBrowsers(){
  return( !isMozilla() && !isFirefox() && !isFlock() && !isNetscape() && !isIE() && !isOpera());
}

function verificanav(){
  if(isFirefox()){
    document.getElementById('navegador').value="firefox"
  } else {
	document.getElementById('navegador').value="ie"	
  }
}

// validacao do formulario de contato
function cad_contato(frmNome, url, destino){
  var erro="N";
  if(document.getElementById('con_nome').value==""){
	alert("Informe o seu nome.");
	document.getElementById('con_nome').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('con_tel').value==""){
	alert("Informe o seu telefone.");
	document.getElementById('con_tel').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('con_email').value.length < 10 || document.getElementById('con_email').value.indexOf("@") < 0 || document.getElementById('con_email').value.indexOf(".") < 0) {
    alert("Informe um e-mail válido."); 
	document.getElementById('con_email').focus(); 
	pronto="S"; 
	return false;
  }
  if(document.getElementById('con_assunto').value==""){
	alert("Informe o assunto.");
	document.getElementById('con_assunto').focus();
	erro="S";
	return false;
  }																																			
  if(erro=="N"){enviaForm(frmNome, url, destino);}
}

// validacao do formulario de contato
function cad_contatonew(frmNome, url, destino){
  var erro="N";
  if(document.getElementById('cli_nome').value==""){
	alert("Informe o seu nome.");
	document.getElementById('cli_nome').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('cli_email').value.length < 10 || document.getElementById('cli_email').value.indexOf("@") < 0 || document.getElementById('cli_email').value.indexOf(".") < 0) {
    alert("Informe um e-mail válido."); 
	document.getElementById('cli_email').focus(); 
	pronto="S"; 
	return false;
  }
  if(erro=="N"){enviaForm(frmNome, url, destino);}
}

function cad_pesquisa(frmNome, url, destino){
  var erro="N";
  if(document.getElementById('filtr1').value=="Digite uma palavra-chave"){
    alert("Indique uma fonte para pesquisa.");
    document.getElementById('filtr1').focus();
    erro="S";
    return false;
  }
  if(erro=="N"){enviaForm(frmNome, url, destino);}
}

// validacao do formulario de cadastro de Cliente
function cli_cadastrosit(frmNome, url, destino){
  var erro="N";
  if(document.getElementById('cli_nome').value==""){
	alert("Informe a razão social.\n  Campo obrigatório.");
	document.getElementById('cli_nome').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('cli_cpfcnpj').value==""){
	alert("Informe o CNPJ/CPF do responsável.\n              Campo obrigatório.");
	document.getElementById('cli_cpfcnpj').focus();
	erro="S";
	return false;
  }																																			
  if(document.getElementById('cli_cep').value==""){
	alert("     Informe o cep.\nCampo obrigatório.");
	document.getElementById('cli_cep').focus();
	erro="S";
	return false;
  }																																			
  if(document.getElementById('cmbbxn11_1').value==""){
	alert("Escolha a U.F. e a cidade.\n      Campo obrigatório.");
	document.getElementById('cmbbxn11_1').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('cender').value==""){
	alert("Informe o endereço.\n  Campo obrigatório.");
	document.getElementById('cender').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('cli_numero').value==""){
	alert("Informe o número do endereço.\n            Campo obrigatório.");
	document.getElementById('cli_numero').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('cli_tel').value==""){
	alert("Informe o número do telefone.\n          Campo obrigatório.");
	document.getElementById('cli_tel').focus();
	erro="S";
	return false;
  }																																			
  if(document.getElementById('cli_email').value.length < 10 || document.getElementById('cli_email').value.indexOf("@") < 0 || document.getElementById('cli_email').value.indexOf(".") < 0) {
    alert("Informe um e-mail válido."); 
	document.getElementById('cli_email').focus(); 
	pronto="S"; 
	return false;
  }
  if(erro=="N"){enviaForm(frmNome, url, destino);}
}

function cad_depoimento(frmNome, url, destino){
  var erro="N";
  if(document.getElementById('depo_nome').value==""){
    alert("Informe o seu nome.");
    document.getElementById('depo_nome').focus();
    erro="S";
    return false;
  }
  if(document.getElementById('depo_email').value.length < 10 || document.getElementById('depo_email').value.indexOf("@") < 0 || document.getElementById('depo_email').value.indexOf(".") < 0) {
    alert("Informe seu e-mail."); 
    document.getElementById('depo_email').focus(); 
    pronto="S"; 
    return false;
  }
  if(document.getElementById('depo_texto').value==""){
    alert("Informe o assunto.");
    document.getElementById('depo_texto').focus();
    erro="S";
    return false;
  }																																			
  if(erro=="N"){enviaForm(frmNome, url, destino);}
}

function valor_radio( nome ){
	var radios = document.getElementsByName( nome );
	var retorno = "";
	for( var i=0;i<radios.length;i++ ){
		if( radios[ i ].checked ){
			retorno = radios[ i ].value;
		}
	}
	return retorno;
}

// validacao do cadastro de inquilino
function valida_site(frmNome, url, destino){
  var erro="N";
  if(document.getElementById('cender_imo').value==""){
	alert(" Informe o endereço do imóvel.\n        Campo obrigatório.");
	document.getElementById('cender_imo').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('ass_nome').value==""){
	alert(" Informe o seu nome.\n   Campo obrigatório.");
	document.getElementById('ass_nome').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('ass_sexo').value==""){
	alert("   Informe o seu sexo.\n  Campo obrigatório.");
	document.getElementById('ass_sexo').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('ass_cpfcnpj').value==""){
	alert("   Informe o seu CPF/CNPJ.\n       Campo obrigatório.");
	document.getElementById('ass_cpfcnpj').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('ass_rg').value==""){
	alert("   Informe o seu RG/I.E.\n    Campo obrigatório.");
	document.getElementById('ass_rg').focus();
	erro="S";
	return false;
  }  
  if(document.getElementById('ass_orgao').value==""){
	alert(" Informe o orgão emissor.\n     Campo obrigatório.");
	document.getElementById('ass_orgao').focus();
	erro="S";
	return false;
  }  
  if(document.getElementById('ass_nomemae').value==""){
	alert("Informe o nome da mãe.\n     Campo obrigatório.");
	document.getElementById('ass_nomemae').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('ass_tel').value==""){
	alert("Informe o número do telefone.\n          Campo obrigatório.");
	document.getElementById('ass_tel').focus();
	erro="S";
	return false;
  }																																			
  if(document.getElementById('ass_email').value.length < 10 || document.getElementById('ass_email').value.indexOf("@") < 0 || document.getElementById('ass_email').value.indexOf(".") < 0) {
	alert("  Informe seu e-mail\n Campo obrigatório."); 
	document.getElementById('ass_email').focus(); 
	pronto="S"; 
	return false;
  }
  if(document.getElementById('ass_estcivil').value==""){
	alert("Informe o estado civil.\n  Campo obrigatório.");
	erro="S";
	return false;
  }																																			
  if(document.getElementById('ass_rendimento').value==""){
	alert("Informe sua renda familiar.\n       Campo obrigatório.");
	document.getElementById('ass_rendimento').focus();
	erro="S";
	return false;
  }

    var ass_tipo=valor_radio( 'ass_tipo' );
    if(ass_tipo==""){
	alert("Marque o tipo de moradia atual.\n           Campo obrigatório.");
	erro="S";
	return false;
    } else if(ass_tipo=="S"){
	if(document.getElementById('ass_aluguel').value==""){
	  alert("Informe o valor do aluguel.\n       Campo obrigatório.");
	  document.getElementById('ass_aluguel').focus();
	  erro="S";
	  return false;
	}
    }

    var ass_prof=valor_radio( 'ass_prof' );
    if(ass_prof==""){
	alert("Marque sua profissão.\n  Campo obrigatório.");
	erro="S";
	return false;
    } else if(ass_prof=="1"){
	if(document.getElementById('ass_dtadmissao').value==""){
	  alert("Informe mês/ano de admissão.\n        Campo obrigatório.");
	  document.getElementById('ass_dtadmissao').focus();
	  erro="S";
	  return false;
	}
    }

    var ass_bens=valor_radio( 'ass_bens' );
    if(ass_bens==""){
	alert("Marque se possui bens.\n  Campo obrigatório.");
	erro="S";
	return false;
    }

    var ass_vei=valor_radio( 'ass_vei' );
    var ass_onusv=valor_radio( 'ass_onusv' );
    var ass_onusi=valor_radio( 'ass_onusi' );
    var ass_bens=valor_radio( 'ass_bens' );

    if(ass_bens=="S"){
	if(ass_vei==""){
	    alert("Marque se é automovel ou imóvel.\n             Campo obrigatório.");
	    erro="S";
	    return false;		
	} else {
	  if(ass_vei=="V"){
	    if(ass_onusv==""){		
	      alert("Marque se é quitado ou financiado o automóvel.\n                      Campo obrigatório.");
	      erro="S";
	      return false;
	    } else if(ass_onusv=="2"){
	      if(document.getElementById('ass_valoronus1').value==""){
		 alert("Informe o valor da parcela do automóvel.\n                Campo obrigatório.");
		 document.getElementById('ass_valoronus1').focus();
		 erro="S";
		 return false;
	      }
	    }
	  } else if(ass_vei=="I"){
	    if(ass_onusi==""){		
	      alert("Marque se é quitado ou financiado o imóvel.\n                   Campo obrigatório.");
	      erro="S";
	      return false;
	    } else if(ass_onusi=="2"){
	      if(document.getElementById('ass_valoronus2').value==""){
		 alert("Informe o valor da parcela do imóvel.\n             Campo obrigatório.");
		 document.getElementById('ass_valoronus2').focus();
		 erro="S";
		 return false;
	      }
	    }
	  }
	}
    }

    var ass_motivolocacao=valor_radio( 'ass_motivolocacao' );
    if(ass_motivolocacao==""){
	alert("Marque um motivo de locação.\n         Campo obrigatório.");
	erro="S";
	return false;
    } else if(ass_motivolocacao=="00"){
	if(document.getElementById('ass_outromotivo').value==""){
	   alert("Informe o motivo da locação.\n        Campo obrigatório.");
	   document.getElementById('ass_outromotivo').focus();
	   erro="S";
	   return false;
	}
    }
  if(erro=="N"){enviaForm(frmNome, url, destino);}
}




