/*****************************************************************************************************

 *              Biblioteca de Funções Genéricas                                                      *

 *                                                                                                   *

 * Funções neste arquivo:                                                                            *

 *                                                                                                   *

 * 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 fnSoNumeros(objeto)
{
	var keypress = event.keyCode; 
	var campo = eval (objeto);

	var sCaracteres = '0123456789';

	if (sCaracteres.indexOf(String.fromCharCode(keypress))!=-1){
		event.returnValue = true;
    }else 
		event.returnValue = false;
}

function fnSoNumerosPonto(objeto)
{
	var keypress = event.keyCode; 
	var campo = eval (objeto);

	var sCaracteres = '.0123456789';

	if (sCaracteres.indexOf(String.fromCharCode(keypress))!=-1){
		event.returnValue = true;
    }else 
		event.returnValue = false;
}

//funcao para ver se o usuario digitou numeros nas caixas
function fnSoAlfa(objeto)
{
	var keypress = event.keyCode; 
	var campo = eval (objeto);

	var sCaracteres = 'ABCDEFGHIJKLMNKOPQRSTUVWXYZÃÂÁÀÔÓÒÕÇÜÚÙÍÌÉÈÊabcdefghijklmnopqrstuvwxyzãâáàôõòóçüúùìíéèê ';

	if (sCaracteres.indexOf(String.fromCharCode(keypress))!=-1){
		event.returnValue = true;
    }else 
		event.returnValue = false;
}

function fnAlfaNumeros(objeto)
{
	var keypress = event.keyCode; 
	var campo = eval (objeto);

	var sCaracteres = '/0123456789ABCDEFGHIJKLMNKOPQRSTUVWXYZÃÂÁÀÔÓÒÕÇÜÚÙÍÌÉÈÊabcdefghijklmnopqrstuvwxyzãâáàôõòóçüúùìíéèê ';

	if (sCaracteres.indexOf(String.fromCharCode(keypress))!=-1){
		event.returnValue = true;
    }else 
		event.returnValue = false;
}

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 isNumero (s)
{   
    var i;
    for (i = 0; i < s.length; i++)

    {
        var c = s.charAt(i);
        if (!(c >= "0") && (c <= "9")) return false;

    }
    return true;
}


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);
        alert(matchArray);

        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("Data deve estar no 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)) 
          {
            
            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];}
}

var xmlHttp;
var wcpo;
function createXmlHttpRequest(){
if(window.ActiveXObject) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} else if(window.XMLHttpRequest) {
xmlHttp=new XMLHttpRequest();
}
}

function handleStateChange(){
if(xmlHttp.readyState==4){
   if(xmlHttp.status==200) {
	var message =   xmlHttp.responseXML.getElementsByTagName("descricao")[0].childNodes[0].nodeValue;
	wcpo.value = message;
    } else {
	 alert("Error loading pagen"+ xmlHttp.status +":"+xmlHttp.statusText);
    }
}
}
function procuraEnter(evt) {
	evt = (evt) ? evt : event;
	var c = (evt.which) ? evt.which : evt.keyCode;
	if (c == 13) {
		iniciaRequisicao();
		return false;
	}
	return true;
}
	

function Data12(datai)
{
ano = datai.substring(0,4);
mes = datai.substring(4,6)-12;
dia = 01;
var data = new Date(ano,mes,dia);
var diferenca = data.getTime();
var diferenca = new Date(diferenca);
document.form.pf.value = datai.substring(4,6) + "/" + datai.substring(0,4);
document.form.pi.value = (String)(parseInt(diferenca.getMonth())+1) + "/" + diferenca.getYear();
var anod = diferenca.getYear();
var mesd = (String)(parseInt(diferenca.getMonth())+1);
if(mesd.length == 1)
{
	mesd = format((String)(parseInt(diferenca.getMonth())+1),"0#");
}
return anod+mesd;

}
