function RIT_checkForm( frm ) {
   var valido = true;

   if (document.getElementById('contErrSumario'))
   {
 	  document.getElementById('contErrSumario').style.display='none';
 	  document.getElementById('contObriLista').style.display='none';
 	  document.getElementById('contErrLista').style.display='none';
 	  document.getElementById('divObriSumario').innerHTML="";
 	  document.getElementById('divErrSumario').innerHTML="";
   }
   
   for (iCont = frm.elements.length-1 ; iCont >= 0; iCont--) {
   		   if(!frm.elements[iCont].getAttribute("RIT_Output")==""){ 
   	       document.getElementById(frm.elements[iCont].getAttribute("RIT_Output")).innerHTML="";
   	   	   if(frm.elements[iCont].getAttribute("RIT_Required")==""){
				if(!checkVazio(frm.elements[iCont],frm.elements[iCont].getAttribute("RIT_Name"))) valido = false;
			}
			
			//Switch para os valores do RIT_Type	
		   switch(frm.elements[iCont].getAttribute("RIT_Type")){
					case "email":
						if(frm.elements[iCont].value != ""){
						    if(!checkEmail(frm.elements[iCont],frm.elements[iCont].getAttribute("RIT_Name"))) valido = false;
						}break    
					case "cpf":
  						if(frm.elements[iCont].value != ""){
  							if(!pfValidaCPF_CGC(frm.elements[iCont], frm.elements[iCont].getAttribute("RIT_Name")))	valido = false;
  						}
					    break
					case "cnpj":
  						if(frm.elements[iCont].value != ""){
  							if(!pfValidaCPF_CGC(frm.elements[iCont], frm.elements[iCont].getAttribute("RIT_Name"))) valido = false;
  						}
  						break 
  					case "radio":
  						if(frm.elements[iCont].value != ""){
  							if(!checkRadio(frm.elements[iCont],frm.elements[iCont].name,frm.elements[iCont].getAttribute("RIT_Name"))) valido = false;
  						}
  						break
  					case "checkbox":
  						if(frm.elements[iCont].value != ""){
  							if(!checkCheckboxes(frm.elements[iCont],frm.elements[iCont].name, frm.elements[iCont].getAttribute("RIT_Name"))) valido = false;
  						}
  						break 
  					case "select":
  					    if(frm.elements[iCont].value == ""){
  							if(!checkSelect(frm.elements[iCont], frm.elements[iCont].name,frm.elements[iCont].getAttribute("RIT_Name"))) valido = false;
  						}
						break
  					case "confirmacao":
  						if(!checkConfirmacao(frm.elements[iCont], frm.elements[iCont].name,frm.elements[iCont].getAttribute("RIT_Name"))) valido = false;
  						break 
					case "DataEuropeia":
					      if (frm.elements[iCont].value != ""){
							  if(!checkDate(frm.elements[iCont], frm.elements[iCont].getAttribute("RIT_Name")))	valido = false;	
					    } 
						break						
		   }
		   
			
   	    }		
	}
	return(valido);

}

function appendMessage(Id, msg) {
	  var oNewP = document.createElement("div");
      var oText = document.createTextNode(msg);
      //document.getElementById(Id).appendChild(oText);
      if (document.getElementById('contErrSumario'))
      {
    	  //var oText2 = document.createTextNode(msg+"<br />");
    	  document.getElementById('contErrSumario').style.display='block';
    	  if(msg.indexOf("obrigat")>0)
    	  {
    		  document.getElementById('contObriLista').style.display='block';
    		  document.getElementById('divObriSumario').innerHTML=msg.substr(0,msg.length-12)+"<br />"+document.getElementById('divObriSumario').innerHTML;
    	  }
    	  else
    	  {
    		  document.getElementById('contErrLista').style.display='block';
    		  document.getElementById('divErrSumario').innerHTML=msg+"<br />"+document.getElementById('divErrSumario').innerHTML;
    	  }  
    	  //document.getElementById('divErrSumario').appendChild(oText2);
    	  
      }
      //document.body.appendChild(oNewP);
   }
function checkConfirmacao(pCampo,pMsg)
{
	objFrom=document.getElementById(pCampo.getAttribute("RIT_From"));
	
	if (pCampo.value != objFrom.value)
	{
		appendMessage(pCampo.getAttribute("RIT_Output"), "A confirmação de " + objFrom.getAttribute("RIT_Name") + " está diferente do campo original");
		pCampo.focus();
		return false;		
	}
	return true;
}   

function checkVazio(pCampo,pMsg)
{
	if (pCampo.value == "")
	{
		//appendMessage(pCampo.getAttribute("RIT_Output"), "Preenchimento do campo " + pMsg + " obrigatório");
		appendMessage(pCampo.getAttribute("RIT_Output"), pMsg + " obrigatório");
		//pCampo.focus();
		return false
	}
	return true
}

function checkRadio(pCampo,id,pMsg)
{	var campos = document.getElementsByName(id);
	for(var i=0; i < campos.length; i++)
	{		
		if(campos[i].checked)
		{
			return true
		}
	}
	//pCampo.focus();
	//appendMessage(pCampo.getAttribute("RIT_Output"), "Preenchimento do campo " + pMsg + " obrigatório");
	appendMessage(pCampo.getAttribute("RIT_Output"), pMsg + " obrigatório");
	return false;
}

function checkCheckboxes(pCampo,id,pMsg){
    var boxes = document.getElementsByName(id);
    for (i=0; i<boxes.length; i++)
    {	if (boxes[i].type=="checkbox" && boxes[i].checked){
            return true
        }
    }
    pCampo.focus();
	appendMessage(pCampo.getAttribute("RIT_Output"), "Preenchimento do campo " + pMsg + " obrigatório");
	return false
}

function checkSelect(pCampo,id,pMsg){
	if(pCampo.value == ""){
       return true
    }
    pCampo.focus();
	//appendMessage(pCampo.getAttribute("RIT_Output"), "Preenchimento do campo " + pMsg + " obrigatório");
	appendMessage(pCampo.getAttribute("RIT_Output"), pMsg + " obrigatório");
	return false
}

function checkNumber(pCampo,pMsg)
{
	if (!validateNumber(pCampo.value))
	{  
	    appendMessage(pCampo.getAttribute("RIT_Output"),pMsg + " inválido! Favor preencher corretamente.");
		pCampo.focus();
		return false;
	}
	return true;
}

function checkDate(pCampo,pMsg)
{
	if (!validateDate(pCampo.value))
	{ 
		
		
		//pCampo.focus();
		appendMessage(pCampo.getAttribute("RIT_Output"), " " + pMsg + " inválido! Favor preencher corretamente.");
		return false
	}
	return true
}


function checkLen(pCampo,pMsg,tam,tam2)
{
	var TAMANHO;

	TAMANHO=pCampo.value.length;

	if (!((TAMANHO >= tam) && (TAMANHO <= tam2)))
	{
		alert(pMsg);
		pCampo.focus();
		return false;
	}
	return true;
}	

function checkEmail(pCampo,pMsg)
{
	if (!validateEmail(pCampo.value))
	{   
		appendMessage(pCampo.getAttribute("RIT_Output"),pMsg + " inválido! Favor preencher corretamente.");
		pCampo.select();
		return false;
	}
	return true;
}

function cleanNumber(s)
{
	var numeroLimpo="";
	var thisChar;	
	
	//Test for a string
	if (s.length <= 0)
	{
		return "";
	}

	for (var j=0; j < s.length; j++)  
	{                                      
          thisChar = s.substring(j,j+1);                              
		  if (thisChar >= "0" && thisChar <= "9") 
		  {                             
		      numeroLimpo = numeroLimpo + "" + thisChar;
		  }
	}
	return numeroLimpo;
}

function validateNumber(s)
{
	var gabarito = "0123456789";
	var temPonto = false;
	var thisChar;	
	
	//Test for a string
	if (s.length <= 0)
	{
		return false;
	}

	for (var j=0; j < s.length; j++)  
	{                                      
          thisChar = s.substring(j,j+1);                              
          if (thisChar == "," )
	    {                             
             return false ;                                                  
          }    
          
	    if (thisChar == "." )
	    {                             
	       temPonto = true;
          }    
	}

	
	//Cria varios Arrays em funcao do pos pontos que possam ser encontrados.
	strarr = new Array ()

	//Use own split function as JScript does not include JavaScripts split function
	own_split(strarr, s, ".");


			
	if (strarr.length > 2)
	{//O numero possui mais de um ponto.
		return false;
	}


	//O numero esta coerente em relacao ao ponto.
	if  (strarr.length == 2) 
	{
		if ( (strarr[0].length == 0) || (strarr[1].length == 0 ) )
		{
			return false;
		}
	}

	//Numero sem casa decimal
	if  ((strarr.length == 1) && (temPonto))
	{
		return false;
	}



	//Test the value of each element falls in an acceptable range
	for (var i = 0; i < strarr.length; i++)
	{
		for (var k = 0; k < strarr[i].length; k++)
		{
	          thisChar = strarr[i].substring(k,k+1); 
		  if (thisChar < "0" || thisChar > "9") 
		  {                             
		      return false ;
		  }
		}
	}

	return true;
}


//Date validation function
function validateDate(s)
{
	//Test for a string
	if (s.length > 0)
	{
		//Create an array to split the date into (dd/mm/yyyy)
		strarr = new Array ()

		//Use own split function as JScript does not include JavaScripts split function
		own_split(strarr, s, "/");
		
		//3 array elements means day, month, and year
		if (strarr.length == 3)
		{
			//Test the value of each element falls in an acceptable range
			for (var i = 0; i < strarr.length; i++)
			{
				if ((strarr[0] < 0) || (strarr[0] >31)){
					return false;
				}
				if ((strarr[1] < 0) || (strarr[1] >12)){
					return false;
				}
				if (strarr[2].length != 4 ){
					return false;
				//Verifica se aos mes de fevereiro foi atribuido mais de 29 dias
				if((strarr[1] == 2) && (strarr[0]>29))
					return false;
				//Verifica se aos mes de abril foi atribuido mais de 30 dias
				if((strarr[1] == 4) && (strarr[0]>30))
					return false;
				//Verifica se aos mes de junho foi atribuido mais de 30 dias
				if((strarr[1] == 6) && (strarr[0]>30))
					return false;
				//Verifica se aos mes de setembro foi atribuido mais de 30 dias
				if((strarr[1] == 9) && (strarr[0]>30))
					return false;
				//Verifica se aos mes de novembro foi atribuido mais de 30 dias
				if((strarr[1] == 11) && (strarr[0]>30))
					return false;

				}
			}
			return true;
		}
		return false;
	}
	return false;
}


//String split function to accomodate JScripts lack of JavaScripts split function
function own_split(arr, str, delim)
{
	//Initialise local variables
	var pos = 0;
	var num = 0;
	var start = 0;
	
	//Loop while there are characters in the string
	while (pos < str.length)
	{
		//Loop while there are delimiters in the string
		while((str.substring (pos, pos+1) != delim) && (pos < str.length))
		{
		pos++;
		}
		//Add the new characters to the output array
		arr[num] = str.substring(start,pos);
		num++;
		start = pos+1;
		pos++;
	}
}

function MesNumero(NomeMes)
{
	if (NomeMes == "Jan")	
		return MesNumero = "01"
	if (NomeMes == "Fev")	
		return MesNumero = "02"
	if (NomeMes == "Mar")	
		return MesNumero = "03"
	if (NomeMes == "Abr")	
		return MesNumero = "04"
	if (NomeMes == "Mai")	
		return MesNumero = "05"
	if (NomeMes == "Jun")	
		return MesNumero = "06"
	if (NomeMes == "Jul")	
		return MesNumero = "07"
	if (NomeMes == "Ago")	
		return MesNumero = "08"
	if (NomeMes == "Set")	
		return MesNumero = "09"
	if (NomeMes == "Out")	
		return MesNumero = "10"
	if (NomeMes == "Nov")	
		return MesNumero = "11"
	if (NomeMes == "Dez")	
		return MesNumero = "12"	
}

function validateEmail(Expression)
{	
	if (Expression == null){ alert(Expression + "Ola321");
		return (false);}
	var supported = 0;
	Expression = Trim(Expression);
	if(Expression.indexOf(" ")>-1)
	{
		return false;
	}
	if (window.RegExp)
	{
		var tempStr = "a";
		var tempReg = new RegExp(tempStr);
		if (tempReg.test(tempStr)) supported = 1;
	}
	if (!supported) 
		return (Expression.indexOf(".") > 2) && (Expression.indexOf("@") > 0);
	var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
	var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
	return (!r1.test(Expression) && r2.test(Expression));
}


function isValidDate(frm,txt) {
  var dd, mm, aa;
  aa  = parseInt(frm.substring(6,10));
  dd  = frm.substring(0, 2);
  mm  = frm.substring(3, 5);
  var msg = '';
  if ((dd < '01') || (dd > '31')) {
    alert(msg + 'dia inv�lido!');
	return false;}
  if ((mm < '01') || (mm > '12')) {
    alert(msg + 'mês inv�lido!');
	return false;}
  if (mm == '02') {
     if (dd > '29') {
	    alert(msg + 'dia inv�lido para o mês informado!');
	    return false;}
	 else if ((dd == '29') && ((aa%4) != 0)) {
	       alert(msg + 'este ano não é bissexto!');
	       return false;}}
  else if ( ((mm == '04')||(mm == '06')||(mm == '09')||(mm == '11')) &&
	         (dd == '31')){alert(msg + 'dia inválido para o mês informado!');
	                       return false;}
  if (aa < 1900){
    alert(msg + 'ano inv�lido!');
	return false;}
  var hoje = new Date();
  var data = new Date();
  data.setDate(dd);
  data.setMonth(mm-1);
  data.setYear(aa);
  if (txt=='abaixo'){
	if (data > hoje){alert(msg + 'data tem que ser menor do que hoje!');
					 return false;}}
  if (txt=='acima'){
    if (data < hoje){alert(msg + 'data tem que ser maior do que hoje!');
					 return false;}}
  return true;
}
 
function testa_data(campo,tipo){
var ValidaData  = /^\d{2}[\/]\d{2}[\/]\d{4}$/;
/*if (campo.value == '') 	{
	alert('Data n�o informada!');
	campo.focus();
	return false;
}*/
if (!ValidaData.test(campo.value)){
	alert('A data deve ser digitada no formato DD/MM/AAAA');
	campo.focus();
	return false;
}
if (!isValidDate(campo.value,tipo)){
	//alert('A data deve ser digitada no formato dd/mm/yyyy');
	campo.focus();
	return false;
}
return true;
}


//fun��o para validar (CNPJ-CGC) ou CPF
function ValidarCPF_CGC(pCampo)
{
	
	if(pCampo.value=='')
	{
		alert('Por favor informe o cpf');
		pCampo.select();
	}
	else
	{
		return pfValidaCPF_CGC(pCampo, 'CPF ou CNPJ inválido');
	}
	
}

function pfValidaCPF_CGC(msCPF_CGC, msMSG)
{
	if (!(checa(cleanNumber(msCPF_CGC.value), msMSG))){
		appendMessage(msCPF_CGC.getAttribute("RIT_Output"),msMSG + " inválido! Favor preencher corretamente.");
		msCPF_CGC.select()
		return false;
	}
	else
	{
		return true; 
	}
}


function checa(msCPF_CGC, msMSG)
{	
	if ((msCPF_CGC.length != 14 || msCPF_CGC == "00000000000000" || msCPF_CGC == "11111111111111" ||
msCPF_CGC == "22222222222222" || msCPF_CGC == "33333333333333" || msCPF_CGC == "44444444444444" ||
msCPF_CGC == "55555555555555" || msCPF_CGC == "66666666666666" || msCPF_CGC == "77777777777777" ||
msCPF_CGC == "88888888888888" || msCPF_CGC == "99999999999999") && (msCPF_CGC.length != 11 || msCPF_CGC == "00000000000" || msCPF_CGC == "11111111111" ||
msCPF_CGC == "22222222222" || msCPF_CGC == "33333333333" || msCPF_CGC == "44444444444" ||
msCPF_CGC == "55555555555" || msCPF_CGC == "66666666666" || msCPF_CGC == "77777777777" ||
msCPF_CGC == "88888888888" || msCPF_CGC == "99999999999"))
	{ 	
		return false;
	}

	if ((!(modulo(msCPF_CGC.substring(0,msCPF_CGC.length - 2)).toString()+modulo(msCPF_CGC.substring(0,msCPF_CGC.length - 1)).toString() == msCPF_CGC.substring(msCPF_CGC.length - 2,msCPF_CGC.length))) && (modulo_cic(msCPF_CGC.substring(0,msCPF_CGC.length - 2)) + "" + modulo_cic(msCPF_CGC.substring(0,msCPF_CGC.length - 1)) != msCPF_CGC.substring(msCPF_CGC.length - 2,msCPF_CGC.length)))
	{		
		return false;
	}
	return true;
}
function modulo(msCPF_CGC)
{
	soma=0;
	ind=2;
	
	for(pos=msCPF_CGC.length-1;pos>-1;pos=pos-1)
	{
		soma = soma + (parseInt(msCPF_CGC.charAt(pos)) * ind);
		ind++;
		
		if(msCPF_CGC.length>11){ 
			if(ind>9) ind=2; 
		}
	}
	
	resto = soma - (Math.floor(soma / 11) * 11);
			
	if(resto < 2)
	{ 
		return 0;
	}
	else{ 
		return (11 - resto);
	}
}

function modulo_cic(msCPF_CGC)
{
	soma=0;
	ind=2;

	for(pos=msCPF_CGC.length-1;pos>-1;pos=pos-1)
	{
			soma = soma + (parseInt(msCPF_CGC.charAt(pos)) * ind);
			ind++;
			
			if(msCPF_CGC.length>11){	
			if(ind>9) ind=2; 
			}
	}				
	
	resto = soma - (Math.floor(soma / 11) * 11);
			
	if(resto < 2)
	{	
		return 0; 
	}
	else{ 
		return 11 - resto;
	}
}



// Função Valida data 
function DataValida(data) {
	// Informa os tipos de carcteres que ser�o aceitos como data
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/; 
	var month, day, year;
	var matchArray = data.match(datePat); // Formato do array 
	
	// Verifica se o array esta preenchido
	if (matchArray == null) {
	alert("Data não está num formato valido(dd/mm/aaaa).")
	return false;
	}
	// Divide a data em 3 partes Dia, mes e ano
	month = matchArray[3]; 
	day = matchArray[1];
	year = matchArray[4];
	// testa se o ano eh menor que 1800
	if (year <1800)
	{
	alert("Este não é um ano válido");
	return false;
	}
	// Testa se o mes esta entre 1 e 12
	if (month < 1 || month > 12) { 
	alert("Mês deve estar entre 1 e 12.");
	return false;
	}
	// Testa se o dia esta entre 1 e 31
	if (day < 1 || day > 31) {
	alert("Dia deve estar entre 1 e 31.");
	return false;
	}
	// testa os meses que tem 30 dias
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
	alert("O Mês "+month+" não tem 31 dias!")
	return false
	}
	// validacao especial pra fevereiro 
	// testa se � bisexto
	if (month == 2) { 
	var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
	// testa se � dia 28 ou 29 de acordo com o resultado acima
		if (day>29 || (day==29 && !isleap)) 
		{
		alert("Fevereiro " + year + " não tem " + day + " dias!");
		return false;
	   }
	}
	alert("Data valida"); 
	return true;  // data valida

}

function Trim(sString) 
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function abreJanela (URL, Largura, Altura){
   window.open(URL,"janela1","width="+Largura+",height="+Altura+",scrollbars=NO")
}


//contador de caracteres de textarea
function getObject(obj) {
   var theObj;
   if(document.all) {
   if(typeof obj=="string") {
           return document.all(obj);
   } else {
           return obj.style;
   }
   }
   if(document.getElementById) {
   if(typeof obj=="string") {
           return document.getElementById(obj);
   } else {
           return obj.style;
   }
   }
   return null;
 }

function Contar(entrada,salida,texto,caracteres) {
  
           var entradaObj=getObject(entrada);
           var salidaObj=getObject(salida);
           var longitud=caracteres - entradaObj.value.length;
  
 if(longitud <= 0) {
           longitud=0;
           texto='<span class="disable"> '+texto+' </span>';
           entradaObj.value=entradaObj.value.substr(0,caracteres);
   }
           salidaObj.innerHTML = texto.replace("{CHAR}",longitud);
   }
//fim contador
