<!--//
var NomeBrowser  = navigator.appName;
var VersBrowser  = navigator.appVersion;
var child = null;

function openWin(popup_url,name,width,height) {
   var size = ',width=' + width + ',height=' + height;
   var posicion = ",left="+Math.round(screen.availWidth/3)+",top="+Math.round(screen.availHeight/3);
   var popUp=window.open(popup_url,name,'resizable=no,menubar=no,location=no,toolbar=no,status=no,scrollbars=no,directories=no,'+size+posicion);
   popUp.opener=self;
}

function keep_on_top() {
   if (child != null)
      if (child.closed)
         child = null;
      else
         child.focus();
}

function CreateButton(Valor,Nome,Form) {
   document.write("<table id='" + Nome + "' border='0' width='" + (Valor.length + 80) + "' cellspacing='0' cellpadding='0' class='Botao' height='20'>");
   document.write("  <tr>");
   document.write("    <td width='100%' align='center' height='20' onMouseOver='Over("+Nome+",\"None\")' onMouseOut='Out("+Nome+",\"None\")' onClick=\"" + Form + "\">"+Valor+"</td>");
   document.write("  </tr>");
   document.write("</table>");
}

function Over(Obj,Cor) {
   if (Cor=='None') {
      Cor = "#0033CC";
   }
   Obj.style.backgroundColor = Cor;
}

function Out(Obj,Cor) {
   if (Cor=='None') {
      Cor = "#0066FF";
   }
   Obj.style.backgroundColor = Cor;
}

function findserv() {	
  child = open("servico.php","findserv","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=600,height=200,left=100,top=200");
}

function abre_cac() {
   iLeft = (screen.availWidth - 679) / 2;
   iTop = (screen.availHeight - 342) / 2;	
   child = open("cac.php","cac","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=679,height=342,left=" + iLeft + ",top=" + iTop);	
}


function abre() {
   document.location.href = "./php/login.php";
}

function abre_pesq() {
   iLeft = (screen.availWidth - 579) / 2;
   iTop = (screen.availHeight - 142) / 2;
   child = open("pesquisa.php","pesq","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=579,height=142,left=" + iLeft + ",top=" + iTop);
}

function Lancamento(opcao, modo, mesano, item, tipo, altura, posicao) { 
   iLeft = (screen.availWidth - 309) / 2;
   iTop = (screen.availHeight - 509) / 2;
   
   if (mesano == "0") {
      alert("Entre com o valor Mês/Ano e clique em Buscar, antes de Inserir um lançamento.");
      return;	
   }
   
   var link = "lancamento.php?opcao=" + opcao + "&modo=" + modo + "&mesano=" + mesano + "&item=" + item + "&tipo=" + tipo;
   window.open(link, "Lancamento", "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizeable=0,width=309,height=509,left=" + iLeft + ",top=" + iTop);
}
//
function Lancamento1(opcao, modo, mesano, item, tipo, altura, posicao) {
   iLeft = (screen.availWidth - 309) / 2;
   iTop = (screen.availHeight - altura) / 2;

   if (mesano == "0") {
      alert("Entre com o valor Mês/Ano e clique em Buscar, antes de Inserir um lançamento.");
      return;
   }

  var link = "lancamentos.php?opcao=" + opcao + "&modo=" + modo + "&mesano=" + mesano + "&item=" + item + "&tipo =" + tipo;
   window.open(link, "Lancamento", "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizeable=0,width=309,height=" + altura + ",left=" + iLeft + ",top=" + iTop);
}

//
function Lancamento2(opcao, modo, mesano, item, tipo, altura, posicao) {
   iLeft = (screen.availWidth - 309) / 2;
   iTop = (screen.availHeight - 509) / 2;

   if (mesano == "0") {
      alert("Entre com o valor Mês/Ano e clique em Buscar, antes de Inserir um lançamento.");
      return;
   }

  var link = "lancamentor.php?opcao=" + opcao + "&modo=" + modo + "&mesano=" + mesano + "&item=" + item + "&tipo=" + tipo;
  window.open(link, "Lancamento", "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizeable=0,width=309,height=509,left=" + iLeft + ",top=" + iTop);
}

//
function Lancamento3(opcao, modo, mesano, item, tipo, altura, posicao) {
   iLeft = (screen.availWidth - 309) / 2;
   iTop = (screen.availHeight - 509) / 2;

   if (mesano == "0") {
       alert("Entre com o valor Mês/Ano e clique em Buscar, antes de Inserir um lançamento.");
       return;
   }

   var link = "lancamentot.php?opcao=" + opcao + "&modo=" + modo + "&mesano=" + mesano + "&item=" + item + "&tipo=" + tipo;
   window.open(link, "Lancamento", "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizeable=0,width=309,height=509,left=" + iLeft + ",top=" + iTop);
}


//


function criar_masc(field) {

   if (field.name.substring(0,4) == 'cnpj') {
      /*if (field.value.length == 2 || field.value.length == 6) {
         field.value = field.value + '.';
      }
      if (field.value.length == 10) {
         field.value = field.value + '/';
      }
      if (field.value.length == 15) {
         field.value = field.value + '-';
      }*/
      return;
   }
  
   if (field.name.substring(0,9) == 'inscricao') {
      if (field.value.length == 3 || 
          field.value.length == 7 || 
          field.value.length == 11) {
         field.value = field.value + '.';
      }
      return;
   }

   if (field.name.substring(0,2) == 'rg') {
      if (field.value.length == 2 || field.value.length == 6) {
         field.value = field.value + '.';
      }
      if (field.value.length == 10) {
         field.value = field.value + '-';
      }
      return;
   }

   if (field.name.substring(0,3) == 'cep') {
      // 13.203-490
      if (field.value.length == 2) {
         field.value = field.value + '.';
      }
      if (field.value.length == 6) {
         field.value = field.value + '-';
      }
      return;
   }

   if (field.name.substring(0,8) == 'telefone') {
      if (field.value.length == 2) {
         field.value = field.value + ' ';
      }
      if (field.value.length == 7) {
         field.value = field.value + '-';
      }
      return;
   }
   
   if (field.name == 'dtemissao') {
      // 30/06/2003
      if (field.value.length == 2) {
         field.value = field.value + '/';
      }
      if (field.value.length == 5) {
         field.value = field.value + '/';	
      }
   }

   if (field.name.substring(0,4) == 'data') {
      if (field.value.length == 4) {
         field.value = field.value + '-';
      }
      if (field.value.length == 9) {
         field.value = field.value + ' ';
      }
      if (field.value.length == 12 || field.value.length == 15) {
         field.value = field.value + ':';
      }
      return;
   }

   if (field.name.substring(0,6) == 'mesano') {
      if (field.value.length == 2) {
         field.value = field.value + "/";
      }
      return;
   }
   
   if (field.name.indexOf("hora")) {
      if (field.value.length == 2 || field.value.length == 5) {
         field.value = field.value + ':';
      }
      return;
   }
   
}

function processa_form(form) {
   alert('entrou');
   if (processa_valid(form)) {
      for (j=0; j<(form.elements.length); j++) {
         inds = form.elements[j].name.indexOf("quantidade_tray");
         indv = form.elements[j].name.indexOf("sel");
         indx = form.elements[j].name.indexOf("_required");
         indy = form.elements[j].name.indexOf("email");
         inda = form.elements[j].name.indexOf("issdevido");
         indb = form.elements[j].name.indexOf("cnpjtomador");
         indc = form.elements[j].name.indexOf("issretido");
         
         if (inda != -1) {
            if (form.elements[j].value <= 0) {
               mensagem("O Campo ISS DEVIDO não pode ser Zero.");
               return false;
            }         	
         }
         
         if (indc != -1) {
            if (form.elements[j].value <= 0) {
               mensagem("O Campo ISS RETIDO não pode ser Zero.");
               return false;
            }             	
         }
         
         if (indb != -1) {
               if (form.elements[j].value.length == 0) {
                  fieldname = form.elements[j].name.toUpperCase();
                  fieldname = fieldname.replace(/\_/g,' '); 
                  mensagem("É necessário preencher o campo "+fieldname.substring(0,indb)+" !");
                  form.elements[j].focus();
                  form.elements[j].blur();
                  form.elements[j].select();
                  return false;
            }      	
         }

         if (indx != -1) {
            if (form.elements[j].value.length == 0) {
               if (indv != -1) {
                  mensagem("É necessário efetuar pelo menos 1 (uma) seleção");
               } else {
                  fieldname = form.elements[j].name.toUpperCase();
                  fieldname = fieldname.replace(/\_/g,' '); 
                  mensagem("É necessário preencher o campo "+fieldname.substring(0,indx)+" !");
                  form.elements[j].focus();
                  form.elements[j].blur();
                  form.elements[j].select();
               }
               return false;
            }
         }
   
         if (indy != -1) {
            if (!isEmail(form.elements[j].value)) {
               mensagem("Endereço de Email inválido!");
               form.elements[j].focus();
               form.elements[j].blur();
               form.elements[j].select();
               return false;
            }
         }

         if (inds != -1) {
            if (form.elements[j].value <= 0) {
               mensagem("É necessário preencher o campo QUANTIDADE !");
               return false;
            }
         }
      }
      return true;
   }
   return false;
}

function processa_valid(form) {
   for (k=0; k<(form.elements.length); k++) {
      inda = (form.elements[k].name.indexOf("cnpj") >= 0);
      indb = (form.elements[k].name.indexOf("cpf") >= 0);
      indc = (form.elements[k].name.indexOf("_required") >= 0);
      indd = (form.elements[k].value != "");
      if (inda && indc) {
         if (!cnpj(form.elements[k])) {
            mensagem("Número do CNPJ inválido!");
            form.elements[k].focus();
            form.elements[k].blur();
            form.elements[k].select();
            return false;
         }
      }
      if (indb && indd) {
         if (!cpf(form.elements[k])) {
            mensagem("Número do CPF inválido!");
            form.elements[k].focus();
            form.elements[k].blur();
            form.elements[k].select();
            return false;
         }
      }
   }
   return true;
}

function isEmail(str) {
   returnval = true;
   var r1 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
   if (str != "") {
      check1 = (str.indexOf(".") > 2);
      check2 = (str.indexOf("@") > 0);
      check3 = r1.test(str);
      if (!check1 || !check2 || !check3) {
         returnval = false;
      }
   }
   return returnval;
}

function mensagem(texto) {
   alert(texto);
}

function cnpj(numero) {
   var num   = numero.value;
   var dx    = num.lastIndexOf("-");
   var dv    = num.substring((dx+1),(dx+3));
   num       = num.toString().replace(/\-|\'|\/|\\|\.|[a-zA-Z]/g,'');
   var alg1  = new Array(5,4,3,2,9,8,7,6,5,4,3,2);
   var digt  = 0;
   var resu  = "";
   returnval = true;
  
   for (i=0; i < 2; i++) {
      var soma = 0;
      for (j=0; j < 12; j++) 
         soma = soma + (num.substring(j,(j+1)) * alg1[j]);
 
      if (i == 1) soma = soma + eval(digt * 2);

      digt = ((soma % 11) > 1 ? eval(11 - (soma % 11)) : 0);

      resu = resu + digt.toString();
      alg1 = new Array(6,5,4,3,2,9,8,7,6,5,4,3);
   }

   if (dv != resu) {
      returnval = false;
   }
   return returnval;
}

function cpf(numero) {
   var num   = numero.value;
   var dx    = num.lastIndexOf("-");
   var dv    = num.substring((dx+1),(dx+3));
   num       = num.toString().replace(/\-|\'|\/|\\|\.|[a-zA-Z]/g,'');
   var ini   = 2;
   var fim   = 10;
   var digt  = 0;
   var resu  = "";
   returnval = true;

   for (i=0; i < 2; i++) {
      var soma = 0;
      for (j=ini; j <= fim; j++) 
      soma = soma + eval(num.substring((j-ini),((j-ini)+1))*(fim+1+(i+1)-j));
 
      if (i == 1) soma = soma + eval(digt * 2);

      digt = ((soma % 11) > 1 ? eval(11 - (soma % 11)) : 0);

      resu = resu + digt.toString();
      ini  = 3;
      fim  = 11;
   }

   if (dv != resu) {
      returnval = false;
   }
   return returnval;
}

// Sessão 3
// Conjunto de funcoes para controle do listbox magico
// Determina o sort do listbox
// 1 = Ativa a ordenação
// 2 = Desliga a ordenação
sortitems = 1;
/***********************\
Limpa determinado listbox
\***********************/
function limpabox(listbox) {
   for(var i=0; i<listbox.options.length; i++) {
      listbox.options[i].value = "";
      listbox.options[i].text = "";   
      listbox.options.length -= 1;
   }
   BumpUp(listbox);
}

/***************************************************************************\
Move o conteúdo do listbox original (olist) para o listbox de destino (dlist)
\***************************************************************************/
function move(from, to) {
   for(var i=0;i<from.options.length;){
      var o = from.options[i];
      if(o.selected) {
         o.selected=false;
         o = new Option(o.text,o.value);
         from.options[i] = null;
         for(var j=0; j<to.options.length;j++) {
            var more=eval(to.options[j].value+">"+o.value);
            if(more) {
              var o1=new Option(to.options[j].text,to.options[j].value)
              to.options[j] = o;
              o = o1;
            }
         }
         to.options[to.options.length]=o;         
        
       }
      else i++;
   } 
}

/**********************************************************\
Filtra o box1 de acordo com as informações presentes no box2
\**********************************************************/
function FiltUp(box1,box2) {
   for (var i=0; i<box1.options.length; i++) {
      for (var j=0; j<box2.options.length; j++) {
         if (box1.options[i].value == box2.options[j].value) {
            box1.options[i].value = "";
            box1.options[i].text = "";
            break;
         }
      }
   }

   for (var i=0; i<box2.options.length; i++) {
      box2.options[i].selected = 1;
   }
}

/*****************************************************************\
Redimensiona o tamanho dos indices e os objetos do listbox filtrado
\*****************************************************************/
function BumpUp(box)  {
   for(var i=0; i<box.options.length; i++) {
      if(box.options[i].value == "")  {
         for(var j=i; j<box.options.length-1; j++)  {
            box.options[j].value = box.options[j+1].value;
            box.options[j].text = box.options[j+1].text;
         }
         var ln = i;
         break;
      }
   }

   if(ln < box.options.length)  {
      box.options.length -= 1;
      BumpUp(box);
   }
}

/***********************************\
Executa o sort (ordenação) no listbox
\***********************************/
function SortD(box)  {
   var temp_opts = new Array();
   var temp = new Object();

   for(var i=0; i<box.options.length; i++)  {
      temp_opts[i] = box.options[i];
   }

   for(var x=0; x<temp_opts.length-1; x++)  {
      for(var y=(x+1); y<temp_opts.length; y++)  {
         if(temp_opts[x].text > temp_opts[y].text)  {
            temp = temp_opts[x].text;
            temp_opts[x].text = temp_opts[y].text;
            temp_opts[y].text = temp;
         }
      }
   }

   for(var i=0; i<box.options.length; i++)  {
      box.options[i].value = temp_opts[i].value;
      box.options[i].text = temp_opts[i].text;
   }
}

// GECIWEB --------------------------------------------------------------

function alterna(num,on) {
   if (contador==1) {
      image = eval(IImagem[num] + (on == 1 ? "on.src" : "off.src"));
      document[IImagem[num]].src = image;
   }
   contador = 1;
}

function substitui(num1) {
   var i = 1;
   while (i <= 4) {
      if (i != num1) {
         image = eval(IImagem[i] + "off.src");
         document[IImagem[i]].src = image;
      }
      i++;
   }
   contador = 2;
}

function mOvr(src,clrOver) {
   if (!src.contains(event.fromElement)) {
      src.style.cursor = 'hand';
      src.id = clrOver;
   }
}

function mOut(src,clrIn) {
   if (!src.contains(event.toElement)){
      src.style.cursor = 'default';
      src.id = clrIn;
   }
}

function mClk(src) {
   //if (event.srcElement.tagName=='TD') {
   //   src.children.tags('A')[0].click();
   //}
   parent.right.location.href = src.target; 
}

// sessão 1
// Controles de proteção de dados e manipulacao de eventos referentes a tela

/**********************************************************************\
Abre mensagem na tela p/ usuário não visualizar o código fonte da página
\**********************************************************************/
function event_false() {
      window.event.returnValue = false
}
   
function protege() {
  if (event.button==2)
     mensagem("© VLC Soluções Web e VL Consulting Co."); 
}   

/*************************************************************\
Abre tela de consulta rápida findfunc (procura de funcionarios)
\*************************************************************/
function findfunc() {
  child = open("Vls900-001.php?priv=1","findfunc","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=600,height=200,left=0,top=0");
}

/*************************************************************\
Abre tela de consulta rápida findprod (procura de produtos)
\*************************************************************/
function findprod() {
  child = open("Vls900-002.php","findprod","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=620,height=250,left=0,top=0");
}

/***************\
Abre tela de help 
\***************/
function help(arquivo) {
  helpx = "Vls100-002.php?arquivo=" + arquivo;
  window.open(helpx,"HELP","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=400,height=500,left=350,top=40");
}

/*********************************************\
Modifica o action de um form e executa o submit 
\*********************************************/
function ChangePost(form,dest) {
   form.action = dest; 
   //if (processa_form(form)) {
      form.submit();
   //}
}

// Sessão 2
// Controles de Edição de dados
/***************************\
Formata MyValor em Javascript 
\***************************/
function formataMyvalor(masc,num,mdec) {
   mdec = (mdec - 1);
   dec = Math.pow(10,mdec);
   num = num.toString().replace(/\,/g,'.');
   num = num.toString().replace(/]$|\,/g,'');
   if (isNaN(num)) num = "0";
   if (num.toString().indexOf(".") > 0) {
      cents = num.substring((num.toString().indexOf("."))+1);
   } else {
      cents = Math.floor((num*dec+0.5)%dec);
      if (dec > 10) {
         if (cents < 10) cents = "00" + cents;
      } else {
         if (cents < 10) cents = "0" + cents;
      }
   }
   //num = Math.floor((num*dec+0.5)/dec).toString();
   num = Math.floor((num*dec+0.05)/dec).toString();
   for (var i=0; i < Math.floor((num.length-(1+i))/4); i++)
   num = num.substring(0,num.length-(4*i+3))+'.'+num.substring(num.length-(4*i+3));
   if (num == 0) {
      return num;
   } else {
      if (masc == '@') {
         return (num + '.' + cents);
      } else {
         return (masc + ' '+ num + ',' + cents);
      }
   }
}

/*********************************\
Função para Validação de CGC / CNPJ 
\*********************************/

/**************************\
Função para Validação de CPF 
\**************************/
/***************************************\
Verifica o valor da quantidade de um item
\***************************************/
function checkQtd(field) {
   var valo = eval(field.value);
   var limi = eval(field.limite);
   var masc = field.unidade;
   var ndec = field.decimal;
   if (valo > limi) {
      mensagem("QUANTIDADE EXCEDEU O ESTOQUE ATUAL \n" + formataMyvalor(masc,field.limite,ndec));
      field.value = 0;
      field.focus();
      return false;
   } 
   return true;
}

/*****************************************************************\
Verifica o valor de um campo no formulario p/ mandar dados ao total
\*****************************************************************/
function checkChoice(masc,whichbox,mdec,ndec) {
   with (whichbox.form) {
      whichbox.value = formataMyvalor('@',whichbox.value,ndec);
      if (isNaN(whichbox.value)) { 
         whichbox.value = whichbox.priorval;
         whichbox.focus(); 
      }
      whichbox.value = Math.abs(whichbox.value);
      //var dec = whichbox.value.indexOf('.', 1)
      //if (dec > 0) { 
      //   mensagem('No decimal places allowed for \"' +whichbox.name +'\" !');
      //   whichbox.value = whichbox.priorval;
      //   whichbox.focus();
      //}
      hiddentotal.value = eval(hiddentotal.value) - eval(whichbox.price * whichbox.priorval);
      whichbox.priorval = whichbox.value;
      hiddentotal.value = eval(hiddentotal.value) + eval(whichbox.price * whichbox.value);
      return(formataMyvalor(masc,hiddentotal.value,mdec));
   }
}

/***********************************************\
Inicializa os valores das variaveis totalizadoras
\***********************************************/
function InitForm(form) {
   for (j=0; j<(form.elements.length); j++) {
      indt = form.elements[j].name.indexOf("total");
      if (indt != -1) form.elements[j].value= 0;
   }
}

/*************************************************************\
Processa um form verificando error em campos requeridos e email
\*************************************************************/
/*************************************************************\
Segunda parte da função processa_form para validar campos cnpj
e cpf, por que na mesma função geram um erro desconhecido
\*************************************************************/

/********************************************\
Verifica se o str é uma string de email valida
\********************************************/
/**************************************\
Verifica se a senha1 é identica a senha2 
\**************************************/
function isPasswd(senha1,senha2) {
   if (senha1 == senha2) { 
      return true;
   }
   mensagem("As senhas não estão identicas, digite novamente!");
   return false;   
}

/*****************************************************\
Modifica o estado atual de um determinado checkbox cbox
\*****************************************************/
function changeBox(cbox) {
   box = eval(cbox);
   box.checked = !box.checked;
}


// Sessão 4
// Conjunto de funcoes para controle do menu. 
var isMenu = false;
/********************\
Esconde todos os menus
\********************/
function hideAll() {
   M1.style.left = -500;
   M2.style.left = -500;
   M3.style.left = -500;
}

/**********\
Exibe o menu
\**********/
function PopUp(menu) {
   hideAll();

   switch (menu.id) {
      // M1 => Operações
      case "M1":
         menu.style.left = 0;
         break;

      // M2 => Consultas
      case "M2":
         menu.style.left = 91;
         break;

      // M3 => Cadastros
      case "M3":
         menu.style.left = 182;
         break;
   }
}

/*******************\
Esconde menu corrente 
\*******************/
function PopDown(menu) {
   if (isMenu==false) menu.style.left = -500;
}

/***********************************************\
Muda URL da página para o destino do item de menu
\***********************************************/
function menuClick(Menu) {
   if (Menu.value != "#") {
      parent.center.location.href = Menu.value;
      //window.location.href = Menu.value;
   }
   if (Menu.name == "menu1") {
      window.menu2.options[0].selected = 1;
   } else {
      window.menu1.options[0].selected = 1;
   }
}

/***************************************************\
Controla aparência do menu quando ganha foco do mouse
\***************************************************/
function ItemIn() {
   isMenu=true;
   window.event.srcElement.style.color="#FFFFFF";
   window.event.srcElement.style.background="#0000FF";
   //window.event.srcElement.style.background="#808080";
}

/***********************************************\
Controla aparência do menu quando perde foco do mouse
\***********************************************/
function ItemOut(menu) {
   isMenu=false
   window.event.srcElement.style.color="#000000";
   window.event.srcElement.style.background="#C0C0C0";
   switch (menu.id) {
      // M1 => Operações
      case "M1":
         window.setTimeout('PopDown(M1)',300);
         break;

      // M2 => Consultas
      case "M2":
         window.setTimeout('PopDown(M2)',300);
         break;

      // M3 => Cadastros
      case "M3":
         window.setTimeout('PopDown(M3)',300);
         break;
   }
}

// Sessão 5
// Conjunto de funcoes para controle de Applets 
var gCurrentType = new Array
function changeGraphtype(pApplet,GraphType) {
   pApplet.pcscript( 'main.execute(' + GraphType + ')')
}

function VerificaBrowser() {
   if (NomeBrowser != "Microsoft Internet Explorer" || VersBrowser < "4.0") {
      return "nn";
   }
   return "ie";
}

function abre() {
   document.location.href = "./php/login.php";
}

function valida() {

     var Form, URL, resposta, s;
     Form = document.form1;
     URL = document.URL.toString();

     if (Form.cnpjtomador.value.length == 0) {
	alert("O CGC/CPF é um campo obrigatório !");
        Form.cnpjtomador.focus();
        return false;
     }
     s = limpa_string(Form.cnpjtomador.value);
     // checa se é cpf
     if (s.length == 11) {
	if (valida_CPF(Form.cnpjtomador.value) == false ) {
           alert("O CPF não é válido !");
           Form.cnpjtomador.value = '';
		   Form.cnpjtomador.focus();
           return false;
	}
     }
     // checa se é cgc
     else if (s.length == 14) {
        if (valida_CGC(Form.cnpjtomador.value) == false ) {
	   alert("O CNPJ não é válido !");
           Form.cnpjtomador.value = '';
		   Form.cnpjtomador.focus();
           return false;
	}
     }
     else {
        alert("O CPF/CGC não é válido !");
        Form.cnpjtomador.value = '';
	    Form.cnpjtomador.focus();
		return false;
     }

     return true;
}

function limpa_string(S){
// Deixa so' os digitos no numero
var Digitos = "0123456789";
var temp = "";
var digito = "";
    for (var i=0; i<S.length; i++){
      digito = S.charAt(i);
      if (Digitos.indexOf(digito)>=0){temp=temp+digito}
    }
    return temp
}
function valida_CPF(s)
{
	var i;
	s = limpa_string(s);
	var c = s.substr(0,9);
	var dv = s.substr(9,2);
	var d1 = 0;
	for (i = 0; i < 9; i++)
	{
		d1 += c.charAt(i)*(10-i);
	}
        if (d1 == 0) return false;
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1)
	{
		return false;
	}

	d1 *= 2;
	for (i = 0; i < 9; i++)
	{
		d1 += c.charAt(i)*(11-i);
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1)
	{
		return false;
	}
        return true;
}

function valida_CGC(s)
{
	var i;
	s = limpa_string(s);
	var c = s.substr(0,12);
	var dv = s.substr(12,2);
	var d1 = 0;
	for (i = 0; i < 12; i++)
	{
		d1 += c.charAt(11-i)*(2+(i % 8));
	}
        if (d1 == 0) return false;
        d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1)
	{
		return false;
	}

	d1 *= 2;
	for (i = 0; i < 12; i++)
	{
		d1 += c.charAt(11-i)*(2+((i+1) % 8));
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1)
	{
		return false;
	}
        return true;
}


function valida_numeros(s)
{
	var i; 
	var dif = 0;
	for (i = 0; i < s.length; i++)
	{
		var c = s.charAt(i);
		if (!((c >= "0") && (c <= "9")))
		{
			dif = 1;
		}
	}
	if (dif == 1)
	{
		return false;
	}
	return true;
}

//-->
