/*****************************************************************************************************

 *                                                                                                   *

 * FUNÇÃO                                RETORNO   DESCRIÇÃO                                         *

 * ------                                -------   ---------                                         *

 * testaString(str, descricao)           Boolean   checa string nula ou com brancos                  *

 * testaCombo(combo, descricao)          Boolean   checa se existe opção selecinada                  *

 * testaComboValor(combo, descricao)     Boolean   checa se existe opção selecinada testando valor   *

 *                                                 diferente -1                                      *

 * testaCep(campoCep)                    Boolean   Testa se o Cep é valido                           *

 * testaCgc(campoCgc)                    Boolean   Testa se o CGC é valido                           *

 * checa_cpf (numcpf)                    Boolean   Testa se o Cpf é valido                           *

 * mod(ini,fim)                          Number    Calcula o resto de ini/fim                        *

 * emailCheck(emailStr)                  Boolean   Testa se o E-mail é valido                        *

 * trim(str)                             String    comprime espaços da string                        *

 * testaData(dateStr)                    Boolean   Testa se a data é valida                          *

 * formatCurrency(num)                   String    Formata número separando por (.) e (,)            *

 *                                                 Ex: formatCurrency(1000.5) = "1.000,50"           *

 * format(str,format)					 String    formata o string str no formato definido em format*
 
 * testaValor(str, descricao)            Boolean   checa se o valor numérico e valido e não nulo     *

 * testaRadioGroup(radioObj, descricao)  Boolean   checa se existeb alguma opção selecionada         *

 * testaAno(str, descricao)              Boolean   Testa ano com 4 algarismo                         *

 * isDigit(c)                            Boolean   Testa se o caracter c é numero (0 a 9)            *

 * isInteger (s)                         Boolean   Testa se a string só contem numeros               *
 
 * isSignedInteger (s)                   Boolean   Testa se a string só contem numeros               *

 * isFloat (s)                           Boolean   Testa se a string só contem float (0 a 9 e .)     *

 * testaFloat(numero, descricao)         Boolean   Testa se a string só contem float (0 a 9 e .)     *

 * testaTelefone(numero, descricao)      Boolean   Testa se a string só contem numeros(0 a 9 e -)    *

 * data(strData)                         Number    Valor Numerico da Data, permitindo comparar datas *

 * dataAtual()                           String    data atual formato dd/mm/yyyy                     *

 * strZero(numero, tam)                  String    numero com zeros a esquerda até preencher o tam   *

 * maxText(String, int)                  String    Limita o numero de caracteres da text area String *
                                                   em int                                            *

 *****************************************************************************************************/

var msgConfirmacaoPadrao = "Confirma gravação dos dados";

function Format(value,format)
{
	value = value.replace(/\D/g,"");
	var result="";
	
	if(format.length < value.length)
		return value;
	
	for(i=0,j=0;(i<format.length)&&(j<value.length);i++)
	{
		var ch = format.charAt(i);

		if(ch == '#')
		{
			result += value.charAt(j++);
			continue;
		}
		result += ch;
	}
	return result;
}

function confirmacao(msg) {
  if (trim(msg) == "")
    msg = msgConfirmacaoPadrao; 		
  resp = confirm(msg);
  return resp;
}

function isEmpty(s)
{
	return ((s == null) || (s.length == 0));
}

var hoje = new Date();

var AnoCorrente = parseInt(hoje.getFullYear());

function isLetter (c)
{
	return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) );
}

function isLetterOrDigit (c)
{   
	return (isLetter(c) || isDigit(c) || (c == " "));
}

function soNumeroLetra(str)
{
  var resposta = true;
  for (i = 0; i <= str.length - 1; i++) {
    if (!isLetterOrDigit(str.substr(i,1)))
      resposta = false; 
  }
  return resposta;    
}

function data(strData)
{

  //formato esperado: dd/mm/yyyy

  var ano = strData.substring(6,10);

  var mes = strData.substring(3,5);

  var dia = strData.substring(0,2);

  var dtData = Date.parse(mes + "/" + dia + "/" + ano);

  return dtData;

}


function dataAtual()
{

  var d;

  var s = "";

  d = new Date();
  
  s += (strZero(d.getDate(),2) + "/");
    
  s += strZero((d.getMonth() + 1),2) + "/";
    
  s += d.getFullYear();
  
  return(s);

}



function strZero(numero, tam)

{
  var numero = trim(numero);

  while(numero.length < tam) {

    numero = "0" + numero;

  }

  return numero;

}



function testaString(str, descricao)

{

  if (trim(str) == "") {

    alert(descricao + " é Campo Obrigatório !");

    return false;

  }

  return true;

}





function testaCombo(combo, descricao)

{

  if (combo.selectedIndex == -1 || combo.selectedIndex == 0) {

        if (trim(descricao) != "" && trim(descricao) != " "){

            alert(descricao + " deve ter uma Opção Selecionada");

        }

    return false;

    }

  else

    return true;

}



function testaComboValor(combo, descricao)

{

  if (combo.options[combo.selectedIndex].value == -1) {

        if (trim(descricao) != "" && trim(descricao) != " "){

            alert(descricao + " deve ter uma Opção Selecionada");

        }

    return false;

    }

  else

    return true;

}



function testaValor_(str)

{

    var inp = "";

    var decimal = -1;

    var milhar = -1;

    var chr;

    var negativo = false;

    var texto = trim(str);

    for (i = 1; i <= texto.length; i++) {

        chr = texto.charAt(texto.length - i);

        if (negativo) return 0;

        else if (chr == '-') {

            inp = '-' + inp;

            negativo = true;

        }

        else if (",.".indexOf(chr) >= 0) {

            if (chr == decimal) return 0;

            if (i <= 3) {

                if (decimal != -1) return 0;

                decimal = chr;

                inp = '.' + inp;

            }

            else if (milhar == -1) milhar = chr;

            if (chr != milhar && chr != decimal) return 0;

        }

        else if ("0123456789".indexOf(chr) >= 0) inp = chr + inp;

        else return 0;

    }

    return parseFloat(inp);

}



function testaValor(str, descricao)

{

    if (str.length > 13) {

        alert(descricao + " deve ter no máximo 13 posições");

        return false;

    }

    if (testaValor_(str) == 0 && trim(descricao) != "" && trim(descricao) != " ") {

        alert(descricao + " Deve ser Preenchido Corretamente");

        return false;

    }

    return true;

}



function testaRadioGroup(radioObj, descricao)

{

  for(i = 0; i < radioObj.length; i++) {

    if (radioObj[i].checked)

      return true;

  }

        if (trim(descricao) != "" && trim(descricao) != " "){

                  alert("Deve ser selecionada uma opção de " + descricao);

                  return false;

        }

}



function isDigit (c)

{
	return ((c >= "0") && (c <= "9"));
}



function isInteger (s)


{   var i;

    for (i = 0; i < s.length; i++)

    {

        // Check that current character is number.

        var c = s.charAt(i);



        if (!isDigit(c)) return false;

    }

    // All characters are numbers.

    return true;

}

function isSignedInteger (s)
{  
 if (isEmpty(s))
       if (isSignedInteger.arguments.length == 1) return false;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = false;

        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];

        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;
        return (isInteger(s.substring(startPos, s.length), secondArg));
    }
}



function isFloat (s)



{   var i;

    var decimalPointDelimiter = ".";



    if (s == decimalPointDelimiter) return false;



    for (i = 0; i < s.length; i++)

    {

        // Check that current character is number.

        var c = s.charAt(i);



        if (!((c == decimalPointDelimiter) || (isDigit(c))))

          return false;

    }



    return true;

}



function testaFloat(numero, descricao)

{

  if (!isFloat(numero)) {

    alert(" O campo " + descricao + " deve conter somente números e \".\"");

    return false;

  }

  return true;

}



function testaTelefone (numero, descricao)



{   var i;

    var traco = "-";

    var branco = " ";

    s = trim(numero);

    if (s == traco) {

      alert(descricao + " Não é um Numero de Telefone de Válido");

      return false;

    }

    for (i = 0; i < s.length; i++)

    {

        // Check that current character is number.

        var c = s.charAt(i);



        if (!((c == traco) || (c == branco) || (isDigit(c)))) {

          alert(descricao + " Não é um Numero de Telefone de Válido");

          return false;

        }

    }



    return true;

}





function testaAno(ano, descricao)

{

  var tam = ano.length;

  if (tam < 4) {

    alert(descricao + " Deve ter 4 (quatro) posições");

    return false;

  }

  if (!isInteger(ano)) {

    alert(descricao + " Deve ser Numero Inteiro");

        return false;

  }

  if (parseInt(ano) < parseInt(AnoCorrente - 8)) {

    alert(descricao + " Ano deve ser Maior que " + parseInt(AnoCorrente - 9));

    return false;

  }

  return true;

}



function testaInteiro(numero, descricao)

{

  if (trim(numero) == "") {

    alert(descricao + " é Campo Obrigatório");

    return false;

  }

  var numero = trim(numero);

  var tam = numero.length;

  if (tam > 8) {

    alert(descricao + " deve ter no máximo 8 (oito) posições");

    return false;

  }

  if (!isInteger(numero)) {

    alert(descricao + " deve ser Numero Inteiro");

        return false;

  }

  return true;

}

function testaInteiroNegativo(numero, descricao) {

  var num = trim(numero); 
  
  tamanho = num.length;
 
  if (num.charAt(0) == "-" && tamanho < 2) {

    return false;

  }
  
  if (num.charAt(0) == "-" && tamanho >= 2) {
  
    if(!testaInteiro(num.substring(1,tamanho - 1), descricao)) {
    
      return false;
      
    }
    
  }
  
  else {
  
    if(!testaInteiro(num, descricao)) {

      return false;

    }

  }  

  return true;

}


function testaSignedInteiro(numero, descricao)

{

  if (trim(numero) == "") {

    alert(descricao + " é Campo Obrigatório");

    return false;

  }

  var numero = trim(numero);

  var tam = numero.length;

  if (tam > 9) {

    alert(descricao + " deve ter no máximo 8 (oito) posições");

    return false;

  }

  if (!isSignedInteger(numero)) {

    alert(descricao + " deve ser Numero Inteiro");

        return false;

  }

  return true;

}

function testaCep(campoCep)

{

        /* Critica de CEP - função principal */

        
        var num1 = new initArrayCep(9);

        if((campoCep == null) || (campoCep == "00000-000")) {

              //alert("CEP nulo");

            return false; }

        if(campoCep.length != 9) {

            //alert("CEP diferente de 9 posições");

            return false; }

        if((campoCep.substr(5,1) != "-") || (!isInteger(campoCep.substr(0,5)))

                 || (!isInteger(campoCep.substr(6,3))))

         {

            //alert("CEP deve estar no formato NNNNN-NNN");

            return false;

         }

	return true;


}

function testaCepAntiga(campoCep)

{

        /* Critica de CEP - função principal */

        var dblNum;

        var num1 = new initArrayCep(8);

        if((campoCep == null) || (campoCep == "00000000")) {

              alert("CEP nulo");

            return false; }

        if(campoCep.length != 8) {

            alert("CEP diferente de 8 posições");

            return false; }

        if((campoCep.substr(5,1) < "0") || (campoCep.substr(5,1) > "9")

                 || (campoCep.substr(6,1) < "0") || (campoCep.substr(6,1) > "9")

                 || (campoCep.substr(7,1) < "0") || (campoCep.substr(7,1) > "9"))

         {

            alert("CEP não deve conter caracteres diferentes de números");

            return false;

         }



        dblNum = 0.1;

        if(!isNaN(campoCep))

        {

                dblNum = campoCep;

                return true;

        }

        else

        {

                alert("CEP tem que ser numérico");

                return false;

        }

}



function initArrayCep()

{

        /* Critica de Cep - Sub-funcao */

        this.length = initArrayCep.arguments.length;

      for (var i = 0 ; i < 9 ; i++)

        {

        this[i] = " ";

      }

}



function testaCgc(campoCgc)

{

      var num1 = new initArray(14);

      if(campoCgc == null)

        {     //alert("CNPJ nulo");

            return false;

        }

        if(campoCgc.length != 14)

        {

            //alert("CNPJ diferente de 14 posições");

            return false;

        }

            for (var i = 0 ; i < 14 ; i++)

                {

               num1[i] = campoCgc.substring(i, i+1);

                }



        digito13 = calculaDigito(13, num1);

        digito14 = calculaDigito(14, num1);

        if (num1[12]==(digito13) && num1[13]==(digito14)){

            return true;  }

      else {

            //alert("CNPJ incorreto");

            return false;  }



}



function initArray()

{

        this.length = initArray.arguments.length;

      for (var i = 0 ; i < 14 ; i++)

        {

        this[i] = " ";

      }

}



function calculaDigito( cgc_limite,  num)

{

     cgc_soma = 0;

     cgc_ind = 1;

     cgc_peso = cgc_limite - 7 - cgc_ind;

     while(cgc_ind < cgc_limite)

     {

         cgc_soma += num[cgc_ind - 1] * cgc_peso;

         cgc_ind++;

         if(cgc_peso == 2)

              cgc_peso = 9;

         else

              cgc_peso--;

     }

     cgc_resto = mod(cgc_soma, 11);

     if(cgc_resto == 0 || cgc_resto == 1)

           {cgc_digito = 0;}

     else

           {cgc_digito = 11 - cgc_resto;}

     return cgc_digito;

}



function mod(ini, fim)

{

     t = ini % fim;

     return t;

}

function temRepeticao(str, num)
{
  var cont = 0;
  var num = parseInt(num,10);
  for (i = 0; i <= str.length - 1; i++) {
    cont = 0; 
    for (j = i + 1; j <= str.length - 1; j++) {
	  if (str.substr(i,1) == str.substr(j,1))
	    cont++;
	  else
	    break;
	}
	if (cont >= num) 
	  break;
  }
  return (cont >= num);
}

function checa_cpf (numcpf)

{
        // teste se o cpf tem 11 numeros repetidos (iguais)  
        if (temRepeticao(numcpf,10)) {
          alert ("Número do CPF inválido !!!");
          return false;
        }
        x = 0;

        soma = 0;

        dig1 = 0;

        dig2 = 0;

        texto = "";

        numcpf1="";

        len = numcpf.length; x = len -1;

        // var numcpf = "12345678909";

        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;

        //alert ("Digito Verificador : " + dig1 + "" + dig2);

        if ((dig1 + "" + dig2) == numcpf.substring(len,len-2)) {

                return true;

        }

        alert ("Número do CPF inválido !!!");

        falso = "F";

        return false;

}



function testa_CPF(numcpf)

{

        if(checa_cpf(numcpf)) {

                return true;

        }

        else {

                return false;

        }

}



function emailCheck (emailStr) {

        //remove espaços antes da verificação

        var emailStr = trim(emailStr);

        /* Critica de e-mail */

        var emailPat="/^(.+)@(.+)$/";

        var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";

        var validChars="\[^\\s" + specialChars + "\]";

        var quotedUser="(\"[^\"]*\")";

        var ipDomainPat="/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/";

        var atom=validChars + "+";

        var word="(" + atom + "|" + quotedUser + ")";

        var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

        var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");





        var matchArray=emailStr.match(emailPat);

        if (matchArray==null) {

                alert("O endereço de e-mail parece incorreto (verifique @ e .'s)");

                return false;

        }

        var user=matchArray[1];

        var domain=matchArray[2];



        if (user.match(userPat)==null) {

            alert("O nome de usuário do e-mail não parece ser válido.");

            return false;

        }



        var IPArray=domain.match(ipDomainPat);

        if (IPArray!=null) {

                  for (var i=1;i<=4;i++) {

                    if (IPArray[i]>255) {

                        alert("O endereço IP de destino do e-mail é inválido!");

                        return false;

                    }

            }

            return true;

        }



        var domainArray=domain.match(domainPat);

        if (domainArray==null) {

                alert("O nome do domínio do e-mail não parece ser válido.");

            return false;

        }



        var atomPat=new RegExp(atom,"g");

        var domArr=domain.match(atomPat);

        var len=domArr.length;

        if (domArr[domArr.length-1].length<2 ||

            domArr[domArr.length-1].length>3) {

           alert("O endereço de e-mail deve terminar com um domínio de 3 letras ou um país com 2 letras.");

           return false;

        }



        if (len<2) {

           var errStr="Este endereço de e-mail não possui um nome de Host!";

           alert(errStr);

           return false;

        }



        return true;

}





function trim(str) {

  str = str.toString().replace(/\$|\ /g,'');

  return str;

}



function testaData(dateStr) {

  // testa data em branco -> usa função trim
  dateStr = trim(dateStr);

  if (trim(dateStr) == "") {

    alert("Data é Campo Obrigatório");

    return false;

  }

  // testa numero de caracteres da data

  if (dateStr.length != 10) {
    
    alert("Formato de data inválido. Utilize o formato dd/mm/aaaa");

    return false;

  }

// Checks for the following valid date formats:

// DD/MM/YY   DD/MM/YYYY   DD-MM-YY   DD-MM-YYYY

// Also separates date into month, day, and year variables



	// To require a 2 digit year entry, use this line instead:

	var datePat = "/^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/";



// To require a 4 digit year entry, use this line instead:

   var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;



var matchArray = dateStr.match(datePat); // is the format ok?

if (matchArray == null) {

alert("Data deve estar no formato DD/MM/AAAA");

return false;

}



day = matchArray[1];

month = matchArray[3]; // parse date into variables

year = matchArray[4];


if (day < 1 || day > 31) {

alert("Dia deve ser entre 1 e 31.");

return false;

}

if (month < 1 || month > 12) { // check month range

alert("Mês deve ser entre 1 e 12.");

return false;

}

if ((month==4 || month==6 || month==9 || month==11) && day==31) {

alert("Mês "+month+" não tem 31 dias!");

return false;

}

if (month == 2) { // check for february 29th

var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));

if (day>29 || (day==29 && !isleap)) {

alert("Fevereiro " + year + " não tem " + day + " dias!");

return false;

   }

}

return true;  // date is valid

}



function formatCurrency(num) {

num = num.toString().replace(/\$|\./g,'');

num = num.toString().replace(/\$|\,/g,'.');

if(isNaN(num)) num = "0";

cents = Math.floor((num*100+0.5)%100);

num = Math.floor(num).toString();

if(cents < 10) cents = "0" + cents;

for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)

num = num.substring(0,num.length-(4*i+3))+'.'+num.substring(num.length-(4*i+3));

return (num + ',' + cents);

}



function valorCurrency(num)

{

  num = num.toString().replace(/\$|\./g,'');

  num = num.toString().replace(/\$|\,/g,'.');

  valor = parseFloat(num);
  return valor;

}



function roundOff(value, precision)

{

        value = "" + value; //convert value to string

        precision = parseInt(precision,10);



        var whole = "" + Math.round(value * Math.pow(10, precision));



        var decPoint = whole.length - precision;



        if(decPoint != 0)

        {

                result = whole.substring(0, decPoint);

                result += ".";

                result += whole.substring(decPoint, whole.length);

        }

        else

        {

                result = whole;

        }

        return result;

}



function maxText(descricao,limite,nome){

   if (nome.length > (limite-1)){
       alert("O campo " + descricao + " não pode ter mais que " + limite + " caracteres" );
       nome=nome.substring(0,(limite-1));
       return false;
   }
   return true;    
}



//Calcula número de dias entre dataFim e Data Inicio

function intervaloDatas(dataInicio,dataFim) {
  
        var data_Ini = data(dataInicio);

        var data_Fim = data(dataFim);

        var intervaloDias = (data_fim - data_Inicio)/86400000;

        return intervalosDias;

}
/**************************************************************************************
function soloNumeros(e) { 
 
  Evita que se puedan escribir caracteres que no sean numeros en un campo.
  Para asociar esta funcion a un campo hay que usar:
		document.forms[0].nombreCampo.onkeypress = soloNumeros; 
  e: evento que se genera
  
***************************************************************************************/

function soloNumeros(e) {

 if (navigator.appName == 'Microsoft Internet Explorer')
         key = window.event.keyCode;
     else
         key = e.which;

    var caracterPulsado=String.fromCharCode(key);

	if(isDigit(caracterPulsado) || key == 45) {
   		return true;
   		}
   	else {
		return false;
  	}

  }

function soloCurrency(e) {

 if (navigator.appName == 'Microsoft Internet Explorer')
         key = window.event.keyCode;
     else
         key = e.which;

    var caracterPulsado=String.fromCharCode(key);

	if(isDigit(caracterPulsado) || key == 44 || key == 45 || key == 46 ) {
   		return true;
   		}
   	else {
		return false;
  	}

  }

// si el argumento d está en blanco se devuelve la data actual
function seleccionaData(d) {

 return ((d != '' ) ? d : dataAtual());

}

//Verifica se dataInicio e anterior a dataFim em atre numMeses meses
      
       function validaIntervaloMes (dataInicio,dataFim,numMeses) {
       
        var anoInicio = parseInt(dataInicio.substring(6,10),10);
        var mesInicio = parseInt(dataInicio.substring(3,5),10);
        var diaInicio = parseInt(dataInicio.substring(0,2),10);
        var anoFim = parseInt(dataFim.substring(6,10),10);
        var mesFim = parseInt(dataFim.substring(3,5),10);
        var diaFim = parseInt(dataFim.substring(0,2),10);
	var x = 0;
	
	if (anoInicio == anoFim) {
          if (mesInicio < (mesFim - numMeses)) {
            return false;
          }
          if (mesInicio == (mesFim - numMeses)) 
          {
            alert("Mes inicio = mes fin - x");
            if (diaFim == 31 && diaInicio == 30 && mesInicio != 1 && mesInicio != 3 && mesInicio != 5 && mesInicio != 7 && mesInicio != 8 && mesInicio != 10 && mesInicio != 12) {
			  return true;
			}
			if (diaFim == 31 && mesInicio== 02 && diaInicio == 28) {
			  return true;
	        }
			if (diaFim == 30 && mesInicio== 02 && diaInicio == 28) {
			  return true;
	        }
			if (diaFim == 31 && mesInicio== 02 && diaInicio == 29) {
			  return true;
	        }
			if (diaFim == 30 && mesInicio== 02 && diaInicio == 29) {
			  return true;
	        }
			if (diaInicio < diaFim) {
              return false;
            }
          }
          return true;
        }
        if (anoInicio < (anoFim - 1)) {
          return false;
        }
        if (anoInicio == (anoFim - 1)) {
          if (mesFim > numMeses) {
            return false;
          }
          for (i = numMeses; i >= 1;i--) {
            if (mesFim == i) {
              if (mesInicio < 12 - x) {
                return false;
              }
              if (mesInicio == 12 - x) {
                if (diaFim == 31 && diaInicio == 30 && mesInicio != 1 && mesInicio != 3 && mesInicio != 5 && mesInicio != 7 && mesInicio != 8 && mesInicio != 10 && mesInicio != 12) {
			      return true;
			    }
				if (diaFim == 31 && mesInicio== 02 && diaInicio == 28) {
			      return true;
	            }
				if (diaFim == 30 && mesInicio== 02 && diaInicio == 28) {
			      return true;
	            }
				if (diaFim == 31 && mesInicio== 02 && diaInicio == 29) {
			      return true;
	            }
				if (diaFim == 30 && mesInicio== 02 && diaInicio == 29) {
			      return true;
	            }
				if (diaInicio > diaFim) {
                  return false;
                }
              }
            }
            x = x + 1;
          }
        }
        return true;
      }
    
 function MM_swapImgRestore() {// v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() {// v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) {// v3.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}

function MM_swapImage() {// v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

/********************************************************************************/

//Retorna False se o cnpj for invalido!
function testaCnpj(variavel) {
                 //CNPJ = document.validacao.CNPJID.value;
				 CNPJ = variavel
                 erro = new String;
                 if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! "; 
                 if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
                 if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! ";
                 }
                 //substituir os caracteres que não são números
               if(document.layers && parseInt(navigator.appVersion) == 4){
                       x = CNPJ.substring(0,2);
                       x += CNPJ. substring (3,6);
                       x += CNPJ. substring (7,10);
                       x += CNPJ. substring (11,15);
                       x += CNPJ. substring (16,18);
                       CNPJ = x; 
               } else {
                       CNPJ = CNPJ. replace (".","");
                       CNPJ = CNPJ. replace (".","");
                       CNPJ = CNPJ. replace ("-","");
                       CNPJ = CNPJ. replace ("/","");
               }
               var nonNumbers = /\D/;
               if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! "; 
               var a = [];
               var b = new Number;
               var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
               for (i=0; i<12; i++){
                       a[i] = CNPJ.charAt(i);
                       b += a[i] * c[i+1];
}
               if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
               b = 0;
               for (y=0; y<13; y++) {
                       b += (a[y] * c[y]); 
               }
               if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
               if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
                       //erro +="Dígito verificador com problema!";
					    return false;
               }
               if (erro.length > 0){
                       //alert(erro);
                       return false;
               } else {
                       //alert("CNPJ valido!");
					    return true;
               }
               return true;
       }


function VerificaDados(){
var erro =0;
	if(document.InsereUsuarios.Nome.value==''){
		msg="Preencha seu nome.";
		alert(msg);
		return false;
	}
	if(document.InsereUsuarios.Cpf.value==''){
		msg="Preencha seu CPF.";
		alert(msg);
		return false;
	}					
	if(document.InsereUsuarios.Rg.value==''){
		msg="Preencha seu Rg.";
		alert(msg);
		return false;
	}
	if(document.InsereUsuarios.DddTelefone.value==''){
		msg="Preencha o DDD de seu telefone.";
		alert(msg);
		return false;
	}
	if(document.InsereUsuarios.DddCelular.value==''){
		msg="Preencha o DDD de seu Celular.";
		alert(msg);
		return false;
	}
	if(document.InsereUsuarios.Telefone.value==''){
		msg="Preencha o Telefone.";
		alert(msg);
		return false;
	}
	if(document.InsereUsuarios.Celular.value==''){
		msg="Preencha o Celular.";
		alert(msg);
		return false;
	}
	if(document.InsereUsuarios.Email.value==''){
		msg="Preencha o Email.";
		alert(msg);
		return false;
	}
	if(document.InsereUsuarios.Login.value==''){
		msg="Preencha o Login.";
		alert(msg);
		return false;
	}
	document.InsereUsuarios.submit();
}

function checaCPF(campo) {
	CPF = campo.value;
	erro = 0;
	
	if(CPF==''){
		return false;
	}
	if (CPF.length != 11 || CPF == "00000000000" || CPF == "11111111111" ||
		CPF == "22222222222" ||	CPF == "33333333333" || CPF == "44444444444" ||
		CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
		CPF == "88888888888" || CPF == "99999999999")
		erro = 1;
		soma = 0;
	for (i=0; i < 9; i ++)
		soma += parseInt(CPF.charAt(i)) * (10 - i);
		resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(CPF.charAt(9)))
		erro = 1;
		soma = 0;
		for (i = 0; i < 10; i ++)
			soma += parseInt(CPF.charAt(i)) * (11 - i);
		resto = 11 - (soma % 11);
		if (resto == 10 || resto == 11)
			resto = 0;
		if (resto != parseInt(CPF.charAt(10)))
			erro = 1;
		if(erro==1){
			alert('CPF invalido!!!');
			campo.focus();
		}

}

function retorna() {
history.go(-1);
}

function tamanho_campo(objA, objP,tipo, tamanho) {
	var key = window.event.keyCode;	
  	if(tipo==0) {
				if (( key < 47 )||( key > 58 )) {
						window.event.returnValue = null; 
						return; 
     			}
 			}
	 caracter = String.fromCharCode(key); 
   	 palavra = objA.value +  caracter; 
	 if (palavra.length == tamanho) 
   		{
   			objA.value = palavra;
			window.event.returnValue = null;
			objP.focus();
			return;
   		}
   	 else
   		{ 
			if (palavra.length > tamanho) 
   				{
   					objA.value = palavra.substring(0, tamanho);
					window.event.returnValue = null;
					objP.focus();
					return;
   				}
   			else
   				{ 
	 	 			objA.focus(); 
	  			}
   		}
}

function valida_numero(s){
	if ( s != '' ) {
		var i;
		var dif = 0;
		for (i = 0; i < s.value.length; i++){
			var c = s.value.charAt(i);
			if (!((c >= '0') && (c <= '9'))){
				dif = 1;
			}
		}
		if (dif == 1){
			alert('Este campo deve ser numerico!');
			s.focus();	
			s.select();
			return false;
		}
	}
	return true;
}
 function tamanho_campo(objA, objP,tipo, tamanho) {
	var key = window.event.keyCode;	
  	if(tipo==0) {
				if (( key < 47 )||( key > 58 )) {
						window.event.returnValue = null; 
						return; 
     			}
 			}
	 caracter = String.fromCharCode(key); 
   	 palavra = objA.value +  caracter; 
	 if (palavra.length == tamanho) 
   		{
   			objA.value = palavra;
			window.event.returnValue = null;
			objP.focus();
			return;
   		}
   	 else
   		{ 
			if (palavra.length > tamanho) 
   				{
   					objA.value = palavra.substring(0, tamanho);
					window.event.returnValue = null;
					objP.focus();
					return;
   				}
   			else
   				{ 
	 	 			objA.focus(); 
	  			}
   		}
}
function verifica_mail(mail) {
var formulario;
  if ((mail.value).length > 0) {
	formulario = document.cad1
	if (!/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/.test(mail.value)) {
		alert('E-mail incorreto.');
		mail.focus();
		return false;
	}
	var _dominio = formulario.nome.value+'.'+formulario.sufixo.value;
	var _dominio_email = mail.value;
	var _iPos = _dominio_email.indexOf('@',0);
	_dominio_email = _dominio_email.substring(_iPos+1, _dominio_email.length);
	if (_dominio_email == _dominio) {
		alert('E-mail Inválido.\nEste deve ser um e-mail atualmente disponível para você, \ncaso contrário você não conseguirá receber as instruções iniciais da LocaWeb.');
		mail.focus();
		return false;
	}
  if ((formulario.email_cobranca.value).length == 0) {
			formulario.email_cobranca.value = mail.value;
		}
	return true;
 }
}

function VerificaDadosModulo(){
var erro =0;
	if(document.InsereModulo.Nome.value==''){
		msg="Preencha o nome do módulo.";
		alert(msg);
		return false;
	}
	if(document.InsereModulo.Url.value==''){
		msg="Preencha a url.";
		alert(msg);
		return false;
	}					
	document.InsereModulo.submit();
}




function VerificaDadosClientes(){
var erro =0;
	if(document.InsereClientes.Nome.value==''){
		msg="Preencha seu nome.";
		alert(msg);
		return false;
	}
	if(document.InsereClientes.Cpf.value==''){
		msg="Preencha seu CPF.";
		alert(msg);
		return false;
	}					
	if(document.InsereClientes.Rg.value==''){
		msg="Preencha seu Rg.";
		alert(msg);
		return false;
	}
	if(document.InsereClientes.DddTelRes.value==''){
		msg="Preencha o DDD de seu telefone.";
		alert(msg);
		return false;
	}
	if(document.InsereClientes.DddTelCom.value==''){
		msg="Preencha o DDD de seu Celular.";
		alert(msg);
		return false;
	}
	if(document.InsereClientes.DddTelCel.value==''){
		msg="Preencha o DDD de seu Celular.";
		alert(msg);
		return false;
	}
	if(document.InsereClientes.PrefTelRes.value=='' || document.InsereClientes.FinTelRes.value==''){
		msg="Preencha o Telefone.";
		alert(msg);
		return false;
	}
	if(document.InsereClientes.Email.value==''){
		msg="Preencha o Email.";
		alert(msg);
		return false;
	}
	if(document.InsereClientes.Endereco.value==''){
		msg="Preencha o Login.";
		alert(msg);
		return false;
	}
	document.InsereClientes.submit();
}

function verificaDatas(dtInicial, dtFinal){
	
	var dtini = dtInicial;
	var dtfim = dtFinal;
	
	if ((dtini == '') && (dtfim == '')) {
		alert('Complete os Campos data.');
		//campos.inicial.focus();
		return false;
	}
	
	datInicio = new Date(dtini.substring(6,10), 
						 dtini.substring(3,5), 
						 dtini.substring(0,2));
	datInicio.setMonth(datInicio.getMonth() - 1); 
	
	
	datFim = new Date(dtfim.substring(6,10), 
					  dtfim.substring(3,5), 
					  dtfim.substring(0,2));
					 
	datFim.setMonth(datFim.getMonth() - 1); 

	if(datInicio <= datFim){
		//alert('Cadastro Completo!');
		return true;
	} else {
		alert('ATENÇÃO: Data Inicial é maior que Data Final');
		//document.all.campos.final.focus();
		//document.all.campos.final.select();
		return false;
	}	
}


