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 do usuário.");
    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;
}

function carrossel(){
	$('#barousel_thslide').barousel({
		navWrapper: '#thslide_barousel_nav .thslide_list',
		manualCarousel: 1,
		navType: 3
	});
	$('#thslide_barousel_nav').thslide({
		itemOffset: 283 //93 é para 6 imagens ou seja 15.5 para cada imagem 
	});
}

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 );
		}
	} );
}


// 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();
}

function amplia(){
  document.getElementById('fotoZoom').style.display='block';
  document.getElementById('bgFotoZoom').style.display='block';
}

//Esta função mostra as informações que estarão dentro da div>>
//obs.: o script a seguir dentro de innerHTML="" é onde mostrará o conteúdo dentro da div,
//deve ser escrito na mesma linha sem quebra de linha entre os dados html dentro deste script
function abre(img,legenda,credito,largura,altura) {
  document.getElementById("fotoZoom").innerHTML="<center><table bgcolor='white' cellspadding='1' cellspacing='1' width='100%'><tr><td align=center><strong><font size=2 face=Verdana class=style2>"+legenda+"</strong></td></tr><tr><td><a href='javascript:fecha();'><img alt='"+legenda+"' src='"+img+"' width='"+largura+"' height='"+altura+"'></a></td></tr><tr><td align=right><strong><font size=2 face=Verdana class=style2>"+credito+"</strong>&nbsp;</font></td></tr></table>";
}

//Esta executa o script fecha, para fechar a div que foi aberta anteriormente

function fecha() {
  document.getElementById('fotoZoom').style.display='none';  
  document.getElementById('bgFotoZoom').style.display='none';
}

//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 calcular_idade( data ){
    data = data.replace( "-", "/" ).replace( "-", "/" );
    data = data.split( "/" );
    var hje = new Date();
    var dia = parseInt( data[ 0 ] );
    var mes = parseInt( data[ 1 ] );
    var ano = parseInt( data[ 2 ] );
    var idd = 0;

    if( isNaN( dia ) || isNaN( mes ) || isNaN( ano ) ){
        alert( "Data inválida!" );
    }
    else{
        idd = hje.getFullYear()-ano;

        if( ( ( hje.getMonth()+1 )-mes )<=0 ){
             if( ( ( hje.getMonth()+1 )-mes )==0 ){
                 if( hje.getDate()<dia ){
                     idd--;
                 }
             }
             else{
                 idd--;
             }
        }
    }

    return idd;
}

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><font color='black' size='2'>aguarde...</font>";
  } 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;
    }*/
  } 
}

Number.prototype.formatMoney = function( c, d, t ){ //Serve para formatar um number em formato dinheiro 
  var n = this;
  c = isNaN( c = Math.abs( c ) )?2:c;
  d = ( d==undefined )?",":d;
  t = ( t==undefined )?".":t;
  var i = parseInt( n = ( +n || 0 ).toFixed( c ) )+"";
  var j = ( ( j=i.length )>3 )?j%3:0;
  return ( ( j )?i.substr( 0, j )+t:"" )+i.substr( j ).replace( /(\d{3})(?=\d)/g, "$1"+t )+( ( c )?d+( n-i ).toFixed( c ).slice( 2 ):"" );
};

function busca_cidades( cod_uf, id_cidades, cid_cod ){
  $.ajax( {
    url: "../include/busca_cidades.php?cod_uf="+cod_uf,
    type: "get",
    success: function( response ){
      eval( "var cidades = "+response );

      var html = "";
      for( var i=0;i<cidades.length;i++ ){
        html += "<option value='"+cidades[ i ][ "cid_cod" ]+"'>"+cidades[ i ][ "cidade" ]+"</option>";
      }

      $( "#"+id_cidades ).html( html );

      if( cid_cod!=undefined ){
        for( var i=0;i<cidades.length;i++ ){
          if( parseInt( cid_cod )==parseInt( cidades[ i ][ "cid_cod" ] ) ){
            $( "#"+id_cidades )[ 0 ].selectedIndex = i;
          }
        }
      }
    }
  } );
}

function busca_cpf(){
  var cli_cpfcnpj = $( "#cli_cpfcnpj" ).val();
  var tipo_seg = $( "#tipo_seg" ).val();  
  if( cli_cpfcnpj!="" && ver_cpf_cnpj( cli_cpfcnpj, $( "#cli_cpfcnpj" )[ 0 ] ) ){    
    $.ajax( {
      url: "index_buscabase.php",
      type: "post",
      data: "busca=000&id_pro="+$( "#id_pro" ).val()+"&cli_cpfcnpj="+cli_cpfcnpj+"&tipo_seg="+tipo_seg,
      success: function( response ){
        eval( "var cliente="+response );
        if( cliente[ "cli_nome" ]!=null ){
          if( cliente[ "cli_pg" ]=="S" ){ $( "#cli_pg1" )[ 0 ].checked = true; }else{ $( "#cli_pg2" )[ 0 ].checked = true; }
          $( "#cli_nome" ).val( cliente[ "cli_nome" ] );
          $( "#cli_sexo" )[ 0 ].selectedIndex = ( cliente[ "cli_sexo" ]=="M" )?1:2;
          $( "#cli_rg" ).val( cliente[ "cli_rg" ] );
          var data = cliente[ "cli_dtexpedicao" ].split( "-" );
          $( "#cli_dtexpedicao" ).val( data[ 2 ]+"-"+data[ 1 ]+"-"+data[ 0 ] );
          $( "#cli_orgao" ).val( cliente[ "cli_orgao" ] );
          var data = cliente[ "cli_dtnascimento" ].split( "-" );
          $( "#cli_dtnascimento" ).val( data[ 2 ]+"-"+data[ 1 ]+"-"+data[ 0 ] );
          for( var i=0;i<$( "#cod_pais" )[ 0 ].options.length;i++ ){
            if( $( "#cod_pais" )[ 0 ].options[ i ].value==cliente[ "cod_pais" ] ){
              $( "#cod_pais" )[ 0 ].selectedIndex = i;
            }
          }
          $( "#cli_cep" ).val( cliente[ "cli_cep" ] );
          for( var i=0;i<$( "#cod_uf" )[ 0 ].options.length;i++ ){
            if( $( "#cod_uf" )[ 0 ].options[ i ].value==cliente[ "cod_uf" ] ){
              $( "#cod_uf" )[ 0 ].selectedIndex = i;
            }
          }
          $( "#cid_cod" ).val( cliente[ "cid_cod" ] );         
          $( "#cidades" ).html( "<option value='"+cliente[ "cid_cod" ]+"'>"+cliente[ "cidades" ]+"</option>" );
          $( "#cender" ).val( cliente[ "cender" ] );
          $( "#cli_numero" ).val( cliente[ "cli_numero" ] );
          $( "#cli_complemento" ).val( cliente[ "cli_complemento" ] );
          $( "#cbairr" ).val( cliente[ "cbairr" ] );
          $( "#cli_tel" ).val( cliente[ "cli_tel" ] );
          $( "#cli_cel" ).val( cliente[ "cli_cel" ] );
          for( var i=0;i<$( "#cli_opera" )[ 0 ].options.length;i++ ){
            if( $( "#cli_opera" )[ 0 ].options[ i ].value==cliente[ "cli_opera" ] ){
              $( "#cli_opera" )[ 0 ].selectedIndex = i;
            }
          }
          $( "#cli_email" ).val( cliente[ "cli_email" ] );
          $( "#cli_mae" ).val( cliente[ "cli_mae" ] );
          $( "#cli_bonus" ).val( cliente[ "cli_bonus" ] );
          $( "#tipo_seg" ).val( cliente[ "tipo_seg" ] );
          var totped = parseFloat( $( "#totped" ).val().replace( ",", "." ) );
          $( "#totped" ).val( ( totped-cliente[ "cli_bonus" ] ).formatMoney() );
          if( calcular_idade( $( "#cli_dtnascimento" ).val() )>=cliente[ "pro_idade" ] ){
              alert( "Este produto está fora de sua faixa etária para aquisição." );
              $( "#btcomprar" )[ 0 ].disabled = true;
          }
        }
      }
    } );
  }
}

function busca_idade_produto(){
  $.ajax( {
    url: "index_buscabase.php",
    type: "post",
    data: "busca=003&id_pro="+$( "#id_pro" ).val(),
    success: function( response ){
      eval( "var pro_idade="+response );
      if( calcular_idade( $( "#cli_dtnascimento" ).val() )>=pro_idade[ "pro_idade" ] ){
          alert( "Este produto está fora de sua faixa etária para aquisição." );
          $( "#btcomprar" )[ 0 ].disabled = true;
      }
    }
  } );
}

function busca_dataviagemini(){
  var cli_viagemini = $( "#cli_viagemini" ).val();
  var tipo_seg = $( "#tipo_seg" ).val();
  if( cli_viagemini!="" ){
    $.ajax( {
      url: "index_buscabase.php",
      type: "post",
      data: "busca=004&id_pro="+$( "#id_pro" ).val()+"&cli_viagemini="+cli_viagemini,
      success: function( response ){
	eval( "var viagemi="+response );
	$( "#viagemini" ).val( viagemi[ "viagemini" ] );
	if( viagemi["viagemini"]!="SIM"){
	    alert( "A data inicial está fora do período de viagem." );
            $( "#cli_viagemini" ).val("");
	}
      }
    } );
  }
}

function busca_dataviagemfim(){
  var cli_viagemfim = $( "#cli_viagemfim" ).val();
  var tipo_seg = $( "#tipo_seg" ).val();
  if( cli_viagemfim!="" ){        
    $.ajax( {
      url: "index_buscabase.php",
      type: "post",
      data: "busca=005&id_pro="+$( "#id_pro" ).val()+"&cli_viagemfim="+cli_viagemfim,
      success: function( response ){
	eval( "var viagemf="+response );
	$( "#viagemfim" ).val( viagemf[ "viagemfim" ] );
	if( viagemf["viagemfim"]!="SIM"){
	    alert( "A data final está fora do período de viagem." );
            $( "#cli_viagemfim" ).val("");
	}
      }
    } );
  }
}


function busca_cpfbon(){
  var cli_cpfcnpj = $( "#cli_cpfcnpj" ).val();
  if( cli_cpfcnpj!="" && ver_cpf_cnpj( cli_cpfcnpj, $( "#cli_cpfcnpj" )[ 0 ] ) ){
    $.ajax( {
      url: "index_buscabase.php",
      type: "post",
      data: "busca=002&cli_cpfcnpj="+cli_cpfcnpj,
      success: function( response ){
        eval( "var cliente="+response );
        if( cliente[ "cli_nome" ]!=null ){
          $( "#cli_cli_codigo" ).val( cliente[ "cli_codigo" ] );
          if( cliente[ "cli_pg" ]=="S" ){ $( "#cli_pg1" )[ 0 ].checked = true; }else{ $( "#cli_pg2" )[ 0 ].checked = true; }
          $( "#cli_nome" ).val( cliente[ "cli_nome" ] );
          $( "#cli_sexo" )[ 0 ].selectedIndex = ( cliente[ "cli_sexo" ]=="M" )?1:2;
          $( "#cli_rg" ).val( cliente[ "cli_rg" ] );
          var data = cliente[ "cli_dtexpedicao" ].split( "-" );
          $( "#cli_dtexpedicao" ).val( data[ 2 ]+"-"+data[ 1 ]+"-"+data[ 0 ] );
          $( "#cli_orgao" ).val( cliente[ "cli_orgao" ] );
          var data = cliente[ "cli_dtnascimento" ].split( "-" );
          $( "#cli_dtnascimento" ).val( data[ 2 ]+"-"+data[ 1 ]+"-"+data[ 0 ] );

          for( var i=0;i<$( "#cod_pais" )[ 0 ].options.length;i++ ){
            if( $( "#cod_pais" )[ 0 ].options[ i ].value==cliente[ "cod_pais" ] ){
              $( "#cod_pais" )[ 0 ].selectedIndex = i;
            }
          }

          $( "#cli_cep" ).val( cliente[ "cli_cep" ] );

          for( var i=0;i<$( "#cod_uf" )[ 0 ].options.length;i++ ){
            if( $( "#cod_uf" )[ 0 ].options[ i ].value==cliente[ "cod_uf" ] ){
              $( "#cod_uf" )[ 0 ].selectedIndex = i;
            }
          }

          $( "#cidades" ).val( cliente[ "cid_cod" ] );         

          $( "#cidades" ).html( "<option value='"+cliente[ "cid_cod" ]+"'>"+cliente[ "cidades" ]+"</option>" );
          $( "#cender" ).val( cliente[ "cender" ] );
          $( "#cli_numero" ).val( cliente[ "cli_numero" ] );
          $( "#cli_complemento" ).val( cliente[ "cli_complemento" ] );
          $( "#cbairr" ).val( cliente[ "cbairr" ] );
          $( "#cli_tel" ).val( cliente[ "cli_tel" ] );
          $( "#cli_cel" ).val( cliente[ "cli_cel" ] );
          for( var i=0;i<$( "#cli_opera" )[ 0 ].options.length;i++ ){
            if( $( "#cli_opera" )[ 0 ].options[ i ].value==cliente[ "cli_opera" ] ){
              $( "#cli_opera" )[ 0 ].selectedIndex = i;
            }
          }
          $( "#cli_email" ).val( cliente[ "cli_email" ] );
          $( "#cli_mae" ).val( cliente[ "cli_mae" ] );
          $( "#id_rel" ).val( cliente[ "id_rel" ] );
          if( cliente[ "id_rel" ]==null ){
            alert("Confirme seu Cadastro para ganhar o Bonus.");
	  } else {
            alert("Você já tem Bonus desta promoção. \n\           Só pode indicar amigos.");
	    enviagenerico("cli_codigo="+cliente[ "cli_codigo" ]+"&cli_email="+cliente[ "cli_email" ],'index_amigo.php','POST','conteudo');	 
	  }
        }
      }
    } );
  }
}


function busca_email(){
  var cli_emaili = $( "#cli_emaili" ).val();
  if( cli_emaili!="" ){
    $.ajax( {
      url: "index_buscabase.php",
      type: "post",
      data: "busca=001&cli_emaili="+cli_emaili,
      success: function( response ){
        eval( "var clientess="+response );
        if( clientess[ "cli_cpfcnpj" ]!=null ){	  
          $( "#cli_codigoi" ).val( clientess[ "cli_codigoi" ] );
          $( "#cli_cpfcnpj" ).val( clientess[ "cli_cpfcnpj" ] );
        } else {
         alert("Para indicar amigos você tem que se cadastrar.");
	 enviagenerico('&','index_bonus.php','POST','conteudo');	 
	}
    }  
    } );
  }
}

function busca_emailami(){
  var cli_emaili = $( "#cli_emaili" ).val();
  if( cli_emaili!="" ){
    $.ajax( {
      url: "index_buscabase.php",
      type: "post",
      data: "busca=001&cli_emaili="+cli_emaili,
      success: function( response ){
        eval( "var clientess="+response );
        if( clientess[ "cli_cpfcnpj" ]!=null ){	  
          $( "#cli_codigoi" ).val( clientess[ "cli_codigoi" ] );
          $( "#cli_cpfcnpj" ).val( clientess[ "cli_cpfcnpj" ] );
        } else {
         alert("Para indicar amigos você tem que se cadastrar.");
	 enviagenerico('&','index_bonus.php','POST','conteudo');	 
	}
    }  
    } );
  }
}

function buscaPorCEP(url){
	$.ajax( {
		url: url,
		type: "POST",
		data: "cli_cep="+$( "#cli_cep" ).val(),
		success: function( response ){
			eval( "var dadosCEP="+response );
			for( var i=0;i<$( "#cod_uf" )[ 0 ].options.length;i++ ){
				if( $( "#cod_uf" )[ 0 ].options[ i ].value==dadosCEP[ "uf" ].toUpperCase() ){
					$( "#cod_uf" )[ 0 ].options[ i ].selected = true;
				}
			}
			
			busca_cidades( $( "#cod_uf" ).val(), 'cidades', dadosCEP[ "cidade_cod" ] )
			
			$( "#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('id_adm').value==""){
	alert("Selecione a empresa.\n  Campo obrigatório." );
	document.getElementById('id_adm').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('con_nome').value==""){
	alert("Informe o seu nome.\nCampo obrigatório.");
	document.getElementById('con_nome').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('con_tel').value==""){
	alert("Informe o seu telefone.\n   Campo obrigatório.");
	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.\n      Campo obrigatório."); 
	document.getElementById('con_email').focus(); 
	pronto="S"; 
	return false;
  }
  if(document.getElementById('con_assunto').value==""){
	alert("Informe o assunto.\nCampo obrigatório.");
	document.getElementById('con_assunto').focus();
	erro="S";
	return false;
  }																																			
  if(erro=="N"){enviaForm(frmNome, url, destino);}
}

// validacao do formulario de depoimento
function cad_contdepo(frmNome, url, destino){
  var erro="N";
  if(document.getElementById('cond_nome').value==""){
	alert("Informe o seu nome.\nCampo obrigatório.");
	document.getElementById('cond_nome').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('cond_email').value.length < 10 || document.getElementById('cond_email').value.indexOf("@") < 0 || document.getElementById('cond_email').value.indexOf(".") < 0) {
    alert("Informe um e-mail válido.\n      Campo obrigatório."); 
	document.getElementById('cond_email').focus(); 
	pronto="S"; 
	return false;
  }
  if(document.getElementById('cond_assunto').value==""){
	alert("Informe o assunto.\nCampo obrigatório.");
	document.getElementById('cond_assunto').focus();
	erro="S";
	return false;
  }																																			
  if(erro=="N"){enviaForm(frmNome, url, destino);}
}

// validacao do formulario de depoimento
function cad_contnews(frmNome, url, destino){
  var erro="N";
  if(document.getElementById('col_nome').value==""){
	alert("Informe o seu nome.\nCampo obrigatório.");
	document.getElementById('col_nome').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('col_email').value.length < 10 || document.getElementById('col_email').value.indexOf("@") < 0 || document.getElementById('col_email').value.indexOf(".") < 0) {
    alert("Informe um e-mail válido.\n      Campo obrigatório."); 
	document.getElementById('col_email').focus(); 
	pronto="S"; 
	return false;
  }
  if(erro=="N"){enviaForm(frmNome, url, destino);}
}

// validacao do formulario de cadastro de Compras
function cad_compra(frmNome, url, destino){
  var erro="N";
  if(document.getElementById('cli_cpfcnpj').value==""){
	alert("Informe o seu CPF/CNPJ.\n     Campo obrigatório." );
	document.getElementById('cli_cpfcnpj').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('cli_nome').value==""){
	alert("Informe o seu nome.\n Campo obrigatório.");
	document.getElementById('cli_nome').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('cli_sexo').value==""){
	alert(" Informe o seu sexo.\nCampo obrigatório.");
	document.getElementById('cli_sexo').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('cli_rg').value==""){
	alert("Informe o seu RG/IE.\n Campo obrigatório.");
	document.getElementById('cli_rg').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('cli_dtexpedicao').value==""){
	alert("Informe data de expedição.\n       Campo obrigatório.");
	document.getElementById('cli_dtexpedicao').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('cli_orgao').value==""){
	alert("Informe o orgão emissor.\n     Campo obrigatório.");
	document.getElementById('cli_orgao').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('cli_dtnascimento').value==""){
	alert("Informe data de nascimento.\n        Campo obrigatório.");
	document.getElementById('cli_dtnascimento').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('cli_cep').value==""){
	alert("Informe o seu CEP.\nCampo obrigatório.");
	document.getElementById('cli_cep').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('cidades').value==""){
	alert("Escolha a U.F. e a cidade.\n      Campo obrigatório.");
	document.getElementById('cidades').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.\n Campo obrigatório.");
	document.getElementById('cli_numero').focus();
	erro="S";
	return false;
  }																																			
  if(document.getElementById('cbairr').value==""){
	alert("Informe o seu bairro.\n Campo obrigatório.");
	document.getElementById('bairr').focus();
	erro="S";
	return false;
  }																																			
  if(document.getElementById('cli_tel').value==""){
	alert("Informe o seu 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.\n      Campo obrigatório."); 
	document.getElementById('cli_email').focus(); 
	pronto="S"; 
	return false;
  }
  if(document.getElementById('cli_mae').value==""){
	alert("Informe o nome de sua mãe.\n        Campo obrigatório.");
	document.getElementById('cli_mae').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('tipo_seg').value=="V"){
    if(document.getElementById('cli_localviagem').value==""){    
	alert("Informe o local de sua viagem.\n          Campo obrigatório.");
	document.getElementById('cli_localviagem').focus();
	erro="S";
	return false;
    }
    if(document.getElementById('cli_viagemini').value==""){    
	alert("Informe a data inicial de sua viagem.\n               Campo obrigatório.");
	document.getElementById('cli_viagemini').focus();
	erro="S";
	return false;
    }
    if(document.getElementById('cli_viagemfim').value==""){    
	alert("Informe a data final de sua viagem.\n               Campo obrigatório.");
	document.getElementById('cli_viagemfim').focus();
	erro="S";
	return false;
    }
  }  
  if(erro=="N"){enviaForm(frmNome, url, destino);}
}

// validacao do dados de esqueci minha senha
function env_sen(frmNome, url, destino){
  var erro="N";
  if(document.getElementById('usus_email').value.length < 10 || document.getElementById('usus_email').value.indexOf("@") < 0 || document.getElementById('usus_email').value.indexOf(".") < 0) {
    alert("Informe um E-mail valido.\n       Campo obrigatório.");
    document.getElementById('usus_email').focus();
    erro="S";
    return false;
  }
  if(erro=="N"){enviaForm(frmNome, url, destino);}
}

// validacao do dados de esqueci minha senha
function cad_amigo(frmNome, url, destino){
  var erro="N";
  if(document.getElementById('cli_emaili').value==""){
	alert("É obrigatório informar o e-mail do indicador.");
	document.getElementById('cli_emaili').focus();
	erro="S";
	return false;
  }
  if(document.getElementById('cli_email1').value=="" && document.getElementById('cli_email2').value=="" && document.getElementById('cli_email3').value=="" && document.getElementById('cli_email4').value=="" && document.getElementById('cli_email5').value==""){
        alert("Você tem que indicar pelo menos um amigo.");
	erro="S";
	return false;
  } else {
    if(document.getElementById('cli_email1').value!=""){
      if(document.getElementById('cli_email1').value.length < 10 || document.getElementById('cli_email1').value.indexOf("@") < 0 || document.getElementById('cli_email1').value.indexOf(".") < 0) {
        alert("Informe um E-mail valido para o amigo 1");
        document.getElementById('cli_email1').focus();
        erro="S";
        return false;
      }
    }
    if(document.getElementById('cli_email2').value!=""){
      if(document.getElementById('cli_email2').value.length < 10 || document.getElementById('cli_email2').value.indexOf("@") < 0 || document.getElementById('cli_email2').value.indexOf(".") < 0) {
        alert("Informe um E-mail valido para o amigo 2");
        document.getElementById('cli_email2').focus();
        erro="S";
        return false;
      }
    }
    if(document.getElementById('cli_email3').value!=""){
      if(document.getElementById('cli_email3').value.length < 10 || document.getElementById('cli_email3').value.indexOf("@") < 0 || document.getElementById('cli_email3').value.indexOf(".") < 0) {
        alert("Informe um E-mail valido para o amigo 3");
        document.getElementById('cli_email3').focus();
        erro="S";
        return false;
      }
    }
    if(document.getElementById('cli_email4').value!=""){
      if(document.getElementById('cli_email4').value.length < 10 || document.getElementById('cli_email4').value.indexOf("@") < 0 || document.getElementById('cli_email4').value.indexOf(".") < 0) {
        alert("Informe um E-mail valido para o amigo 4");
        document.getElementById('cli_email4').focus();
        erro="S";
        return false;
      }
    }
    if(document.getElementById('cli_email5').value!=""){
      if(document.getElementById('cli_email5').value.length < 10 || document.getElementById('cli_email5').value.indexOf("@") < 0 || document.getElementById('cli_email5').value.indexOf(".") < 0) {
        alert("Informe um E-mail valido para o amigo 5");
        document.getElementById('cli_email5').focus();
        erro="S";
        return false;
      }
    }
  }
  if(erro=="N"){enviaForm(frmNome, url, destino);}
}

