//Arquivos que foram incorporados em geral.js
//
//Modal.js
//formatacao.js
//valida_campos.js
//validaco.js

//*********************************************************
//					Modal.js
//*********************************************************
function CentralizaModal() {
	window.moveTo(parseInt((window.screen.width - document.body.offsetWidth) / 2,10), parseInt((window.screen.height - document.body.offsetHeight) / 2,10));
}	

function fireOnLoad() {
	var iWidth, iHeight = 0;
   bver=navigator.appVersion.split(";");
   if(bver[1].match("5.")){
		window.opener.document.body.attachEvent('onActive', setFocus); }
   else
	{
		window.opener.document.body.attachEvent('onmousemove', setFocus);
	}	
}

function fireOnUnLoad() {
	bver=navigator.appVersion.split(";");
	if(bver[1].match("5.")) {
		window.opener.document.body.detachEvent('onmousemove', setFocus);
	}
    else {
		window.opener.document.body.detachEvent('onActive'); 
	}
}

function setFocus() {

	window.focus();

}
//*********************************************************
//					formatacao.js
//*********************************************************
	function FormataValor(campo,tammax,teclapres) {
		var tecla;
		if (teclapres != null)
			tecla = teclapres.keyCode;
		else tecla = 9;
		vr = campo.value;
		vr = vr.replace( /\//g, "" );
		vr = vr.replace( /\,/g, "" );
		vr = vr.replace( /\./g, "" );
		
		/*if (("0123456789.").indexOf(tecla)==-1){
			vr = '';
			campo.value = vr;
		}*/
		tam = vr.length;
				
		if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }
	
		if ( tecla == 9 || tecla == 8 ){	tam = tam - 1 ; }
			
		if ( tecla == 9 || tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
			if ( tam <= 2 ){ 
		 		campo.value = vr ; }
		 	if ( (tam > 2) && (tam <= 5) ){
		 		campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
		 	if ( (tam >= 6) && (tam <= 8) ){
		 		campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
		 	if ( (tam >= 9) && (tam <= 11) ){
		 		campo.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
		 	if ( (tam >= 12) && (tam <= 14) ){
		 		campo.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
		 	if ( (tam >= 15) && (tam <= 17) ){
		 		campo.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;}
		}		
		
	}		
	
	function FormataFloat(campo,tammax,teclapres) {
		var tecla;
		if (teclapres != null)
			tecla = teclapres.keyCode;
		else tecla = 9;
		vr = campo.value;
		vr = vr.replace( /\//g, "" );
		vr = vr.replace( /\,/g, "" );
		vr = vr.replace( /\./g, "" );
		tam = vr.length;
	
		if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }
	
		if ( tecla == 9 || tecla == 8 ){	tam = tam - 1 ; }
			
		if ( tecla == 9 || tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
			if ( tam <= 2 ){ 
		 		campo.value = vr ; }
		 	if ( (tam > 2) && (tam <= tammax) ){
		 		campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
		}		
		
	}		

	function FormataData(campo,teclapres) {
		var tecla;
		if (teclapres != null)
			tecla = teclapres.keyCode;
		else tecla = 9;
		vr = campo.value;
		vr = vr.replace( /\./g, "" );
		vr = vr.replace( /\//g, "" );
		tam = vr.length + 1;
		if ( tecla != 9 && tecla != 8 ){
			if ( tam > 2 && tam < 5 )
				campo.value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
			if ( tam >= 5 && tam <= 10 )
				campo.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 );
		 }
	}


	function FormataPlaca(campo, teclapres) {
		var tecla;
		campo.value = campo.value.toUpperCase();

		if (teclapres != null)
			tecla = teclapres.keyCode;
		else tecla = 9;

		vr = campo.value;
		tam = vr.length;

		if ( tecla != 9 && tecla != 8 ){
			if ( tam == 3 )
				vr += ' ';
		}

		campo.value = vr;		
	}


    //FUNÇÃO QUE FORMATA CNPJ (99.999.999/9999-99) ENQUANTO O USUARIO DIGITA
	function FormataCgc(campo,tammax,teclapres) {
		var tecla = teclapres.keyCode;
		// vr = document.form[campo].value;
		vr = event.srcElement.value;
		vr = vr.replace( "/", "" );
		vr = vr.replace( "/", "" );
		vr = vr.replace( "/", "" );
		vr = vr.replace( ",", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( "-", "" );
		vr = vr.replace( "-", "" );
		vr = vr.replace( "-", "" );
		vr = vr.replace( "-", "" );
		vr = vr.replace( "-", "" );
		tam = vr.length;
	
		if (tecla == 46) { return; }

		if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }
	
		if (tecla == 8 ){	tam = tam - 1 ; }
			
		if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
			if ( tam <= 2 ){ 
				event.srcElement.value = vr ; }
			if ( (tam > 2) && (tam <= 6) ){
				event.srcElement.value = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ) ; }
			if ( (tam >= 7) && (tam <= 9) ){
				event.srcElement.value = vr.substr( 0, tam - 6 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
			if ( (tam >= 10) && (tam <= 12) ){
				event.srcElement.value = vr.substr( 0, tam - 9 ) + '.' + vr.substr( tam - 9, 3 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
			if ( (tam >= 13) && (tam <= 14) ){
				event.srcElement.value = vr.substr( 0, tam - 12 ) + '.' + vr.substr( tam - 12, 3 ) + '.' + vr.substr( tam - 9, 3 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
			if ( (tam >= 15) && (tam <= 17) ){
				event.srcElement.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ;}
		}		
	}

    //FUNÇÃO QUE FORMATA CPF (999.999.999-99) ENQUANTO O USUARIO DIGITA
	function FormataCpf(campo,tammax,teclapres) {
		var tecla = teclapres.keyCode;
		// vr = document.form[campo].value;
		vr = event.srcElement.value;
		vr = vr.replace( "/", "" );
		vr = vr.replace( "/", "" );
		vr = vr.replace( ",", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( "-", "" );
		vr = vr.replace( "-", "" );
		vr = vr.replace( "-", "" );
		vr = vr.replace( "-", "" );
		vr = vr.replace( "-", "" );
		tam = vr.length;

		if (tecla == 46) { return; }
	
		if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }
	
		if (tecla == 8 ){	tam = tam - 1 ; }
			
		if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
			if ( tam <= 2 ){ 
				event.srcElement.value = vr ; }
			if ( (tam > 2) && (tam <= 5) ){
				event.srcElement.value = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ) ; }
			if ( (tam >= 6) && (tam <= 8) ){
				event.srcElement.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
			if ( (tam >= 9) && (tam <= 11) ){
				event.srcElement.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
			if ( (tam >= 12) && (tam <= 14) ){
				event.srcElement.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
			if ( (tam >= 15) && (tam <= 17) ){
				event.srcElement.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ;}
		}		
	}   
   
    //FUNÇÃO QUE FORMATA CEP (99999-999) ENQUANTO O USUARIO DIGITA
	function MascaraCEP (formato, keypress, objeto)
	{
	campo = eval (objeto);
	if (formato=='CEP')
		{
		caracteres = '01234567890';
		separacoes = 1;
		separacao1 = '-';
		conjuntos = 2;
		conjunto1 = 5;
		conjunto2 = 3;
		if ((caracteres.search(String.fromCharCode (keypress))!=-1) && campo.value.length < 
		(conjunto1 + conjunto2 + 1))
			{
			if (campo.value.length == conjunto1) 
			   campo.value = campo.value + separacao1;
			}
		else 
			event.returnValue = false;
		}
	}   

    //FUNÇÃO QUE FORMATA TELEFONE (9999-9999) ENQUANTO O USUARIO DIGITA
	function MascaraTelefone (keypress, campo){
		caracteres = '01234567890';
		separacoes = 2;
		separacao1 = ' ';
		separacao2 = ' ';
		conjuntos = 3;
		conjunto1 = 4;
		conjunto2 = 8;
		conjunto3 = 13;
		if ((caracteres.search(String.fromCharCode (keypress))!=-1) && campo.value.length < 
		conjunto3){
			if (campo.value.length == conjunto1){
			   campo.value = campo.value + separacao1;
			} else	if (campo.value.length == conjunto2){
					campo.value = campo.value + separacao2;
			} 
		} else {
			event.returnValue = false;
		}
	} 
//*********************************************************
//					valida_campos.js
//*********************************************************
//regras de validacao (Expressoes Regulares)
if(!self.g_IS&&parent.g_IS)var g_IS=parent.g_IS
if(!self.isArray&&parent.isArray) var isArray = parent.isArray
if(!self.isObject&&parent.isObject) var isObject = parent.isObject
if(!self.isDate&&parent.isDate) var isDate = parent.isDate
if(!self.isString&&parent.isString) var isString = parent.isString
var reSpaces			= /^\s+$/
var reLetra 			= /^[a-zA-Z]$/
var reAlfabetico 		= /^[a-zA-Z]+$/
var reAlfanumerico 		= /^[a-zA-Z0-9]+$/
var reAlfaSpaces		= /^[a-zA-Z0-9\s]+$/
var reDigito 			= /^\d/
var reLetraOuDigito 	= /^([a-zA-Z]|\d)$/
var reInteiro 			= /^\d+$/
var reSinalInteiro 		= /^(\+|\-)?\d+$/
//Corrigido para suportar pontos
//var reDecimais	 	= /((^\d*),?$)|((^\d*),(\d*)$)/
var reDecimais	 		= /[0-9]$|^\.$/
var reSinalDecimais     = /^(\+|\-)?((\d*,?$)|(\d*,\d*$))/
var re2Decimais			= /(^\d*,?$)|(^\d*,\d{1,2}$)/
var reSinal2Decimais    = /^(\+|\-)?((\d*,?$)|(\d*,\d{1,2}$))/
var re4Decimais			= /(^\d*,?$)|(^\d*,\d{1,4}$)/
var reSinal4Decimais    = /^(\+|\-)?((\d*,?$)|(\d*,\d{1,4}$))/
var re7Decimais			= /(^\d*,?$)|(^\d*,\d{1,7}$)/
var reSinal7Decimais    = /^(\+|\-)?((\d*,?$)|(\d*,\d{1,7}$))/
var reEmail 			= /^.+\@.+\..+$/
var reSN				= /^[SNsn]$/
var reCPFCGC            = /(^(\d{3})\W?(\d{3})\W?(\d{3})\W?(\d{2})$)|(^(\d{8})\W?(\d{4})\W?(\d{2})$)/ 
var feCPFCGC			= "$2$3$4$5$7$8$9"
var fsCPFCGC			= "$2$3$4$5$7$8$9"
var reCPF               = /^(\d{3})\W?(\d{3})\W?(\d{3})\W?(\d{2})$/ 
var fsCPF				= "$1.$2.$3-$4"
var feCPF				= "$1$2$3$4"
var reCGCMF             = /^(\d{8})\W?(\d{4})\W?(\d{2})$/
var fsCGCMF				= "$1/$2-$3"
var feCGCMF				= "$1$2$3"
var reCEP				= /^(\d{5})\W?(\d{3})$/
var reCEP5				= /^\d{5}$/ 
var feCEP				= "$1-$2"
var fsCEP				= "$1-$2"
var reIERS              = /^(\d{3})\W?(\d{3})\W?(\d{4})$/
var fsIERS				= "$1/$2$3"
var feIERS				= "$1$2$3"
var reData		    	= /^(([0]?[1-9])|([1,2]\d)|([3][0,1]))\W?(([0]?[1-9])|([1][0-2]))\W?([1-9][0-9]{1,3})$/
var fsData				= "$1/$5/$8"
var feData				= "$1$5$8"
var reMMAAAA		    = /^(([0]?[1-9])|([1][0-2]))\W?([1-9]\d{3})$/
var fsMMAAAA			= "$1/$4"
var feMMAAAA			= "$1$4"
var reDDMMAAAA			= /^(([0]?[1-9])|([1,2]\d)|([3][0,1]))\W?(([0]?[1-9])|([1][0-2]))\W?([1-9][0-9]{3})$/
var fsDDMMAAAA			= "$1/$5/$8"
var feDDMMAAAA			= "$1$5$8"
var reDDMMAA			= /^(([0]?[1-9])|([1,2]\d)|([3][0,1]))\W?(([0]?[1-9])|([1][0-2]))\W?([0-9][0-9]{1})$/
var fsDDMMAA			= "$1/$5/$8"
var feDDMMAA			= "$1$5$8"
var reDDMM				=/^(([0]?[1-9])|([1,2]\d)|([3][0,1]))\W?(([0]?[1-9])|([1][0-2]))$/
var feDDMM              = "$1$5"
var fsDDMM              = "$1/$5"
var reDia				=/^(([0]?[1-9])|([1,2]\d)|([3][0,1]))$/ 
var reMes				=/^(([0]?[1-9])|([1][0-2]))$/ 
var reAno4				=/^[1-9][0-9]{3}$/
var reAno2				=/^[0-9][0-9]{1}$/
var reCtaCtb			=/^(\d{1})\W?(\d{2})\W?(\d{2})\W?(\d{4})$/
var feCtaCtb			="$1$2$3$4"
var fsCtaCtb			="$1.$2.$3.$4"
var reRubrica           =/^(\d{4})$/
var reProjSub	   		=/^(\d{4})\W?(\d{3})$/
var feProjSub			="$1$2"
var fsProjSub			="$1.$2"
var reProcesso			=/^(\d{6})\W?(\d{4})\W?(\d{2})\W?(\d)$/
var feProcesso			="$1$2$3$4"
var fsProcesso			="$1.$2.$3-$4"
var reUO				=/^(\d{2})\W?(\d{2})$/
var feUO				="$1$2"
var fsUO				="$1.$2"
var reClassRec			=/^(\d{4})\W?(\d{2})\W?(\d{3})$/
var feClassRec			="$1$2$3$"
var fsClassRec			="$1.$2.$3"
var reCurrency			= /^(R\$\s*)?(([0-9]{1,3})+(\,([0-9]{2}$)))/;
var feCurrency			="$2"
var fsCurrency			="R$ $2"

// usar no onkeyUp -  realiza avanco automatico - nao impede o avanco com tab para outro campo
// para isso combinar com onBlur
//
var impPararNoUltimo=true  				 // Usado para fazer ciclo : false= retorna ao primeiro - true = trava no ultimo campo 

function impAutoTab(input,tam, e,reBusca,fsSaida) { //netscape nao tem .maxLength o que exige reinformar 'len'
	var keyCode = (g_IS.ns4) ? e.which : e.keyCode; 
	var filter = (g_IS.ns4) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	if(reBusca!=null&&fsSaida!=null) {
			input.value=input.value.replace(reBusca,fsSaida)
	}
	if(input.value.length >= tam && impContainsElement(filter,keyCode)==-1) {
		input.value = input.value.slice(0, tam);
		impAvancaCampo(input);
	}
	return true;
}

function ElementoNoDivEscondido(obj){
	divEscondido=false
	toTop = false
	newType=obj.parentNode
	newTypeTagName=newType.tagName
	while (newTypeTagName!="BODY"){
		if (newTypeTagName=="DIV") {
			if ((newType.style.visibility=="hidden")||(newType.style.display=="none")){
				divEscondido=true
				return divEscondido
			}
		} 
		newType=newType.parentNode
		newTypeTagName=newType.tagName
	} 
	return divEscondido
}

function aceitarApenas(obj,filtro) {
	switch (filtro) {
		case "currency" :
			str = "0123456789,-";
			break;
		case "numero" :
			str = "0123456789";
			break;
		case "letras" :
			str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzÁÉÍÓÚÀÈÌÒÙÄËÏÖÜÂÊÎÔÛÃÕáéíóúàèìòùäëïöüâêîôûãõçÇ&ªº'\"\|@_<>!#$%&*()={[}]?:+-.,;/\\0123456789 ";
			break;
		default :
			str = filtro;
			break;
	}
	if (str.indexOf(String.fromCharCode(event.keyCode)) < 0) {
		event.keyCode = ""
	}
}

function impValMainframe(e){
	var Tecla = event.keyCode;
	var msg = false;
	if (impValMainframe.arguments.length > 0)
		msg = impValMainframe.arguments[1];
	if((Tecla >= 35 && Tecla <= 38) || (Tecla >= 40 && Tecla <= 43) || (Tecla >= 45 && Tecla <= 93) || (Tecla == 33) || (Tecla < 20) || (Tecla == 32))
		return;

	if(Tecla >= 97 && Tecla <= 122)
	{
		event.keyCode -= 32;
		return;
	}
	if(msg)
		alert("Caracter inválido!")
	event.returnValue = false;	
}

function impAvancaCampo(input){	
	var ultimoIndexValido=impGetIndex(input)  
	var newIndex=impGetProxIndex(input) //deve accelerar o script por não chamar o impGetProxIndex 4 vezes no while
	var oldIndex=-1    					//para poder comparar repetiçao do index-> chegou no ultimo campo->voltar para ultimo campo valido
	while ((input.form[newIndex].type == "button") || (input.form[newIndex].readOnly)|| (input.form[newIndex].disabled) || (ElementoNoDivEscondido(input.form[newIndex])))
	{
		if (oldIndex==newIndex)  {
			input.form[ultimoIndexValido].focus();
			return 
		}
		input=input.form[newIndex];
		oldIndex=newIndex
		newIndex=impGetProxIndex(input)   
	}
	input.form[newIndex].focus();
	return 
}
function impGetProxIndex(input){
		var ind=impGetIndex(input)
		var indpx=ind;
		var flag =impPararNoUltimo // Evita loop infinito em forms com camo hidden
		do {//ignorar campos hidden
			if( ++indpx==input.form.length){ //rodar no form (do ultimo para o primeiro)
				if (flag){
					indpx=ind;
					break
				}
				indpx= 0;     
				flag=true;
			}
		} while(input.form[indpx].type=='hidden');
		return indpx
	}
	
//usar no onfocus=impReadonly(this) e no onkeyup=impReadonly(this) - readonly para netscape	
function impReadonly(obj){
	if(!obj.defaultvalue)obj.defaultvalue=obj.value
	obj.value=obj.defaultvalue
}
// verifica existencia de 'ele' no array 'arr'
function impContainsElement(arr, ele) {
		var found = -1, index = 0;
		while(found==-1 && index < arr.length){
			if(arr[index] == ele){
				found = index;
			}
			else {
				index++;
			}
		}
		return found;
	}
//obtem posicao atual do campo no forms
function impGetIndex(input) {
		var index = -1, i = 0, found = false;
		while (i < input.form.length && index == -1)
			if (input.form[i] == input)index = i;
			else i++;
		return index;
}

// usar no onBlur - inpede passagem para outro campo se nao bate com formato
// 
//substitui todas as ocorrencias de uma string expressão regular por outra


function formatDMA(sStr,numZeros){	//Completa Zeros - para impFormatCampo
	var  i, sRes;
	if (sStr.length < numZeros && sStr.length > 0)
		for (i=sStr.length;i < numZeros; i++)
			sStr = "0" + sStr;
			
	return sStr;	
}

function impFormatCampo(campo, reBusca, sTroca,umavez,ignorecase)
{
	// - Completa Zeros em Dia e Mês
	var arrDMA
	arrDMA = campo.value.split("/");
	if (arrDMA.length>2)
	campo.value = formatDMA(arrDMA[0],2)+"/"+formatDMA(arrDMA[1],2)+"/"+arrDMA[2];	// DD/MM/AAAA
	// - - - 
	
    campo.value=impFormat(campo.value, reBusca, sTroca,umavez,ignorecase) 
	campo.select()
}

//função de validação de cnpj
function validaCNPJ(objCampo, bolMostraMsg) 
{ 
	var CNPJ = objCampo.value; 
	var Qtd=CNPJ.length; 
	if (Qtd<14 && Qtd>0){ 
		if(bolMostraMsg)
			alert("Quantidade de dígitos de CNPJ inválido !!!!"); 
		return false; 
	}
	var Dg1=CNPJ.substr(12,1); 
	var Dg2=CNPJ.substr(13,1); 
	var a, i, d1,d2,j; 
// ***************************** 
// * calcula o primeiro digito * 
// ***************************** 
	j=5;a=0;i=0;d1=0; 
	for(i=1;i<=12;i++){ 
		a=a+(CNPJ.substr(i-1,1)*j); 
		if (j>2){j=j-1} 
		else{j=9} 
	} 
	a=a%11 
	if (a>1){d1=11-a} 
	else{d1=0} 
// **************************** 
// * calcula o segundo digito * 
// **************************** 
	j=6;a=0;i=0;d2=0; 
	for(i=1;i<=13;i++){ 
		a=a+(CNPJ.substr(i-1,1)*j); 
		if (j>2){j=j-1} 
		else{j=9} 
	} 
	a=a%11 
	if (a>1){d2=11-a} 
	else{d2=0} 
	if (d1==Dg1 && d2==Dg2){return true} 
	else{
		if(bolMostraMsg)
			alert("CNPJ inválido !!!"); 
		return false
	} 
} 


// Funções de validação - CPF
// true = ok
// false = com erro
// 0 = vazio
function impValCPFCGC(field,bmsg,itipo) {
    var atipo=["CPF/CNPJ","CPF","CNPJ"]
    itipo=(itipo)?itipo:0 //0=qualquer, 1=cpf,2=cgc   
	var cpf='', cgc='', digito='',dg='', dgc='', digitoc='', k=0; i=0, j=0, soma=0, mt=0;
	if (field.value=='') return 0
	var cpfcgc = field.value;
	var bcpf=false
	var bcgc=false
	if (itipo==0||itipo==1) bcpf= reCPF.test(cpfcgc)	// valida tamanho e formato do CPF
	if (itipo==0||itipo==2) bcgc= reCGCMF.test(cpfcgc)	// valida tamanho e formato do CCG
	if ((!bcpf)&&(!bcgc)){// formato não reconhecido
	 	 if(bmsg) alert ("Conteúdo informado não reconhecido como "+atipo[itipo]+"\nVerifique sua digitação")
		 field.select();field.focus();
		 return false 
	 }
// tirar separadores
if (bcpf){cpfcgc=cpfcgc.replace(reCPF,feCPF) }
else     {cpfcgc=cpfcgc.replace(reCGCMF,feCGCMF)} 
//valida entradas fáceis
var cpferr = "0000000000011111111111222222222223333333333344444444444"+
             "5555555555566666666666777777777778888888888899999999999"
if ( cpferr.indexOf(cpfcgc)>=0){// informado campo de facil entrada
	 	 if(bmsg) alert ("Conteúdo não é aceito como "+atipo[itipo]+"\nVerifique sua digitação")
		 field.select();field.focus();
		 return false 
	 }
mult = [2,3,4,5,6,7,8,9,2,3,4,5,6,7,8,9]; // tabela de pesos para colunas 
if (bcgc)
	{  	cgc = cpfcgc.substring(0,12);
		digito = cpfcgc.substring(12,14);
		for (j = 1; j <= 2; j++) {
		    digitoc = impCalcDig11(cgc)
		    if (digitoc == 10){digitoc = 0}
		    dgc +=digitoc;
			cgc+=digitoc;
		}
  }
  else {
	  cpf = cpfcgc.substring(0,9);
	  digito = cpfcgc.substring(9,11);
	  for (j = 1; j <= 2; j++) {
	    soma = 0;
	    mt = 2;
	    for (i = 8 + j; i >= 1; i--) {
	      soma += parseInt(cpf.charAt(i-1),10) * mt;
	      mt++;
	    }
	    dg = 11 - (soma % 11);
	    if (dg > 9) {dg = 0};
	    cpf += dg;
		dgc+=dg
	  }
  } 
  if (dgc != digito) {// digito inválido
	 	 if(bmsg) alert (((bcgc)?"CNPJ":"CPF")+" com dígitos inválidos\nVerifique sua digitação")
		 field.select();field.focus();
		 return false 
	 }
  else {
   field.value=impFormat(field.value,((bcgc)?reCGCMF:reCPF),((bcgc)?fsCGCMF:fsCPF))
   return true }
 
  }
// valida digito do inscrição estadual
// 0 = CAMPO vazio
// true = ok
// false = erro
function impValIERS(field,bmsg) {
var dg='',ie='',IERS='',dgc=''
if (field.value=='') return 0
var IERS = field.value;
bIERS= reIERS.test(IERS)	// valida tamanho e formato do CPF
if (!bIERS){// formato não reconhecido
	 	 if(bmsg) alert ("Conteúdo informado não reconhecido como Inscrição Estadual -RS\nVerifique sua digitação")
		 field.select();field.focus();
		 return false 
	 }
IERS=impFormat(IERS,reIERS,feIERS)
ie=IERS.substring(0,9)
dg=IERS.substring(9)
dgc=impCalcDig11(ie)
if (dgc==10) dgc=0
if (dg!=dgc) {// Dígito inválido
	 	 if(bmsg) alert ("Inscrição Estadual com dígitos inválidos\nVerifique sua digitação")
		 field.select();field.focus();
		 return false 
	 }
else  {
   field.value=impFormat(field.value,reIERS,fsIERS)
   return true }
 
}
//digito módulo 11 - pode retornar digito 10  para verificação de aproveitamento
// 					 
function impCalcDig11(numero)
{var pesos=[2,3,4,5,6,7,8,9,2,3,4,5,6,7,8,9]
 var calc= 0 , x=''
 var numero=String(numero).split("")
 var limite=numero.length -1
 var result = 0
 var pso=0
 for (var i=limite; i>=0; i--)
 { x+="\npso:"+pesos[pso]+" * "+ numero[i] + " = " + (pesos[pso] * parseInt(numero[i]))
   calc += (pesos[pso++] * parseInt(numero[i]))
 } 
 result = 11 - ((calc)%11)
  if (result == 11){result = 0}
  return result	 
  
}

function validaPeriodo(iBDtipo, Ano, Mes, Dia){
	switch (parseInt(iBDtipo)) {
		case 0 :	//smalldatetime
			if (Ano < 1900)	{return false}		
			if (Ano > 2079)	{return false}	
			if ((Ano == 2079) && (Mes > 6))	{return false}
			if ((Ano == 2079) && (Mes == 6) && (Dia > 6)){return false}	
			break;
		case 1 :	//datetime
			if (Ano < 1753)	{return false}		
			if (Ano > 9999)	{return false}		
			break;		
	}
	return true;
}

// Valida datas
// true = ok
// false = com erro
// 0 = vazio
  function impValData(field,bmsg,itipo,iBDtipo) {
  	if (field.value==""){return 0};
    var atipo=["data","dd/mm/aa","dd/mm/aaaa","dd/mm","mm/aaaa"]
    iBDtipo=(iBDtipo)?iBDtipo:0 //0=smalldatetime (default), 1=datetime
    itipo=(itipo)?itipo:0 //0=qualquer, 1=dmaa,2=dmaaaa,3=ddmm,4=mmaaaa   
    var bformatoData = formatoData(field.value)
	var bDDMMAA 	=((bformatoData==1)&&(itipo==0||itipo==1))
	var bDDMMAAAA	=((bformatoData==2)&&(itipo==0||itipo==2))
	var bDDMM 		=((bformatoData==3)&&(itipo==0||itipo==3))
	var bMMAAAA		=((bformatoData==4)&&(itipo==0||itipo==4))

	if ((!bDDMMAA)&&(!bDDMMAAAA)&&(!bDDMM)&&(!bMMAAAA)){// formato não reconhecido
	 	 if(bmsg) alert ("Conteúdo informado não reconhecido como sendo "+atipo[itipo]+"\nVerifique sua digitação")
		 field.select();field.focus();
		 return false 
	 }
  	var dia0,mes0,ano0
  	var auxData;
  	var dData=""
	var dHoje=new Date()
	
	if (bDDMMAAAA) dData = impFormat(field.value,reDDMMAAAA,fsDDMMAAAA);
  	else if (bDDMMAA) dData = impFormat(field.value,reDDMMAA,fsDDMMAA);
		 else dData=impFormat(field.value+"/"+dHoje.getFullYear(),reDDMMAAAA,fsDDMMAAAA)
		 	  if (bMMAAAA) dData=impFormat(field.value,reMMAAAA,fsMMAAAA) //MMAAAA

  	dma=dData.split("/")
	
	if (bDDMMAA){dma[2]= (dma[2]<20)?parseInt(dma[2])+2000:parseInt(dma[2])+1900} // janelamento de data
	
	if (bMMAAAA){dma[2]= dma[1];  dma[1]= dma[0];} //ajusta array comparativo para MMAAAA

	if(!validaPeriodo(iBDtipo, dma[2], dma[1], dma[0])){
	alert ("Data inválida")
		 field.select();field.focus();
		 return false 	
	}
		
	var obj = new Date(dma[2], dma[1]-1, dma[0])//cria data no browser


	dma[0]= "00" + dma[0]
	dma[1]= "00" + dma[1]
	dma[2]= "0000" + dma[2]
  	dma[0] = dma[0].substr(dma[0].length-2) 
  	dma[1] = dma[1].substr(dma[1].length-2)
  	dma[2] = dma[2].substr(dma[2].length-4)
  	dData=dma.join("/")
	
	dia0 = "00" + obj.getDate()
  	mes0 = "00" + (obj.getMonth()+1)
  	ano0 = "0000" + obj.getFullYear()
  	dia0 = dia0.substr(dia0.length-2) 
  	mes0 = mes0.substr(mes0.length-2)
  	ano0 = ano0.substr(ano0.length-4)
	if (bMMAAAA)
		{ auxData =  mes0 + "/"+ ano0
		  dData = dma[1] + "/"+ dma[2]}
	else{ auxData = dia0 + "/"+  mes0 + "/"+ ano0}

	if ((auxData != dData)) { 
		if (bmsg) alert("Data incorreta\nVerifique sua Digitação")
		field.select();field.value='';field.focus();
		return false     
	}
  	else {  if (bMMAAAA){field.value=mes0+"/"+ano0}
			else 		{field.value=dia0+"/"+mes0+((itipo==3)?"":("/"+((itipo==1)?ano0.substring(ano0,2):ano0)))}
			return true}
  }
function impValDataCalendario(field,bmsg,itipo,iBDtipo) {
  	if (field.value==""){return 0};
    var atipo=["data","dd/mm/aa","dd/mm/aaaa","dd/mm","mm/aaaa"]
    iBDtipo=(iBDtipo)?iBDtipo:0 //0=smalldatetime (default), 1=datetime
    itipo=(itipo)?itipo:0 //0=qualquer, 1=dmaa,2=dmaaaa,3=ddmm,4=mmaaaa   
    var bformatoData = formatoData(field.value)
	var bDDMMAA 	=((bformatoData==1)&&(itipo==0||itipo==1))
	var bDDMMAAAA	=((bformatoData==2)&&(itipo==0||itipo==2))
	var bDDMM 		=((bformatoData==3)&&(itipo==0||itipo==3))
	var bMMAAAA		=((bformatoData==4)&&(itipo==0||itipo==4))

	if ((!bDDMMAA)&&(!bDDMMAAAA)&&(!bDDMM)&&(!bMMAAAA)){// formato não reconhecido
	 	 if(bmsg) alert ("Conteúdo informado não reconhecido como sendo "+atipo[itipo]+"\nVerifique sua digitação")
		 field.select();field.value='';field.focus();
		 return false 
	 }
  	var dia0,mes0,ano0
  	var auxData;
  	var dData=""
	var dHoje=new Date()
	
	if (bDDMMAAAA) dData = impFormat(field.value,reDDMMAAAA,fsDDMMAAAA);
  	else if (bDDMMAA) dData = impFormat(field.value,reDDMMAA,fsDDMMAA);
		 else dData=impFormat(field.value+"/"+dHoje.getFullYear(),reDDMMAAAA,fsDDMMAAAA)
		 	  if (bMMAAAA) dData=impFormat(field.value,reMMAAAA,fsMMAAAA) //MMAAAA

  	dma=dData.split("/")
	
	if (bDDMMAA){dma[2]= (dma[2]<20)?parseInt(dma[2])+2000:parseInt(dma[2])+1900} // janelamento de data
	
	if (bMMAAAA){dma[2]= dma[1];  dma[1]= dma[0];} //ajusta array comparativo para MMAAAA

	if(!validaPeriodo(iBDtipo, dma[2], dma[1], dma[0])){
	alert ("Data inválida")
		 field.select();field.value='';field.focus();
		 return false 	
	}
		
	var obj = new Date(dma[2], dma[1]-1, dma[0])//cria data no browser


	dma[0]= "00" + dma[0]
	dma[1]= "00" + dma[1]
	dma[2]= "0000" + dma[2]
  	dma[0] = dma[0].substr(dma[0].length-2) 
  	dma[1] = dma[1].substr(dma[1].length-2)
  	dma[2] = dma[2].substr(dma[2].length-4)
  	dData=dma.join("/")
	
	dia0 = "00" + obj.getDate()
  	mes0 = "00" + (obj.getMonth()+1)
  	ano0 = "0000" + obj.getFullYear()
  	dia0 = dia0.substr(dia0.length-2) 
  	mes0 = mes0.substr(mes0.length-2)
  	ano0 = ano0.substr(ano0.length-4)
	if (bMMAAAA)
		{ auxData =  mes0 + "/"+ ano0
		  dData = dma[1] + "/"+ dma[2]}
	else{ auxData = dia0 + "/"+  mes0 + "/"+ ano0}

	if ((auxData != dData)) { 
		if (bmsg) alert("Data incorreta\nVerifique sua Digitação")
		field.select();field.focus();field.value='';
		return false     
	}
  	else {  if (bMMAAAA){field.value=mes0+"/"+ano0}
			else 		{field.value=dia0+"/"+mes0+((itipo==3)?"":("/"+((itipo==1)?ano0.substring(ano0,2):ano0)))}
			return true}
  }  
  
function dma2amd(sdata)
{	dma=sdata.split("/")
	if (dma.length==2){
		var dHoje=new Date()
		dma[2]=dHoje.getFullYear()
	}
	dma[0]= "00" + dma[0]
	dma[1]= "00" + dma[1]
	dma[2]= "0000" + dma[2]
	dma[0] = dma[0].substr(dma[0].length-2) 
	dma[1] = dma[1].substr(dma[1].length-2)
	dma[2] = dma[2].substr(dma[2].length-4)
	return dma[2]+"/"+dma[1]+"/"+dma[0]
}
function limpaNum(num){
num=""+num+""
var temp=num.replace(/\./g,"")
return temp.replace(/\,/g,".")
}

function LimpaEspacosCampo(obj) {
	if ((!obj) || (obj.type == null)) return;
	obj.value = LimpaEspacosTexto(obj.value)
}

function LimpaEspacosTexto(str) {
	if (!str) return str;
	return str.replace(/\s+/g," ")
}
function formatoData(data){
	if  (bMMAAAA=reMMAAAA.test(data)) return 4	
	if  (reDDMMAA.test(data))  return 1
	if  (reDDMMAAAA.test(data)) return 2
	if  (bDDMM=reDDMM.test(data)) return 3
	return false
}
/*
function difData(data1,data2){
var fdata1=formatoData(data1)
var fdata2=formatoData(data2)
if (!formatoData(data1)){
	alert(data1+" não é de formato dd/mm/aa, dd/mm/aaaa ou dd/mm")
	return false
}
if (!formatoData(data2)){
	alert(data2+" não é de formato dd/mm/aa, dd/mm/aaaa ou dd/mm")
	return false
}
if (fdata1!=fdata2){
	alert ('datas não estão no mesmo formato:\n'+data1+" / "+data2)
}
	var bDDMMAA 	=(fdata1==1)
	var bDDMMAAAA	=(fdata1==2)
	var bDDMM 		=(fdata1==3)
if (bDDMMAAAA) 
{ data1 = impFormat(data1,reDDMMAAAA,fsDDMMAAAA);
  data2=impFormat(data2,reDDMMAAAA,fsDDMMAAAA);
}
else
{ 	if (bDDMMAA) 
	{data1 = impFormat(data1,reDDMMAA,fsDDMMAA);
	 data2=  impFormat(data2,reDDMMAA,fsDDMMAA);
	}
	 else{
	 data1=impFormat(data1+"/"+dHoje.getFullYear(),reDDMMAAAA,fsDDMMAAAA)
	 data2=impFormat(data2+"/"+dHoje.getFullYear(),reDDMMAAAA,fsDDMMAAAA)
	 }
}
dma1=data1.split("/");dma2=data2.split("/")
var b= new Date(dma2[2], dma2[1]-1, dma2[0]) 
var a= new Date(dma1[2], dma1[1]-1, dma1[0])
return (b.getTime() - a.getTime())/(24 * 60 * 60 * 1000)//nro de dias de diferença a partir dos milisegundos desde 1970
}
*/

//=====================================================================
//Função  : mascaraValor(campo)
//Parâmetros : campo - nome do campo do formulário a ser mascarado.
//      digitos - quantidade de dígitos, incluindo os decimais.
//Autor   : Fábio Augusto Barcellos
//Data   : 25/07/2001
//Modo de uso : no campo do form que terá valor monetário, use:
//      onKeyUp="mascaraValor(this)"
//=====================================================================
function impMaskCurrency(campo, digitos) {
 var valor = campo.value;
 
 // se o usuário limpou o campo
 if(valor.length==0)
  return;
 
 var strSinal="";
 if(valor.substr(0,1)=="-") {
  strSinal = "-";
 }
 
 // elimina qualquer caracter não numérico
 valor = valor.replace(/[^0-9_]/gi,"");
  
 // se atingiu o tamanho máximo, retorna
 if(valor.length>digitos) {
  valor = valor.substr(0,digitos);
  alert("Limite do tamanho do campo atingido");
 }
 
 // se o usuário só digitou zeros
 if(parseFloat(valor)==0.00) 
  valor = '000';
 
 // garante que há 3 dígitos
 while (valor.length<3)
  valor = '0' + valor;
  
 // elimina zeros colocados no início do número.
 if(valor.length==4 && valor.substr(0,1) == "0")
  valor=valor.substr(1);
 else if((valor.length>4))
  valor=limpaZerosEsquerda(valor,1);
 
 var novoVal = '';
 // pega primeiro as casas decimais
 novoVal = "," + valor.substr(valor.length-2, 2);
 
 // remonta valor sem os últimos dois números
 valor = valor.substr(0,valor.length-2);
 
 // percorre os digitos para formatação
 var i=1;
 for(i=1; valor.length>0; i++) {
  novoVal = valor.substr(valor.length-1,1) + "" + novoVal;
  valor = valor.substr(0,valor.length-1);
  
  // se passou por três caracteres e ainda há mais dígitos, coloca um ponto agrupador
  if((i%3==0) && (valor.length>0))
   novoVal = "." + novoVal;
 }
 
 campo.value = strSinal + '' + novoVal;
}

function impValCurrency(obj,foco){
	if (foco) {
		if (obj.value.indexOf("R$ ") == 0) {
			obj.value = obj.value.substr(3,obj.value.length)
			obj.select()
		}
	} else {
		if ((!obj || obj != '[object]') || (obj.value == "") || (obj.value.indexOf(",") > 0 && obj.value.length > obj.value.indexOf(",") + 2) && (obj.value.indexOf("R$ ") >= 0)) {
			return;
		}
		if (obj.value.indexOf(",") > 0) {
			obj.value = "R$ " + obj.value + ("00").substr(0,parseInt((obj.value.indexOf(",") + 3) - obj.value.length))
		} else {
			obj.value = "R$ " + obj.value + ",00"
		}
	}
}

function FormataValCurrency(vlr){
	if (vlr.indexOf(",") > 0) {
		vlr = obj.vlr + ("00").substr(0,parseInt((vlr.indexOf(",") + 3) - vlr.length))
	} else {
		vlr = vlr + ",00"
	}
}


function impValNumerico(obj,str) {
	if (!obj || obj != '[object]') {
		alert("Erro, obj não declarado ou não é objeto.\nLocal: PRInputs.js # impValNumerico.")
		return false
	}
	if (isNaN(obj.value)) {
		if (str) {
			alert("O conteúdo informado para " + str + " deve ser numérico.")
		} else {
			alert("O conteúdo informado deve ser numérico.")
		}
		obj.focus()
		obj.select()
		return false;
	}
	return true
}

function igualaCampos(campo1,campo2) {
	var bSelect = true
	if(campo2.value != ""){return}
	if (igualaCampos.arguments.length==3)
	{
		if (!igualaCampos.arguments[2])
			bSelect = false
	}		
	if (campo1.value.indexOf("/") > 0 || campo2.value.indexOf("/") > 0) {
		if (campo2.value == "") {
			campo2.value = campo1.value
			return;
		}
		var s1, s2, arr1, arr2
		if (campo1.value != "")
			s1 = (campo1.value.split("/"))[2] + (campo1.value.split("/"))[1] + (campo1.value.split("/"))[0]
		if (campo2.value != "")
			s2 = (campo2.value.split("/"))[2] + (campo2.value.split("/"))[1] + (campo2.value.split("/"))[0]
		if (s2 == "" || s2 < s1) {
			campo2.value = campo1.value
			if (campo2.select){
				if (bSelect)
					campo2.select()
			}	
		}
	} else {
		if (campo1.value == "") { return;}
		//igualar considerando floats
		if ((campo2.value == "") || ( parseFloat(limpaNum(campo2.value)) < parseFloat(limpaNum(campo1.value)))) {
		   campo2.value=campo1.value
			if (campo2.select){
				if (bSelect)
					campo2.select()
			}	
		}
	}
}

function valCurrency(obj,nInt,nDig,sMsgErro,fEntrada) {
	if (fEntrada) {
		obj.value.replace(/\,/gi,'');
		obj.select()
		return true;
	}
	if (sMsgErro) { // validação de conteudo
		if (!testeCurrency(obj,nInt,nDig)) {
		  	alert(sMsgErro)
			obj.focus()
			obj.select()
			return false;
		}
		return true;
	} else { // validação no momento da digitação
		sKeyCode = "48,49,50,51,52,53,54,55,56,57,45,44"
		if (sKeyCode.indexOf(event.keyCode) < 0) {
			event.keyCode = ""
			return;
		}
	}
}

function testeCurrency(obj,nInt,nDig) {
		if (obj.value.indexOf("-",1) > 0) {
			return false;
		}
		if (obj.value.split(",").length > 2) {
			return false;
		}
		if (obj.value.split(",").length == 2) {
			if (obj.value.charAt(0) == "-") {
				if (obj.value.split(",")[0].length > nInt+1) {
					return false;
				}
			} else {
				if (obj.value.split(",")[0].length > nInt) {
					return false;
				}
			}
			if (obj.value.split(",")[1].length < nDig) {
					while(obj.value.split(",")[1].length < nDig) { 
					obj.value += "0"
				}
			} else {
				if (obj.value.split(",")[1].length > nDig) {
				t1 = obj.value.split(",")[1].substr(0,nDig)
				t2 = obj.value.split(",")[1].substr(nDig,obj.value.split(",")[1].length)
				tf = "1"
				for (var i = 0 ; i < t2.length; i++) {
					tf += "0"
				}
				if ((tf/t2) > 2) { // é menor que 5
					obj.value = obj.value.split(",")[0] + "," + t1
				}else{
					obj.value = obj.value.split(",")[0] + "," + (parseInt(t1) + 1)
				}
//					alert(Math.round(parseFloat(obj.value.split(",")[1].substr(0,nDig) + ","  + obj.value.split(",")[1].substr(nDig,obj.value.split(",")[1].length))))
				}
			}
		}
		if (obj.value.split(",").length == 1) {
			if (obj.value == "") {
				return true;
			}
			if (obj.value.charAt(0) == "-") {
				if (obj.value.length > nInt+1) {
					return false;
				}
			} else {
				if (obj.value.length > nInt) {
					return false;
				}
			}
			obj.value += ","
			while(obj.value.split(",")[1].length < nDig) { 
				obj.value += "0"
			}
		}
		return true;
}

function limpaZerosEsquerda(inputString,tipo){
// uso: limpaZerosAEsquerda('000123abc')
// usar tipo = 1 para permitir zero
	var outputString  = '';
	var espacosAntes  = 0;
	//tipo = 0
	if (tipo == 1) {
		re = /^0*$/;
		res = inputString.match(re);
		if (inputString.substr(0,1) != "-" && res == null) inic = 0;
		else  inic = 1;
	}
	else inic = 0;
	for(var i = inic ; i < inputString.length ; i++){
		if(inputString.charAt(i) == '0'){ espacosAntes++; }
		else {	break;	}
	}
	outputString =  String(inputString).substr(espacosAntes);
	return outputString;
}

function procuraRepetidos(arr,procura,indice) {
	if (procura) {
		for (var i = indice ; i < arr.length; i++ ) {
			if (arr[i] == procura) {
				return procura
			}
		}
	} else {
		for (var i = 0 ; i < arr.length - 1; i++ ) {
			bRet = procuraRepetidos(arr,arr[i],i+1)
			if (bRet) {
				return bRet
			}
		}
	}
	return false
}

function procuraForaIntervalo(arr,vMin,vMax) {
	if ((!arr) || (!vMin) || (!vMax)) {
		alert("parâmetros errados.")
		return false;
	}
	if (vMin > vMax) {
		alert("Foram passados parâmetros em posições erradas. A função vai funcionar mesmo assim.")
		vTemp = vMax
		vMax = vMin
		vMin = vTemp
	}
	if (!arr.sort) {
		arr = arr.split(",")
	}
	for (var i = 0 ; i < arr.length; i++) {
		if (parseInt(limpaZerosEsquerda(arr[i],1)) < parseInt(limpaZerosEsquerda(vMin)) ||  parseInt(limpaZerosEsquerda(arr[i])) > parseInt(limpaZerosEsquerda(vMax)) || isNaN(limpaZerosEsquerda(arr[i]))) {
			return [arr[i],vMin,vMax]
		}
	}
	return false;
}

function valCampoPesq(obj,Multiplo,valMin,valMax) { //valida numero com ou sem separador virgula no intervalo (numero,[virgula],ini,fim)
	if ((!valMin && valMax) || (valMin && !valMax)) {
		alert("ATENÇÃO !!!\nErro na chamada da função");
		return false;
	}
	if (!valMin && !valMax && !obj) { // valida digitação
		var sKeyCode = "48,49,50,51,52,53,54,55,56,57"
		sKeyCode = (Multiplo)?sKeyCode + ",44":sKeyCode
		if (sKeyCode.indexOf(event.keyCode) < 0) {
			event.keyCode = ""
			return false;
		}
	} else { // valida valor digitado
		if (obj.value == "") { return true;}
		if (!Multiplo) {
			obj.value = limpaZerosEsquerda(obj.value)
			if (obj.value.indexOf(",") >= 0) {
				alert("Esse campo não aceita pesquisa múltipla")
				obj.select(); obj.focus(); return false;					
			}
			if (isNaN(parseInt(obj.value))) {
				alert("O conteúdo do campo não é válido")
				obj.select(); obj.focus(); return false;					
			}
			if (valMin && valMax) {
				if (valMin > valMax) {
					alert("ATENÇÃO. Foram passados parâmetros em posições erradas. A função vai funcionar mesmo assim.")
					valTemp = valMax
					valMax = valMin
					valMin = valTemp
				}
				if ((obj.value < valMin) || obj.value > valMax) {
					alert("O valor digitado esta fora do intervalo válido que é [" + valMin + "," + valMax + "]")
					obj.select(); obj.focus(); return false;					
				}
			}
		} else {
				if (obj.value.indexOf(",")==0){
					alert("O conteúdo do campo não pode começar com vírgula.")
					obj.focus(); return false;					
				}
				if (obj.value.indexOf(",,")>=0){				
					alert("O conteúdo do campo não pode ter vírgulas repetidas.")
					obj.focus(); return false;					
				}	
				if (obj.value.charAt(obj.value.length-1) == ","){				
					alert("O conteúdo do campo não pode terminar com vírgula.")
					obj.focus(); return false;					
				}
			var arrTeste = obj.value.split(",")				
			var sRepet = procuraRepetidos(arrTeste)
			if (sRepet) {
				alert("Dados repetidos : " + sRepet + "\nA pesquisa não pode ser executada.")
				obj.focus()
				return false;
				
			}
			sRepet = procuraForaIntervalo(arrTeste,valMin,valMax)
			if (sRepet) {
				alert("O valor digitado '" + sRepet[0] + "' esta fora do limite [" + sRepet[1] + "," + sRepet[2] + "] ou não é um valor válido.")
				obj.focus()
				return false;
			}
		}
	}
	return true;
}

function difData(d1,d2,tipo) {
	/*
	TIPO :
		Tipo 1 => DD/MM/AA
		Tipo 2 => DD/MM/AAAA
		Tipo 3 => DD/MM
		Tipo 4 => MM/AAAA
	*/
	if (!tipo) {
		return "ERRO - Esta faltando informar o tipo de data"
	}
	var dif = "#ERRO#"
	switch (parseInt(tipo)) {
		case 1 :
			// ================ DD/MM/AA =======================
			if ( !(/^(([0]?[1-9])|([1,2]\d)|([3][0,1]))\W?(([0]?[1-9])|([1][0-2]))\W?([0-9][0-9]{1})$/.test(d1)) || !(/^(([0]?[1-9])|([1,2]\d)|([3][0,1]))\W?(([0]?[1-9])|([1][0-2]))\W?([0-9][0-9]{1})$/.test(d2)) ) {
				return "ERRO - Datas no formato errado"			
			}
			d1 = d1.split("/")
			d2 = d2.split("/")
			d1[2] = (d1[2] <= 19)?"20" + d1[2]:"19" + d1[2]
			d2[2] = (d2[2] <= 19)?"20" + d2[2]:"19" + d2[2]
			dif = (( (new Date(d2[2], (d2[1]-1) , d2[0], 00, 00, 00)) - (new Date(d1[2], (d1[1]-1) , d1[0], 00, 00, 00)) )/86400000)
			return dif
			break;
		case 2 :
			// ================ DD/MM/AAAA =======================
			if ( !(/^(([0]?[1-9])|([1,2]\d)|([3][0,1]))\W?(([0]?[1-9])|([1][0-2]))\W?([1-9][0-9]{3})$/.test(d1)) || !(/^(([0]?[1-9])|([1,2]\d)|([3][0,1]))\W?(([0]?[1-9])|([1][0-2]))\W?([1-9][0-9]{3})$/.test(d2)) ) {
				return "ERRO - Datas no formato errado"
			}
			d1 = d1.split("/")
			d2 = d2.split("/")
			dif = (( (new Date(d2[2], (d2[1]-1) , d2[0], 00, 00, 00)) - (new Date(d1[2], (d1[1]-1) , d1[0], 00, 00, 00)) )/86400000)
			return dif
			break;
		case 3 :
			// ================ DD/MM =======================
			if ( !(/^(([0]?[1-9])|([1,2]\d)|([3][0,1]))\W?(([0]?[1-9])|([1][0-2]))$/.test(d1)) || !(/^(([0]?[1-9])|([1,2]\d)|([3][0,1]))\W?(([0]?[1-9])|([1][0-2]))$/.test(d2)) ) {
				return "ERRO - Datas no formato errado"
			}
			d1 = d1.split("/")
			d2 = d2.split("/")
			dif = (( (new Date(2000, (d2[1]-1) , d2[0], 00, 00, 00)) - (new Date(2000, (d1[1]-1) , d1[0], 00, 00, 00)) )/86400000)
			return dif
			break;
		case 4 :
			// ================ MM/AAAA =======================
			if ( !(/^(([0]?[1-9])|([1][0-2]))\W?([1-9]\d{3})$/.test(d1)) || !(/^(([0]?[1-9])|([1][0-2]))\W?([1-9]\d{3})$/.test(d2)) ) {
				return "ERRO - Datas no formato errado"
			}
			d1 = d1.split("/")
			d2 = d2.split("/")
			dif = (( (new Date(d2[1], (d2[0]-1) , 1, 00, 00, 00)) - (new Date(d1[1], (d1[0]-1) , 1, 00, 00, 00)) )/86400000) // / 30.4366666666666666666666666666666666666666666667
			return dif
			break;
		default :
			return "ERRO - Tipo de Data Informada não é válida"
	}
	return dif;
}

// funcao para tornar campos  readonly caso um campo seja preenchido
// parametros 
// 1° parametro campo a ser verificado
// na sequencia campos a serem colocados como readonly 
// se 1°  parametro for igual a false destrava os campos!, 
// antes era para uma possivel não desabilitação de botão de pesquisa
// exemplos
// onBlur="travaCampo(this,txUO,txUE)
// onBlur="travaCampo(false,this,txUO,txUE)

function travaCampo(){
	var flg

	if (travaCampo.arguments[0].type == "checkbox"){
		if (travaCampo.arguments[0].checked) {
			// campo base contém valor, desabilitar os campos seguintes no 'travaCampo.arguments'
			flg = true
		} else {
		// campo base vazio, habilitar os campos seguintes no 'travaCampo.arguments'
			flg = false
		}
	}else{
		if (travaCampo.arguments[0].value!="") {
		// campo base contém valor, desabilitar os campos seguintes no 'travaCampo.arguments'
			flg = true
		} else {
		// campo base vazio, habilitar os campos seguintes no 'travaCampo.arguments'
			flg = false
		}
	}

	//Mauro em 07/01/2003  
	if (travaCampo.arguments[0]==false) {
		flg = false
	}
	//
	for (var i = 1 ; i < travaCampo.arguments.length; i++ ) {
		travaCampo.arguments[i].readOnly = flg
		travaCampo.arguments[i].disabled = flg
        //Mauro em 06/01/2003                    
        if (flg){
		travaCampo.arguments[i].className = "readonly"	
		}else{
        travaCampo.arguments[i].className = ""	
		}
	   //
	
	obj = travaCampo.arguments[i]
		do {
			obj = obj.nextSibling
			if (obj && obj.type=='button') {
				obj.disabled=flg
			}
		} while (obj && obj.type!='button')
	}
}

function valDtLancto (data,data_Rede) {
// validar dataLancamento.
	arrTempRede = data_Rede.split("/")	
	hoje = new Date(arrTempRede[2], (arrTempRede[1]-1), (parseInt(arrTempRede[0])), 00, 00, 00)	
	hoje = new Date(hoje.getYear(),hoje.getMonth(),hoje.getDate(),00,00,00)

	
	arrTemp = data.split("/")	
	data = new Date(arrTemp[2], (arrTemp[1]-1), (parseInt(arrTemp[0])), 00, 00, 00)	
	
	mes = data.getMonth()
	
	if (hoje.getTime()<data.getTime())
	{	  
	  return false
	}
	else  
	{
		if (hoje.getTime()==data.getTime())
		{
			return true
		}
		else
		{
		
			data = new Date(arrTemp[2], (arrTemp[1]-1), (parseInt(arrTemp[0])+1), 00, 00, 00)
			//data = new Date(arrTemp[2], (arrTemp[1]), (parseInt(arrTemp[0]))+1,00, 00, 00)
		
			if (parseInt(mes) == parseInt(data.getMonth())) { // se somar um dia na data e o mes continuar o mesmo, retorna false			
				return false;
			}
			else {				
				return true	
			}	
		}
	}
	
	
}


function valHora(obj,entrada) {
	if (entrada) {
		obj.value = obj.value.replace(/\:|[a-zA-Z]/g,"")
		obj.select();
	} else {
		if (obj.value == "") return
		obj.value = obj.value.replace(/\:[a-zA-Z]/g,"")
		if (obj.value.length > 4) {
			valHoraErro(obj)
			return false;
		} else {
			if (obj.value.length < 4) {
				obj.value = ("0000").substr(0,(4-obj.value.length)) + obj.value
			}
			var a = obj.value
			if ((parseInt(a.substr(0,2)) > 23) || (parseInt(a.substr(a.length-2,2)) > 59)) {
				valHoraErro(obj)
				return false;
			}
			obj.value = a.substr(0,2) + ":" + a.substr(a.length-2,2)
		}
	}
	return true;
}

function valHoraErro(obj) {
	alert("Conteúdo informado não reconhecido como sendo hora\nVerifique a sua digitação")
	obj.focus();
	obj.select();
}

function resetTabIndex() {
	for ( var i = 0 ; i < document.all.length ; i++) {
		document.all[i].tabIndex = -1
	}
}



function DifMesAno(mesi,anoi,mesf,anof,sMsgErro) {
	if ( (parseFloat(mesi) + anoi*100 ) <= (parseFloat(mesf) + anof*100) ) {
		return true;
	} else {
		if ((mesf !== '') || (anof !== '')){	    
			if (sMsgErro) {
				alert(sMsgErro);
			}
			return false;
		} else {
			return true;
		}
	}
}

/*
Função que trata o retorno de pesquisa auxiliar múltipla

retira os nomes do retorno, evitando problemas de array em 
jscript ocasionados por possíveis virgulas existentes em campos texto

Parâmetros
sObj = Nome do campo ao qual o valor será atribuido
iIndex = Posicao relativa a funcao transf() na página pesquisar_in/pesquisar_Acoes_in 
		 do campo a ser retornado		 
iQtdElem = Quantidade de campos do retorno da pesquisar_in que são numericos

exemplos de chamada :

MontaRetMult('txProjeto',0,4)

para concatenacao de dois campos de retorno 


MontaRetMult('txProjeto',[1,2],4)


*/
function MontaRetMult(sObj, iIndex, iQtdElem){
    var arrStr =""
	var arrStr2
	var arrResp =""
	var arrAux1
	var arrAux2 = new Array()
	
	if (iQtdElem!=1){

	if (this.window.AUXCOMUM.length != 0) {	
	
	for(var i=0;i<this.window.AUXCOMUM.length;i++){
		arrAux1=this.window.AUXCOMUM[i]
	    k=0;		
		
	    for (j=0;j<arrAux1.length;j++) {				
	       if ((!isNaN(arrAux1[j])) && (arrAux1[j]!="")){
   		      arrAux2[k]=arrAux1[j];
			  k++;
		   } 	 
	    }
		this.window.AUXCOMUM[i]=arrAux2
		   arrStr= arrStr + this.window.AUXCOMUM[i] + ","	 	  
   } 
     	  arrStr2=arrStr.split(",")
	
	for(j=0;j<this.window.AUXCOMUM.length ;j++){
		  if (typeof(iIndex)=="object"){
		  	  for (l=0;l<iIndex.length;l++){
	    		 arrResp =arrResp + arrStr2[j *iQtdElem +iIndex[l]] 	     
		 	  }
			  arrResp =arrResp  + ","
	 	}	  	
	 	else
	   	  arrResp =arrResp + arrStr2[j *iQtdElem +iIndex] + ","
	  }  	  
	  pegaObjeto(sObj).value = arrResp.substring(0, arrResp.length -1)
      
	}
	}else{pegaObjeto(sObj).value = this.window.AUXCOMUM
      }
}
//passa o campo e o numeros de zeros a  serem preenchidos a esquerda
//ex : <input type="text" name ="exemplo" onblur="completaZeros(this,4)">
//   para saida tipo 0003
function completaZeros(poTxt,numZeros){
	var sSrt, i;
	sStr = poTxt.value;
	if (sStr.length < numZeros && sStr.length > 0)
		for (i=sStr.length;i < numZeros; i++)
			sStr = "0" + sStr;
			
	poTxt.value = sStr;	

}

// permite entrada somente de numerico
// ex: <input type="text" name ="exemplo" onkeydown="return tcl();"> 
function tcl(e){
if (((event.keyCode > 45) || (event.keyCode == 9) || (event.keyCode == 8) || (event.keyCode == 37) || (event.keyCode == 39))  && (event.keyCode < 58) || ((event.keyCode < 106) && (event.keyCode > 95))){
    return true;
    }else{
	return false;
	}
  }

function RemoveEspacos(campo){
	campo.value=gerTrim(campo.value);
	LimpaEspacosCampo(campo);
	if (campo.value==' ') 
	    campo.value=''
}

function putFocus(oDiv,campo)
{
	parent.Acoes.mAbas.selTab(oDiv);
	campo.focus();
}



//funções genéricas

if (!self.g_IS)g_IS= new Is()
function getStyle(obj){
	if (g_IS.w3c) return obj.style
	else return obj
}
function Is() {
    var agent = navigator.userAgent.toLowerCase();
	this.major = parseInt(navigator.appVersion);
    this.minor = parseFloat(navigator.appVersion);
    this.ns  = ((agent.indexOf('mozilla')!=-1) && ((agent.indexOf('spoofer')==-1) && (agent.indexOf('compatible') == -1)));
    this.ns2 = (this.ns && (this.major == 2));
    this.ns3 = (this.ns && (this.major == 3));
    this.ns4b = (this.ns && (this.minor < 4.04));
    this.ns4 = ((this.ns && (this.major >= 4))&&!(agent.indexOf('netscape6')!=-1));
	this.gek = (agent.indexOf('gecko')!=-1);
	this.ns6 = (agent.indexOf('netscape6')!=-1);
    this.ie   = (agent.indexOf("msie") != -1);
    this.ie3  = (this.ie && (this.major == 2));
    this.ie4  = (this.ie && (this.major == 4));
    this.ie5  = (this.ie && (this.major >= 4));
    this.op  =  (agent.indexOf("opera") != -1);
	this.w3c = ((agent.indexOf('netscape6')!=-1)||(this.ie && (this.major >= 4)));
}
if (g_IS.ns4){
   g_sSTYLE_REF 			= "";
   g_sDOC_REF 				= "document.layers";
   g_sDOC					="document."		// Netscape aceita visibility igual ao Explorer:
   g_sVISIBLE_REF 			= "show"			// setar style visibility como 'visible' ou 'hidden' 
   g_sHIDE_REF				="hide"				// buscar eh que tem diferenca 'show' e 'hide'g_sSTYLE_REF 			= ".style";
}
else{
   g_sSTYLE_REF				= ".style"
   g_sDOC_REF 				= "document.all";
   g_sDOC					=""
   g_sVISIBLE_REF 			= "visible" 	
   g_sHIDE_REF 				= "hidden"		   
}										
//
// funções de acessibilidade =================================================================
function pegaObjeto(sObj,oOrigem){
	if(!oOrigem) 
	{oOrigem=self 
	}
	if(!isObject(oOrigem))
	{ oOrigem=frames[oOrigem]
	  if (!oOrigem)
	     {var sOrigem=oOrigem ;
	     oOrigem=pegaObjeto(sOrigem,self.parent)}
	  if (!oOrigem)
	     {oOrigem=pegaObjeto(sOrigem,self.top);}
	  if (!oOrigem)
	    {alert('erro - frame não localizado:'+sOrigem);return}
	}
	if (g_IS.ns4) // netscape 4
	{   if  (oOrigem.document.forms[sObj])
		{   return oOrigem.document.forms[sObj]
		}
		for (var f=0;f<oOrigem.document.forms.length;f++)
		{   if (oOrigem.document.forms[f].elements[sObj])
			{   return oOrigem.document.forms[f].elements[sObj]
			}
		}
		if (oOrigem.document.images[sObj])
		{	return oOrigem.document.images[sObj]
		}
		if (oOrigem.document.links[sObj])
		{	return oOrigem.document.links[sObj]
		}
		if (oOrigem.document.anchors[sObj])
		{	return oOrigem.document.anchors[sObj]
		}
		if (oOrigem.document.applets[sObj])
		{	return oOrigem.document.applets[sObj]
		}
		if (oOrigem.document.layers[sObj])
		{	return oOrigem.document.layers[sObj]
		}
		var obj=null
		for (var l=0;l<oOrigem.document.layers.length;l++)
		{	obj=pegaObjeto(sObj,oOrigem.document.layers[l])
			if(obj)	return obj
		}
	}
	else 
	{	if (g_IS.ie4) //explorer 4 ou superior
			{if (oOrigem.document.all[sObj]) 
				{return oOrigem.document.all[sObj]}
			}
		else 
		{ 	if (g_IS.w3c) //netscape 6 e explorer 5 (w3c)
			{   var col=oOrigem.document.getElementsByName(sObj)
				if (col.length==1) return col[0]
				if (col.length>1) return col
				if (oOrigem.document.getElementById(sObj))
			 	return oOrigem.document.getElementById(sObj)
			}
	 	}
	}
	if(oOrigem.frames)
	{ 	if (oOrigem.frames[sObj]) return oOrigem.frames[sObj]
		for (var fr=0;fr<oOrigem.frames.length;fr++)
		{	obj=pegaObjeto(sObj,oOrigem.frames[fr])
			if(obj)	return obj
		}
	}
	return
}
// Verifica tipo de dado criado por alguma classe especifica ex: instanceOf([dfsfsd],Array) =true
function instanceOf(obj, constructor) 
{	if (!g_IS.ns4)	{return (eval("obj instanceof constructor"))	}
	while (obj != null) 
	{	if (obj == constructor.prototype) return true;       
		obj = obj.__proto__;
	}
	return false;
}
function isObject(obj){var stobj= typeof obj;return (stobj.indexOf("object")>=0)}
function isString(obj){var stobj= typeof obj;return (stobj.indexOf("string")>=0)}
function isDate(obj) {	return (obj&&obj.year)?true:false;}
function isArray(obj){return (obj&&obj.sort)?true:false}

function dw(div,stexto,frame){
if (!isObject(frame)) 
{ 
	if (frame) {frame=frames[frame];}
	else {frame=self}
}

sframe=(frame.name)?frame.name:((frame.title)?frame.title:frame.id)

if (!isObject(div))
{	oDiv=pegaObjeto(div,frame)
	if(!oDiv){if(top.debug)alert(div+", em "+sframe+" não encontrada");return false}
}
else oDiv=div
if (g_IS.ns4){
	oDiv.document.open(); 
  	oDiv.document.write(stexto);
	oDiv.document.close();
	}
else  	oDiv.innerHTML = stexto;	

/*else if (g_IS.w3c){ //Netscape 6 adotou innerHTML também, senão...
	rng = document.createRange();	rng.setStartBefore(oDiv);	htmlFrag = rng.createContextualFragment(stexto)
	while(oDiv.hasChildNodes()) oDiv.removeChild(oDiv.lastChild);
	oDiv.appendChild(htmlFrag);
	}*/
}
// The code by Captain <cerebrum@iname.com>
// Mead & Company, http://www.meadroid.com/wpm/
// fake print() for IE4.x
if ( !printIsNativeSupport() ){
  window.print = printFrame;
  }

function imprimirPrinc(){  
 	this.focus();
	if (!printIsNativeSupport() )
	  print(this)
	else 
	  window.print();
}

// main stuff
function printFrame(frame, onfinish) {
  if ( !frame ) frame = window;
  if ( frame.document.readyState !== "complete" &&
       !confirm("A página ainda não está completa! Continuar a impressão?") )
  {
    if ( onfinish ) onfinish();
    return;
  }

  if ( printIsNativeSupport() ) {
    /* focus handling for this scope is IE5Beta workaround,
       should be gone with IE5 RTM.
    */
    var focused = document.activeElement; 
    frame.focus();
    frame.self.print();
    if ( onfinish ) onfinish();
    if ( focused && !focused.disabled ) focused.focus();
    return;
  }

  var eventScope = printGetEventScope(frame);
  var focused = document.activeElement;

  window.printHelper = function() {
    execScript("on error resume next: printWB.ExecWB 6, 1", "VBScript");
    printFireEvent(frame, eventScope, "onafterprint");
    printWB.outerHTML = "";
    if ( onfinish ) onfinish();
//    if ( focused && !focused.disabled ) focused.focus();
    window.printHelper = null;
  }

  document.body.insertAdjacentHTML("beforeEnd",
    "<object id=\"printWB\" width=0 height=0 \
    classid=\"clsid:8856F961-340A-11D0-A96B-00C04FD705A2\"></object>");

  printFireEvent(frame, eventScope, "onbeforeprint");
  frame.focus();
  window.printHelper = printHelper;
  setTimeout("window.printHelper()", 0);
}
// helpers
function printIsNativeSupport() {
  var agent = window.navigator.userAgent.toLowerCase();
  if  ((agent.indexOf('mozilla')!=-1) && (parseInt(navigator.appVersion) >= 4) && (agent.indexOf('spoofer')==-1) && (agent.indexOf('compatible') == -1))
    return true;
  var i = agent.indexOf("msie ")+5;
  return parseInt(agent.substr(i)) >= 5 && agent.indexOf("5.0b1") < 0;
}

function printFireEvent(frame, obj, name) {
  var handler = obj[name];
  switch ( typeof(handler) ) {
    case "string": frame.execScript(handler); break;
    case "function": handler();
  }
}

function printGetEventScope(frame) {
  var frameset = frame.document.all.tags("FRAMESET");
  if ( frameset.length ) return frameset[0];
  return frame.document.body;
}


//- funções de navegação ======================================================================
 
function gerAjuda(sPagina){
sPagina=(sPagina!=null)?sPagina:Dados.document.title
 return window.open(g_sDIR_AJUDA+ sPagina,"AjudaWin","width=340,height=385,scrollbars=yes,dependent");
}

var AUXCOMUM ;

function gerPegaCookie(sChave){
  var sArg = sChave+"=";
  var nLenA = sArg.length;
  var nLenC = document.cookie.length;
  var i=0;
  while(i<nLenC){
    var j = i + nLenA;
	if (document.cookie.substring(i,j) == sArg)
	    return gerPegaCookieVal(j);
	i = document.cookie.indexOf(" ",i)+1;
	if (i==0) break;
  }
  return "";  
}

function gerPegaCookieVal(nOffset){
 if (document.cookie.length > 0) {
  var nEnd = document.cookie.indexOf(";",nOffset);
  if (nEnd == -1) nEnd = document.cookie.length;
  return unescape(document.cookie.substring(nOffset,nEnd));
  }
 else{
  return ""
 }
}
function gerGravaCookie(sChave,sValor){
  var sArgv = gerGravaCookie.arguments;
  var nArgc = gerGravaCookie.arguments.length;
  var sExpires = (nArgc>2)? sArgv[2]:null;
  var sPath = (nArgc>3)? sArgv[3]:null;
  var sDomain = (nArgc>4)? sArgv[4]:null;
  var bSecure = (nArgc>5)? sArgv[5]:null;
  document.cookie = sChave + "=" + escape(sValor) +
   ((sExpires == null)? "":(";expires="+sExpires.toGMTString())) +
   ((sPath == null)? "":(";path="+ sPath )) +
   ((sDomain == null)? "":(";domain="+ sDomain )) +
   ((bSecure == true)? ";secure":"");
}
//persistencia de forms em cookie para recuperacao posterior
function gerPersisteForms(inframe)
{ 
	var posValor = ''
	var bExiste =false
	var sForms
	var titulo
	var sChecked = ""
try{
	titulo = inframe.document.title.toUpperCase()

    inframe=(!inframe)?this.window:inframe
	for (var i=0;i<inframe.document.forms.length;i++){	    
		for (var j=0;j<inframe.document.forms[i].elements.length;j++){
	       if (parent.parent.Auxiliar.document.forms[i].elements[j].name == inframe.document.forms[i].elements[j].name)
	       {	
				
				if (parent.parent.Auxiliar.document.forms[i].elements[j].type.toUpperCase()=="CHECKBOX")
				{						
					parent.parent.Auxiliar.document.forms[i].elements[j].checked = inframe.document.forms[i].elements[j].checked					
				}	
				else
					parent.parent.Auxiliar.document.forms[i].elements[j].value = inframe.document.forms[i].elements[j].value				
			}		
		}
         

	}
	
	for (var k=0;k<parent.parent.Navegacao.ArrPosNomes.length;k++)
		{
			
			if (titulo.search("-"+parent.parent.Navegacao.ArrPosNomes[k].toUpperCase()+"-")>=0)
			{				
				bExiste = true
				posValor = k
				break
			
			}	
			else
				bExiste = false				
			
			
			
		}	
	for (var h=0;h<inframe.document.forms.length;h++)
		{
			sForms =  sForms + "<form name='"+inframe.document.forms[h].name+"'>"
			for (var j = 0; j<inframe.document.forms[h].length;j++)		
			{
				if (inframe.document.forms[h].elements[j].type.toUpperCase()=='CHECKBOX')	
				{	
					if (inframe.document.forms[h].elements[j].checked)
						sChecked = "checked"
					else	
						sChecked = ""
					if (inframe.document.forms[h].elements[j].disabled)
					 	sChecked = sChecked + " Disabled "
					if (inframe.document.forms[h].elements[j].readOnly)
					 	sChecked = sChecked + " readOnly " 	
								
					sForms = sForms + "<input type="+inframe.document.forms[h].elements[j].type+" name='"+inframe.document.forms[h].elements[j].name+"' "+sChecked+">"
				}	
				else
				{					
					if (inframe.document.forms[h].elements[j].type.toUpperCase()=='SELECT-ONE')	
					{	
						sChecked = ""
						if (inframe.document.forms[h].elements[j].disabled)
							sChecked = sChecked + " Disabled "
						if (inframe.document.forms[h].elements[j].readOnly)
							sChecked = sChecked +" readOnly "	
						sForms = sForms + "<SELECT "+sChecked+" name='"+inframe.document.forms[h].elements[j].name+"'>"						
						for (var iSel = 0 ; iSel<inframe.document.forms[h].elements[j].length ; iSel++)
						{
							if (inframe.document.forms[h].elements[j].options[iSel].selected)
								sSelected = "selected"
							else	
								sSelected = ""
							sForms = sForms + "<OPTION "+sSelected+" VALUE="+inframe.document.forms[h].elements[j].options[iSel].value+">"+inframe.document.forms[h].elements[j].options[iSel].text+"</OPTION>"
						}
						sForms = sForms + "</SELECT>"
					}
					else
					{
						if (inframe.document.forms[h].elements[j].type.toUpperCase()=='SELECT-MULTIPLE')	
						{	
							sChecked = ""
							if (inframe.document.forms[h].elements[j].disabled)
								sChecked = sChecked + " Disabled "
							if (inframe.document.forms[h].elements[j].readOnly)
								sChecked = sChecked +" readOnly "	
							sForms = sForms + "<SELECT "+sChecked+" MULTIPLE name='"+inframe.document.forms[h].elements[j].name+"'>"
							for (var iSel = 0 ; iSel<inframe.document.forms[h].elements[j].length ; iSel++)
							{
								if (inframe.document.forms[h].elements[j].options[iSel].selected)
									sSelected = "selected"
								else	
									sSelected = ""
								sForms = sForms + "<OPTION "+sSelected+" VALUE="+inframe.document.forms[h].elements[j].options[iSel].value+">"+inframe.document.forms[h].elements[j].options[iSel].text+"</OPTION>"
							}
							sForms = sForms + "</SELECT>"
						}
						else
						{
							if (inframe.document.forms[h].elements[j].type.toUpperCase()=='RADIO')	
							{
								sChecked = ""
								if (inframe.document.forms[h].elements[j].checked)
									sChecked = "checked"
								else	
									sChecked = ""
								if (inframe.document.forms[h].elements[j].disabled)
									sChecked = sChecked + " Disabled "
								if (inframe.document.forms[h].elements[j].readOnly)
									sChecked = sChecked +" readOnly "	
								sForms = sForms + "<input type="+inframe.document.forms[h].elements[j].type+" name='"+inframe.document.forms[h].elements[j].name+"' "+sChecked+">"
							}	
							else
							{
								sChecked = ""
								if (inframe.document.forms[h].elements[j].disabled)
									sChecked = sChecked + " Disabled "
								if (inframe.document.forms[h].elements[j].readOnly)
										sChecked = sChecked +" readOnly "
								sForms = sForms + "<input "+sChecked+" type="+inframe.document.forms[h].elements[j].type+" name="+inframe.document.forms[h].elements[j].name+" value='"+inframe.document.forms[h].elements[j].value+"'>"
							}	
						}   
				
					}
					
					
				}	
			}
			sForms =  sForms + "</form>"
		}
		if (bExiste){					
			parent.parent.Navegacao.ArrValores[posValor] = sForms						
			
		}
}		
catch(e)	{}
}
// monta forms a partir do cookie
function gerRecupForms(inframe)
{	
var titulo
	var objBody
	var bExiste = false
	var sForms = ""
	var posValor = 0	
try{	
	objBody = parent.parent.Auxiliar.document.body
	
	titulo = inframe.document.title.toUpperCase()
	
	objBody.innerHTML = ""
	
	inframe=(!inframe)?this.window:inframe
	for (var k=0;k<parent.parent.Navegacao.ArrPosNomes.length;k++)
	{
			
		if (titulo.search("-"+parent.parent.Navegacao.ArrPosNomes[k].toUpperCase()+"-")>=0)
		{				
			bExiste = true
			posValor = k
			break
		
		}	
		else
			bExiste = false				
			
	}		
	if (bExiste){				
		objBody.innerHTML  = parent.parent.Navegacao.ArrValores[posValor]
		
		
	}
		
	for (var i=0;i<inframe.document.forms.length;i++){
		for (var j=0;j<inframe.document.forms[i].elements.length;j++){
			if (parent.parent.Auxiliar.document.forms[i].elements[j].name == inframe.document.forms[i].elements[j].name){				
				if (inframe.document.forms[i].elements[j].type.toUpperCase()=='CHECKBOX')
				{					
					if (parent.parent.Auxiliar.document.forms[i].elements[j].checked)
						inframe.document.forms[i].elements[j].checked=true
					if (parent.parent.Auxiliar.document.forms[i].elements[j].disabled)
						inframe.document.forms[i].elements[j].disabled=true
					if (parent.parent.Auxiliar.document.forms[i].elements[j].readOnly)
						inframe.document.forms[i].elements[j].readOnly=true							
							
				}
				else{
					
					if (inframe.document.forms[i].elements[j].type.toUpperCase()=='SELECT-ONE')
					{						
						
						for (var iSel = 0;iSel<parent.parent.Auxiliar.document.forms[i].elements[j].length;iSel++)
						{
							inframe.document.forms[i].elements[j].options[iSel].selected=parent.parent.Auxiliar.document.forms[i].elements[j].options[iSel].selected
						}	
						if (parent.parent.Auxiliar.document.forms[i].elements[j].disabled)
							inframe.document.forms[i].elements[j].disabled=true
						if (parent.parent.Auxiliar.document.forms[i].elements[j].readOnly)
							inframe.document.forms[i].elements[j].readOnly=true					
					}
					else
						if (inframe.document.forms[i].elements[j].type.toUpperCase()=='SELECT-MULTIPLE')												
						{					
							for (var iSel = inframe.document.forms[i].elements[j].length;iSel>=0; iSel--)
							{								
								inframe.document.forms[i].elements[j].options.remove(iSel)
							}
							for (var iSel = 0;iSel<parent.parent.Auxiliar.document.forms[i].elements[j].length;iSel++)
							{
								var oOption = inframe.document.createElement("OPTION");
								inframe.document.forms[i].elements[j].options.add(oOption)
								oOption.innerText = parent.parent.Auxiliar.document.forms[i].elements[j].options[iSel].text 
								oOption.value =  parent.parent.Auxiliar.document.forms[i].elements[j].options[iSel].value
								oOption.selected = parent.parent.Auxiliar.document.forms[i].elements[j].options[iSel].selected
							}					
							if (parent.parent.Auxiliar.document.forms[i].elements[j].disabled)
								inframe.document.forms[i].elements[j].disabled=true
							if (parent.parent.Auxiliar.document.forms[i].elements[j].readOnly)
								inframe.document.forms[i].elements[j].readOnly=true					
						
						}
						else
						{
							if (inframe.document.forms[i].elements[j].type.toUpperCase()=='RADIO')
							{		
								if (parent.parent.Auxiliar.document.forms[i].elements[j].checked)
									inframe.document.forms[i].elements[j].checked=true
								if (parent.parent.Auxiliar.document.forms[i].elements[j].disabled)
									inframe.document.forms[i].elements[j].disabled=true
								if (parent.parent.Auxiliar.document.forms[i].elements[j].readOnly)
									inframe.document.forms[i].elements[j].readOnly=true		
							}
							else
							{
								if (parent.parent.Auxiliar.document.forms[i].elements[j].disabled)
									inframe.document.forms[i].elements[j].disabled=true
								if (parent.parent.Auxiliar.document.forms[i].elements[j].readOnly)
									inframe.document.forms[i].elements[j].readOnly=true	
								inframe.document.forms[i].elements[j].value = parent.parent.Auxiliar.document.forms[i].elements[j].value				
							}	
						}   
				}		   
			}	
		}
	}
}
catch(e){}
}
// recuperar valor para o campo - usa o nro do campo pois podem haver campos de mesmo nome
// se o nome do campo = ao do cookie =atribui valor e retorna true
// senao - ignora e retorna false
// formato da aValores= <#nro>nome%=valor[,vvvvv,vvv,vvv]
function gerBuscaValorCampo(elemento,item){
	aconteudo=item.split("=")
	if (aconteudo[0].indexOf(">"+elemento.name+"%")==-1){return false}
	conteudo=aconteudo[1]
	sw = elemento.type
	var x = conteudo
	if (sw.indexOf("radio")>=0){
		if (elemento.value==x)elemento.checked=true
	}
	else{
		if (sw.indexOf("checkbox")>=0){
			if (elemento.value==x)elemento.checked=true
		}
		else{ 
			if (sw.indexOf("multiple")>=0&&x.indexOf(",")>=0){
			   x = x.split(",")
			   elemento.selectedIndex=-1
 			  for ( var i=0;i<x.length;i++){
					for (var j=0;j<elemento.options.length;j++){
			         if (elemento.options[j].value==x[i]) {elemento.options[j].selected=true}
					}
				}
			}
			else{
			elemento.value=x
			}
		}
	}
return true
}
// recupera o campo do elemento. em caso de selects - retorna lista 
// com texto, valor e selected
//
function gerMontaValor(elemento,textvalue){
	var sw = elemento.type
	var textvalue=(textvalue=='text')?'t':'v'
	var x= String(elemento.value)
	if (sw.indexOf("radio")>=0)
		x= (elemento.checked)?x:""
	if (sw.indexOf("checkbox")>=0)
		x= (elemento.checked)?x:""
	if  (sw.indexOf("select")>=0) 
	{	x=""
		var cx=""
		for ( var i=0;i<elemento.options.length;i++)
		{	 if(elemento.options[i].selected) 
			 {	x+= cx+((textvalue=='v')?elemento.options[i].value:elemento.options[i].text);
			 	cx=",";
			 }
		}
	}
	x=x.replace(/\n/gi,"\n")
	return x.replace(/\r/gi,"\r")
}
//
//funções de manipulacao basica de strings =====================================================

function gerExtraiStr(str1,str2){
  return gerTrocaStr(str1, str2, "")
}
function gerTrim(str1){
return str1.replace(/^\s*(.*[^\s])\s*$/,"$1")
}
function gerExtraiSpc(str1){
 return str1.replace(/\s/g,"")  
}
function gerLimpaString(str1){
  str1 = innerText(str1) //extrai tags html
  str1 = gerTrocaStr(str1, '\\&(\\w)(\\w){1,8}\\;',"$1") // traduz &ccedil; para c; etc.
  return gerExtraiAcentos(str1)
}
function gerExtraiAcentos(str1){
  str1 = gerTrocaStr(str1, "ã", "a")
  str1 = gerTrocaStr(str1, "â", "a")
  str1 = gerTrocaStr(str1, "á", "a")
  str1 = gerTrocaStr(str1, "à", "a")
  str1 = gerTrocaStr(str1, "ä", "a")
  str1 = gerTrocaStr(str1, "õ", "o")
  str1 = gerTrocaStr(str1, "ô", "o")
  str1 = gerTrocaStr(str1, "ó", "o")  
  str1 = gerTrocaStr(str1, "ó", "o")
  str1 = gerTrocaStr(str1, "ò", "o")  
  str1 = gerTrocaStr(str1, "ç", "c")
  str1 = gerTrocaStr(str1, "í", "i")
  str1 = gerTrocaStr(str1, "ì", "i")
  str1 = gerTrocaStr(str1, "î", "i")
  str1 = gerTrocaStr(str1, "ï", "i")
  str1 = gerTrocaStr(str1, "é", "e")
  str1 = gerTrocaStr(str1, "ê", "e")
  str1 = gerTrocaStr(str1, "ë", "e")
  str1 = gerTrocaStr(str1, "ú", "u")
  str1 = gerTrocaStr(str1, "ù", "u")
  str1 = gerTrocaStr(str1, "ü", "u")
  str1 = gerTrocaStr(str1, "û", "u")
  str1 = gerTrocaStr(str1, "ÿ", "y")
  str1 = gerTrocaStr(str1, "Ã", "A")
  str1 = gerTrocaStr(str1, "Â", "A")
  str1 = gerTrocaStr(str1, "Á", "A")
  str1 = gerTrocaStr(str1, "À", "A")
  str1 = gerTrocaStr(str1, "Ä", "A")
  str1 = gerTrocaStr(str1, "Õ", "O")
  str1 = gerTrocaStr(str1, "Ô", "O")
  str1 = gerTrocaStr(str1, "Ó", "O")  
  str1 = gerTrocaStr(str1, "Ó", "O")
  str1 = gerTrocaStr(str1, "Ò", "O")  
  str1 = gerTrocaStr(str1, "Ç", "C")
  str1 = gerTrocaStr(str1, "Í", "I")
  str1 = gerTrocaStr(str1, "Ì", "I")
  str1 = gerTrocaStr(str1, "Î", "I")
  str1 = gerTrocaStr(str1, "Ï", "I")
  str1 = gerTrocaStr(str1, "É", "E")
  str1 = gerTrocaStr(str1, "Ê", "E")
  str1 = gerTrocaStr(str1, "Ë", "E")
  str1 = gerTrocaStr(str1, "Ú", "U")
  str1 = gerTrocaStr(str1, "Ù", "U")
  str1 = gerTrocaStr(str1, "Ü", "U")
  str1 = gerTrocaStr(str1, "Û", "U")
return str1
  
}

//substitui todas as ocorrencias de uma string expressão regular por outra
function gerTrocaStr(instr, reBusca, sTroca,umavez,ignorecase) {
instr=""+instr+""    
if (isString(reBusca)){ 
	  	reBusca = new RegExp(reBusca,((ignorecase)?"i":"")+((umavez)?"":"g"))
	}
    return instr.replace(reBusca,sTroca);
}

function innerText(str) {	// elimina tags html e deixa somente o innertext
	str=""+str+""
	str=str.replace (/\<[^\>]*\>/g,"")
	return(str);
}

function zeraForm(form) {
	for (var i = 0 ; i < form.length; i++) {
		if (!form[i].readOnly) {
			if (form[i].type == 'text') form[i].value = ""
			if (form[i].type == 'select') form[i].selectedIndex = -1
			if (form[i].type == 'radio' || form[i].type == 'checkbox') form[i].checked = false
		}
	}
}

function gerLimpar(inframe,fLimparTudo){
	var auxLimpar	
	re = / /gi;
		
	if (inframe.parent.Acoes.window.document.Script.self.document.activeElement.tagName=="INPUT")
		auxLimpar=inframe.parent.Acoes.window.document.Script.self.document.activeElement.value
	else	
		auxLimpar = ""
	auxLimpar=auxLimpar.replace(re,"")		
	
	if (gerLimpar.arguments.length==1)
		pos=1
	else
		pos=gerLimpar.arguments[1]		
    inframe=(!inframe)?this.window:inframe
	for (var i=0;i<inframe.document.forms.length;i++){
		if (fLimparTudo) {
			zeraForm(inframe.document.forms[i])
		} else {
			inframe.document.forms[i].reset()
		}
	}// no Netscape chama recursivamente para cada Layer
	
	//------Aqui começou a mudança-------------
	
	if ((auxLimpar!="Limpar") && (!g_IS.ns4)){
		var el = inframe.document.all.tags("DIV")
		AtivaDiv(el(pos).id, inframe); //Ativa DIV, no exemplo DIV 0, isto é: a primeira!
	  //-------Aqui termina a mudança-------------
	 } 
	
		if (g_IS.ns4){
		for (var i=0;i<inframe.document.layers.length;i++){
         gerLimpar(inframe.document.layers[i])
		}
	}

	//Coloca foco no primeiro campo da DIV ativa, evita q o foco fique no frame de Acoes (IE5.5)
	var oDiv = inframe.document.all.tags("DIV")
	for (var n=0;n<inframe.document.all.tags("DIV").length;n++)
		if(oDiv(n).style.visibility == "visible")
			{AtivaDiv(oDiv(n).id, inframe);	return;	}

}
//------Aqui começou a mudança-------------
function AtivaDiv(tab, inframe){
    	try{	    	
			this.Acoes.mAbas.escreve("dAbasCab")					
			this.Acoes.mAbas.selTab(tab)
			}
			catch(e){
			}
	}			
//-------Aqui termina a mudança-------------	
// frame a pegar os forms, action , lista de campos extras (nome, conteudo)...
function gerEnviaTodosForms(inframe, saction,starget){
var oDest=null
var err=false
smetod='post';
starget=(starget)?starget:""
var sArgv = gerEnviaTodosForms.arguments;
var nArgc = gerEnviaTodosForms.arguments.length;
// verifica se ha frame Controle
if(!frames.Controle)
{ 	//if(this.frames["Controle"]) 
	//{ 	oDest=this.frames["Controle"]}  
//	else 
	//{
		if(top.debug){alert("erro - estrutura de frames");}
		Controle=window.open("","","width=200,  height=300, dependent");
		err=true 
	//}
}
//cria formulario de trabalho
var str='<form name="zzzzFormUnico" action="'+saction+'" method="'+smetod+'" target="'+((starget&&starget!="")?starget:'Controle')+'">\n'
//se informado frame - varre os forms , senão somente os outros
oDest=pegaObjeto('zzzzControle'); if (!oDest)oDest=frames["Controle"]
dw(oDest,"")
if (inframe) str+=gerMontaForms(inframe)
//grava campos informados pela linha de comando nome,valor,...
if (nArgc>3){
  var xValor=""
	for (var i=3; i<nArgc;i+=2){
            xValor=gerTrocaStr(innerText(sArgv[i+1]),"'",'&lsquo;')
						xValor=gerTrocaStr(xValor,'"','&quot;')
		str+="<input type=text name="+sArgv[i]+" value='"+xValor+"'>\n"
	}
}
if(top.debug){str+='<input type=submit value=enviar>'}
str+='</form>'
dw(oDest,str)
if(top.debug&&!g_IS.ns4){frames.Controle.document.write(str)}
if(!top.debug||confirm("enviar?")) {
	pegaObjeto("zzzzFormUnico").submit();
	dw(oDest,"")
}
return
} 

function gerMontaForms(inframe)
{   inframe=(!inframe)?this.window:inframe
    var str=""
	for (var i=0;i<inframe.document.forms.length;i++){
	    var sValor=""
		for (var j=0;j<inframe.document.forms[i].elements.length;j++){
 		    var etype=(inframe.document.forms[i].elements[j].type)
			fTextArea = false
			if (etype == "textarea") {
				fTextArea = true
			}
			if(etype!='submit'&&etype!='reset'&&etype!='button') //ignora botoes, submit e reset's
			{	
				var xValor=gerMontaValor(inframe.document.forms[i].elements[j])
				if (xValor!="") {
						var xValor=gerTrocaStr(innerText(xValor),"'",'&lsquo;')
						xValor=gerTrocaStr(xValor,'"','&quot;')
						if (fTextArea) {
				    str+='<textarea name="'+inframe.document.forms[i].elements[j].name+'">' + xValor + '</textarea>'
						} else {
				    str+='<input type=text name="'+inframe.document.forms[i].elements[j].name+'" value="'+xValor+'">'
						}
				}
			}
		}
	    this.window.external.AutoCompleteSaveForm(inframe.document.forms[i]); //Registra AutoComplete para todos os objetos nos forms					
	}// no Netscape chama recursivamente para cada Layer
	if (g_IS.ns4){
		for (var l=0;l<inframe.document.layers.length;l++){
			str+=gerMontaForms(inframe.document.layers[l])
		}
	}
	return str	
}


function zeraForm(form){
/*
form é o forme que vai ser zerado.
ATENÇÃO, essa função apaga todos os dados do formulario, não retorna ele para o seu estado original.
*/
	for (var i=0;i<form.elements.length;i++) {
		elem = form.elements[i]
		if (elem.type!='button'&&elem.type!='submit'&&elem.type!='reset') {
			if (elem.type=="radio"||elem.type=="checkbox") {
				elem.checked=false
			} else {
				elem.value=""
			}
		}
	}
}

function impVInput (input,repadrao,msgerr,formatar,aIns){

	if(repadrao){
		if (input.value!=""){
			if(!repadrao.test(input.value)){
				if(msgerr){
					newConfirm('E-Gerdau',msgerr,1,0,0);
				}
				input.select();input.focus();
				return false
			}
			else{
				if(isString(formatar)&&!aIns){ //compatibilidade com interface anterior
				input.value =impFormat(input.value,repadrao,formatar)
			    }
				else if(formatar) input.value =impFormat(input.value,repadrao,aIns)
			}
		}
	}
	return true
}

function impFormat(instr, reBusca, sTroca,umavez,ignorecase) {
    if (isString(reBusca)){ 
	  	reBusca = new RegExp(reBusca,((ignorecase)?"i":"")+((umavez)?"":"g"))
	}
    return instr.replace(reBusca,sTroca);
}


function ValidaFormataCEP(obj){

	if   (obj.value.length > 5) 
	{
		impVInput (obj,reCEP,'CEP Inválido', feCEP, fsCEP);
		
	}
	else 
	{
		impVInput (obj,reCEP5,'CEP Inválido');
	}

}

//*********************************************************
//					validaco.js
//*********************************************************
function AbreHelp(pag,campo) {
	window.open(pag,'_nova', "top=20,left="+window.screen.availWidth-300+",width=415,height=374,toolbar=no,menubar=no,location=no,scrollbars=yes");
}

function isTime(time){
	//declarações
	var hora,minuto,cond,minuto_dia;
	if(time.length >5 || time.length < 4) return false;
	//busca valores de hora e minuto
	for (var i = 0; i < time.length; i++) {
		if (time.substring(i,i+1) == ':' ){
			hora = time.substring(0,i);
			minuto = time.substring(i+1,time.length);
			cond = true;
			break;
		} else {
			cond = false;
		}
	}
	//se : encontrado, trata
	if (cond==true){
		//se numéricos
		if (isNumber(hora) && isNumber(minuto)) {
			if (hora > 23 || minuto > 59) {
				return false;
			} else {
				return true;
			}
		}
	}
}

function isDate(data) {
	if (data.length != 10) return false;
	var dia = data.substring(0,2);
	if (data.substring(2,3) != '/') return false;
	var mes = data.substring(3,5);
	if (data.substring(5,6) != '/') return false;
	var ano = data.substring(6,10);
	if (!isNumber(dia) || !isNumber(mes) || !isNumber(ano)) return false;
	var dia_int = parseInt (dia, 10);
	var mes_int = parseInt (mes, 10);
	var ano_int = parseInt (ano, 10);
	if (ano_int < 1000 || ano_int > 3000) return false;
	if (mes_int < 1 || mes_int > 12) return false;
	if ( (mes_int == 1 || mes_int == 3 || mes_int == 5 || mes_int == 7 || mes_int == 8 || mes_int == 10 || mes_int == 12) && (dia_int < 1 || dia_int > 31) )
			   return false;
	if ( (mes_int == 4 || mes_int == 6 || mes_int == 9 || mes_int == 11) && (dia_int < 1 || dia_int > 30) )
			   return false;
	if (mes_int == 2) {
			   if (isBissexto(ano)) {
						   if (dia_int < 1 || dia_int > 29) return false;
			   } else {
						   if (dia_int < 1 || dia_int > 28) return false;
			   }
	}
	return true;
}


function isBissexto(ano) {
	if (!isNumber(ano)) return false;
	var ano_int = parseInt(ano,10);
	if ( ( ((ano_int % 4) == 0) && ((ano_int % 10) != 0) ) || ((ano_int % 400) == 0) )  return true;
	return false;
}


function compareDate(datainicio, datafim) {
	if (datainicio.length != 10) return false;
	var diainicio = datainicio.substring(0,2);
	var mesinicio = datainicio.substring(3,5);
	var anoinicio = datainicio.substring(6,10);
	if (!isNumber(diainicio) || !isNumber(mesinicio) || !isNumber(anoinicio)) return false;
	var diainicio_int = parseInt (diainicio, 10);
	var mesinicio_int = parseInt (mesinicio, 10);
	var anoinicio_int = parseInt (anoinicio, 10);

	if (datafim.length != 10) return false;
	var diafim = datafim.substring(0,2);
	var mesfim = datafim.substring(3,5);
	var anofim = datafim.substring(6,10);
	if (!isNumber(diafim) || !isNumber(mesfim) || !isNumber(anofim)) return false;
	var diafim_int = parseInt (diafim, 10);
	var mesfim_int = parseInt (mesfim, 10);
	var anofim_int = parseInt (anofim, 10);

	if ( anoinicio < anofim ) return 1;
	if ( anoinicio > anofim ) return -1;
	if ( mesinicio < mesfim ) return 1;
	if ( mesinicio > mesfim ) return -1;
	if ( diainicio < diafim ) return 1;
	if ( diainicio > diafim ) return -1;
	return 0;
}

function compareTime(timeinicio, timefim) {
	if (timeinicio.length != 5) return false;
	var horainicio = timeinicio.substring(0,2);
	var minutoinicio = timeinicio.substring(3,5);
	if (!isNumber(horainicio) || !isNumber(minutoinicio) ) return false;
	var horainicio_int = parseInt (horainicio, 10);
	var minutoinicio_int = parseInt (minutoinicio, 10);

	if (timefim.length != 5) return false;
	var horafim = timefim.substring(0,2);
	var minutofim = timefim.substring(3,5);
	if (!isNumber(horafim) || !isNumber(minutofim) ) return false;
	var horafim_int = parseInt (horafim, 10);
	var minutofim_int = parseInt (minutofim, 10);

	if ( horainicio < horafim ) return 1;
	if ( horainicio > horafim ) return -1;
	if ( minutoinicio < minutofim ) return 1;
	if ( minutoinicio > minutofim ) return -1;
	return 0;
}

function isMMYYYY(data) {
	if (data.length != 7) return false;
	var mes = data.substring(0,2);
	if (data.substring(2,3) != '/') return false;
	var ano = data.substring(3,7);
	if (!isNumber(mes) || !isNumber(ano)) return false;
	var mes_int = parseInt (mes, 10);
	var ano_int = parseInt (ano, 10);
	if (ano_int < 1000 || ano_int > 3000) return false;
	if (mes_int < 1 || mes_int > 12) return false;
	return true;
}



function difMMYYYY(datainicio, datafim) {
	var dif = 0;

	var mesinicio = datainicio.substring(0,2);
	var anoinicio = datainicio.substring(3,7);
	var mesinicio_int = parseInt (mesinicio, 10);
	var anoinicio_int = parseInt (anoinicio, 10);
	var mesfim = datafim.substring(0,2);
	var anofim = datafim.substring(3,7);
	var mesfim_int = parseInt (mesfim, 10);
	var anofim_int = parseInt (anofim, 10);

	if ( anoinicio < anofim ) dif += 12 * (anofim - anoinicio);
	if ( anoinicio > anofim ) dif -= 12 * (anoinicio - anofim);
	if ( mesinicio < mesfim ) dif += mesfim - mesinicio;
	if ( mesinicio > mesfim ) dif -= mesinicio - mesfim;
	return dif;
}


function isNumber(x) {
	if (x.length == 0) return false;
	for (var i = 0; i < x.length; i++)
		if (x.substring(i,i+1) < '0' || x.substring(i,i+1) > '9') return false;
	return true;
}

function isFloat(x) {
	if (x.length == 0) return false;
	var dot = 0;
	for (var i = 0; i < x.length; i++) {
		if (x.substring(i,i+1) == '.' || x.substring(i,i+1) == ',') dot++;
		else if (x.substring(i,i+1) < '0' || x.substring(i,i+1) > '9') return false;
	}
	if (dot > 1) return false;
	return true;
}

function isMoney(x) {
	if (x.length == 0) return false;
	var dot = 0;
	for (var i = 0; i < x.length; i++) {
		if (x.substring(i,i+1) == ',' ) dot++;
		else if ( (x.substring(i,i+1) < '0' || x.substring(i,i+1) > '9') && x.substring(i,i+1) != '.') {
			return false;
		}
	}
	if (dot > 1) return false;
	return true;
}

function isFone(x) {
	if (x.length != 10)	return false;
	if (x.substring(0,1) != '5') return false;;
	if (!( (x.substring(1,2) == '1') || (x.substring(1,2) >= '3' && x.substring(1,2) <= '5') ) )  return false;
	if (x.substring(2,3) != '9') return false;
	if (!(x.substring(3,4) >= '6' && x.substring(3,4) <= '9') ) return false;
	for (var i = 4; i < 10; i++)
		if (x.substring(i,i+1) < '0' || x.substring(i,i+1) > '9') return false;
}

function isChecked(radioArray) {
	for (var i = 0; i < radioArray.length; i++)
		if (radioArray[i].checked == "1") return true;
	return false;
}

function isWord(x) {
	if (x.length == 0) return false;
	if(x.substring(0,1) <=' ') return false;
	return true;
}

function isEmail(s) {
	if (!isWord(s)) return false;
	var i = 1;
	var sLength = s.length;

	while ((i < sLength) && (s.charAt(i) != "@")) {
		i++
	}

	if ((i >= sLength) || (s.charAt(i) != "@")) return false;
	else i += 2;
	while ((i < sLength) && (s.charAt(i) != ".")) {
		i++
	}

	if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
	else return true;
}

function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

function isLetter (c)
{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}

function isAlphabetic (s)

{   var i;

    if (isEmpty(s))
		return false;
    for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);
        if (!isLetter(c))
        return false;
    }
    return true;
}


function isCNPJ(NroCNPJ) {
	NroCNPJ = NroCNPJ.replace(".","");
	NroCNPJ = NroCNPJ.replace(".","");	
	NroCNPJ = NroCNPJ.replace("/","");
	NroCNPJ = NroCNPJ.replace("-","");	
	var dig1=0;
	var dig2=0;
	var x;
	var Mult1 = '543298765432';
	var Mult2 = '6543298765432';

	for(x=0; x<=11; x++)
		dig1 = dig1 + ( parseInt(NroCNPJ.slice(x,x+1)) * parseInt(Mult1.slice(x,x+1)) );
	for(x=0; x<=12; x++)
		dig2 = dig2 + ( parseInt(NroCNPJ.slice(x, x+1)) * parseInt(Mult2.slice(x,x+1)) );

	dig1 = (dig1 * 10)%11;
	dig2 = (dig2 * 10)%11;

	if (dig1 == 10) dig1 = 0;
	if (dig2 == 10) dig2 = 0;

	if (dig1 != parseInt(NroCNPJ.slice(12, 13)))
		return false;
	if (dig2 != parseInt(NroCNPJ.slice(13, 14)))
		return false;

	return true;
}

function isCPF(numcpf) {
	numcpf = numcpf.replace(".","");
	numcpf = numcpf.replace(".","");
	numcpf = numcpf.replace(".","");		
	numcpf = numcpf.replace("/","");
	numcpf = numcpf.replace("-","");
	if (numcpf.length != 11)
		return false;
	if (!isNumber(numcpf))
		return false;
	var x = 10;
	var soma = 0;
	var dig1 = 0;
	var dig2 = 0;
	var len = numcpf.length;
	for (var i = 0; i < 9; i++, x--)
		soma += parseInt(numcpf.substring(i,i+1)) * x;
	dig1 = 11 - (soma % 11);
	if (dig1 == 10) dig1 = 0 ;
	if (dig1 == 11) dig1 = 0 ;
	if ( dig1 != parseInt(numcpf.substring(9,10)) )
		return false;
	x = 11;
	soma=0;
	for (var i = 0; i < 9; i++, x--)
		soma += parseInt(numcpf.substring(i,i+1)) * x;
	soma += dig1 * 2;
	dig2 = 11 - (soma % 11);
	if (dig2 == 10) dig2 = 0;
	if (dig2 == 11) dig2 = 0;
	if ( dig2 != parseInt(numcpf.substring(10,11)) )
		return false;
	return true;
}


function isPlaca(placa) {
	if ( placa.length != 8 )
		return false;

	if ( isNumber(placa.substring(0, 3)))
		return false;

			if(placa.substring(3,4) != ' ')
				return false;

	if ( !isNumber(placa.substring(4, 7)))
		return false;

	return true;
}

// Função que valida o e-mail
function isEmail( strEmail ) {
// Precisa conter pelo menos cinco caracteres
   if (strEmail.length < 6) return false;

// Precisa conter um sinal de arroba
   for (nCont=0; nCont < strEmail.length; nCont++)
		if (strEmail.charAt(nCont) == '@')
			break;
   if (nCont == strEmail.length) return false;
			    
// Precisa conter pelo menos um ponto após o sinal de arroba
   for (nCont1=nCont+1; nCont1 < strEmail.length; nCont1++)
        if (strEmail.charAt(nCont1) == '.')
            break;
   if (nCont1 == strEmail.length) return false;
                   
   return true;
}

//Função que válida se é um objeto
function isObject(obj){
 var stobj = typeof(obj);
 return (stobj.indexOf("object") >= 0 );
}



function MudaTamanhoInscEstadual(estado, TipoPessoa){
	var inscEstadual

	//TPR672
	if(TipoPessoa == "PF"){
		return false;
	}
	if(document.all.inscEstadual){
		inscEstadual = document.all.inscEstadual.value;
		if(estado == 'SP'){
			document.all.inscEstadual.maxLength = 12;
			document.all.inscEstadual.value = inscEstadual.substring(0,12);
		}
		else{
			document.all.inscEstadual.maxLength = 18;
			document.all.inscEstadual.value = inscEstadual;
		}
	}
}


function trim(inputString) {
	if (typeof inputString != "string"){
		return inputString; 
	}
	var retValue = inputString;
	var ch = retValue.substring(0, 1);
	while (ch == " ") { // Verifica espaços no inicio da string
		retValue = retValue.substring(1, retValue.length);
		ch = retValue.substring(0, 1);
	}
	ch = retValue.substring(retValue.length-1, retValue.length);
	while (ch == " ") { // Verifica espaços no final da string.
		retValue = retValue.substring(0, retValue.length-1);
		ch = retValue.substring(retValue.length-1, retValue.length);
	}
	while (retValue.indexOf("  ") != -1) { 
		retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); 
	}
   return retValue; // Retorna a string
} // Fim da função "trim"


function ValidaTelefone(pTel, campo){
	pTel = trim(pTel);
	//alert(pTel);
	if(pTel == ""){
		return false;
	}
	//alert(pTel);
	pTel = pTel.replace(/\-/gi,"");
	pTel = pTel.replace(/\ /gi,"");
	//alert(pTel);
	campo.value= trim(pTel);
	if(impVInput (campo,reInteiro,'Telefone inválido')){
		//entrou no if
		campo.onchange();
	}
	
}


function ValidaDataMaior(obj,DtAtual, blPassaDtHoje){
	var Data = obj.value;
	var Hoje = DtAtual;
	var arrData = Data.split('/');
	var arrHoje = Hoje.split("/");
	var i
	var strMsg = "Data deve ser menor ou igual a data de hoje.";
//	alert(Data);	
//	alert(Hoje);
//	alert(blPassaDtHoje);
	if(!blPassaDtHoje){
		strMsg = "Data deve ser menor que a data de hoje.";
		if(Data == Hoje){
			newConfirm('E-Gerdau',strMsg,1,48,0);
			return false;
		}	
	}
	if (arrData[2] > arrHoje[2]){
		newConfirm('E-Gerdau',strMsg,1,48,0);
		return false;
 	}
	if ((arrData[1] > arrHoje[1]) && (arrData[2] >= arrHoje[2])){
		newConfirm('E-Gerdau',strMsg,1,48,0);
		return false;
	}
	if ((arrData[0] > arrHoje[0]) && (arrData[1] >= arrHoje[1]) && (arrData[2] >= arrHoje[2])){
		newConfirm('E-Gerdau',strMsg, 1,48,0);
		return false;
	}
	return true;
}

function getSelectedRadioValue(buttonGroup) {
   // returns the value of the selected radio button or "" if no button is selected
   var i = getSelectedRadio(buttonGroup);
   if (i == -1) {
      return "";
   } else {
      if (buttonGroup[i]) { // Make sure the button group is an array (not just one button)
         return buttonGroup[i].value;
      } else { // The button group is just the one button, and it is checked
         return buttonGroup.value;
      }
   }
}

function getSelectedRadio(buttonGroup) {
   // returns the array number of the selected radio button or -1 if no button is selected
   if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            return i
         }
      }
   } else {
      if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
   }
   // if we get to this point, no radio button is selected
   return -1;
} // Ends 
//*********************************************************
//					Funções Diversas
//*********************************************************
// please keep these lines on when you copy the source
// made by: Nicolas - http://www.javascript-page.com

var timerID = 0;
var tStart  = null;
var sFuncao;
var iTempo;
var iTempoFinal;

var hHoraInicial;
var hHoraFinal;

function UpdateTimer() {
   if(timerID) {
      clearTimeout(timerID);
      clockID  = 0;
   }
	
   if(!tStart)
      tStart   = new Date();

   var   tDate = new Date();
   var   tDiff = tDate.getTime() - tStart.getTime();

   tDate.setTime(tDiff);

   iTempo = tDate.getMinutes();
   
   timerID = setTimeout("UpdateTimer()", 1000);
   
   if (iTempoFinal == iTempo)
   {
		timerID = setTimeout(sFuncao, 0);
		tStart   = new Date();
		
   }
   
}

function Start(funcao,tempo) {
   
   tStart   = new Date();

   sFuncao = funcao;
   iTempoFinal = tempo;
	
   timerID  = setTimeout("UpdateTimer()", 1000);
      
}

function Stop() {
   if(timerID) {
      clearTimeout(timerID);
      timerID  = 0;
   }

   tStart = null;
}

function Reset() {
   tStart = null;

   document.theTimer.theTime.value = "00:00";
}

var arJanelas = new Array();
		
function FechaJanelas()
{
		
	var x;
			
	for(x=0;x<arJanelas.length;x++)
	{
		//alert(arJanelas.length);			
		if (arJanelas[x] != null)
		{
			arJanelas[x].close();
		}
	}
		
}