function SohNumeros(valor)
{
	 chars= "0123456789-,";
	 e = String.fromCharCode(window.event.keyCode);
	 if (e == ",") {
		if (valor.indexOf(e)==-1) {
			 return;
		}
		window.event.keyCode=0;
	 }
	 if (e == "-") {
		if (valor.indexOf(e)==-1) {
			 return;
		}
		window.event.keyCode=0;
	 }
	 if(chars.indexOf(e)==-1) {
		window.event.keyCode=0;
	 }
}
		

function isValidDate(dateStr) {
	var datePat = /^(\d{2})(\/|-)(\d{2})\2(\d{4})$/;
	var matchArray = dateStr.match(datePat); 
	var strDesc = 'Data de Preenchimento do RMM';
	if (dateStr == '') {
	   return true;
	}
	if (matchArray == null) {
	   alert (strDesc + ' não é uma data válida no formato dd/mm/aaaa!')
	   return false;
	}
	day = matchArray[1];   // parse date into variables
	month = matchArray[3];
	year = matchArray[4];
	if (month < 1 || month > 12) { // check month range
	   alert('O mês de ' + strDesc + ' precisa estar entre 01 e 12.');
	   return false;
	}
	if (day < 1 || day > 31) {
	   alert('O dia de ' + strDesc + ' precisa estar entre 01 e 31.');
	   return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
	   alert ('O mês ' + month + ' em ' + strDesc + ' não tem 31 dias!')
	   return false
	}
	if (month == 2) { // check for february 29th
	   var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
	   if (day>29 || (day==29 && !isleap)) {
		  alert('Fevereiro do ano de ' + year + ' em ' + strDesc + ' não tem ' + day + ' dias!');
		  return false;
	   }
	}
	return true;  // date is valid
}

function disableForm(thedocument) {
  //alert(thedocument.forms.length);
  for (d = 0; d < thedocument.forms.length; d++) {
    var tempform = thedocument.forms[d];
	if (thedocument.all || thedocument.getElementById) {
		for (i = 0; i < tempform.length; i++) {
			var tempobj = tempform.elements[i];
			if (tempobj.type.toLowerCase() == "button" || tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset"){
			    tempobj.disabled = true;
			}
		}
		return true;
	}else{
		return false;
	}
  }
}


function setFocus(thedocument) {
  for (d = 0; d < thedocument.forms.length; d++) {
    var tempform = thedocument.forms[d];
	if (thedocument.all || thedocument.getElementById) {
		for (i = 0; i < tempform.length; i++) {
			var tempobj = tempform.elements[i];
			if (tempobj.type.toLowerCase() == "text" || tempobj.type.toLowerCase() == "radio" || tempobj.type.toLowerCase() == "checkbox" || tempobj.type.toLowerCase() == "select-one" || tempobj.type.toLowerCase() == "password"){
			    if (!tempobj.disabled) {
					tempobj.focus();
					break;
			    }
			}
		}
		return true;
	}else{
		return false;
	}
  }
}

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;
}

//funcao que verifica se algum campo checkbox foi selecionado
function isChecked(f, aobj) {
	var ok = false;		
	aobj = eval(f.elements[aobj]);
	if (aobj == null) {
		//alert('Não existem checkbox para serem selecionados.');
		return;
	}
	
	if (aobj[0] == null) { // Tratamente para a existencia de apenas 1 objeto no form
		if (aobj.checked == true) {
			return true;
		}
	} else {
		if (aobj != null) {
			for(y=0;y<=aobj.length;y++) {
				if (aobj[y] != null) {
					if (aobj[y].checked == true) {
						ok = true;
					} else {
						//ok = false;
					}
				}
			}
		}
	}
return ok;
}

// Remove os espacos vazios das extremidades da string.
function trim(inputString) {
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") {
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { 
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   return retValue; 
}
	

// Move itens de uma mutiple list (fbox) para outra (tbox)
function move(fbox, tbox) {
	var arrFbox = new Array();
	var arrTbox = new Array();
	var arrLookup = new Array();
	var i;
	
	for (i = 0; i < tbox.options.length; i++) {
		arrLookup[tbox.options[i].text] = tbox.options[i].value;
		arrTbox[i] = tbox.options[i].text;
	}
	
	var fLength = 0;
	var tLength = arrTbox.length;

	for(i = 0; i < fbox.options.length; i++) {
		arrLookup[fbox.options[i].text] = fbox.options[i].value;
		if (fbox.options[i].selected && fbox.options[i].value != "") {
			arrTbox[tLength] = fbox.options[i].text;
			tLength++;
		}else {
			arrFbox[fLength] = fbox.options[i].text;
			fLength++;
		}
	}
	
	arrFbox.sort();
	arrTbox.sort();
	fbox.length = 0;
	tbox.length = 0;

	var c;
	
	for(c = 0; c < arrFbox.length; c++) {
		var no = new Option();
		no.value = arrLookup[arrFbox[c]];
		no.text = arrFbox[c];
		fbox[c] = no;
	}
	
	for(c = 0; c < arrTbox.length; c++) {
		var no = new Option();
		no.value = arrLookup[arrTbox[c]];
		no.text = arrTbox[c];
		tbox[c] = no;
    }
}	

function abrirJanelaSel(url, nomeJanela, height, width) { 
	if(!height)
		height = 250;
	if(!width)
		width = 520
	window.open(url, nomeJanela, "location=no,menubar=no,resizable=no,scrollbars=yes,top=0,left=180,height=" + height + ",width=" + width); 
}

function instr(str,s){
   var r   
   r = str.search(s);               //Search the string.
   return(r!=-1);                   //Return the Boolean result.
}

// Contador de caracteres
function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit) {
		field.value = field.value.substring(0, maxlimit);
	} else {
		countfield.value = maxlimit - field.value.length;
	}
}

function MascaraCpf(campo,tammax,teclapres) {
 var tecla = teclapres.keyCode;
  
 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 (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 ) ;}
 }  
}


function MascaraTel(campo,tammax,teclapres) {
 var tecla = teclapres.keyCode;
  
 vr = event.srcElement.value;
 vr = vr.replace( "-", "" );
 tam = vr.length;

 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 > 4) && (tam <= 5) ){
    event.srcElement.value = vr.substr( 0, tam - 1 ) + '-' + vr.substr( tam - 1, tam ) ; }
   
 }  
}


function FormataCNPJ(Campo, teclapres){

	var tecla = teclapres.keyCode;

	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace("/", "");
	vr = vr.replace("-", "");

	tam = vr.length + 1 ;

	
	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 6)
			Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
		if (tam >= 6 && tam < 9)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
		if (tam >= 9 && tam < 13)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
		if (tam >= 13 && tam < 15)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
		}
}

function FormataCNPJ2(Campo){
	var tecla = event.keyCode;

	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace("/", "");
	vr = vr.replace("-", "");

	tam = vr.length + 1 ;

	
	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 6)
			Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
		if (tam >= 6 && tam < 9)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
		if (tam >= 9 && tam < 13)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
		if (tam >= 13 && tam < 15)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
		}
}

// Utilizado para completar campos como CPF e CNPJ
function zeroEsquerda(campo, qtd) {
	while(campo.value.length < qtd) {
		campo.value = "0" + campo.value;
	}
}

function getData(entrada) {
   if (entrada!='')
   {
    var input = entrada.split('/');
    return new Date(input[2], input[1] - 1, input[0], 00, 00, 00);
   }
  }

function FormataData(Campo,teclapres) {
	var tecla = teclapres.keyCode;
//	vr = document.form[Campo].value;
	vr = event.srcElement.value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	tam = vr.length + 1;

	if ( tecla != 9 && tecla != 8 ){
		if ( tam > 2 && tam < 5 )
		{
//			document.form[Campo].value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
			event.srcElement.value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
		}
		if ( tam >= 5 && tam <= 10 )
		{
//			document.form[Campo].value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 ); }
			event.srcElement.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 );
		}
	}
} 

function datediff(start_date, end_date){
   d = getData(start_date)    //start date
   mill=getData(end_date)    //end date
   diff = mill-d    //difference in milliseconds
   mtg = new String(diff/86400000)    //calculate days and convert to string
   point=mtg.indexOf(".")    //find the decimal point
   if (point > 0){
    return mtg.substring(0,point);
   }
   else{
    if (mtg>=0) return mtg; else return '';
   }
 }

 function datediff2(start_date, end_date){
   d = getData(start_date)    //start date
   mill=getData(end_date)    //end date
   diff = mill-d    //difference in milliseconds
   mtg = new String(diff/86400000)    //calculate days and convert to string
   point=mtg.indexOf(".")    //find the decimal point
   if (point > 0){
    return mtg.substring(0,point);
   }
   else{
    if (mtg>=0) return mtg; else return 0;
   }
 }

function formatCurrency(field) {
	var sinal;	
	var num = field.value;
	
	if(num != '') {
		num = num.toString().replace(/\./g,'');
		num = num.toString().replace(/\,/g,'.');
	
		if(num.charAt(0) == '-')
			sinal = '-';
		else
			sinal = '';
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		if(cents<10)
			cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
			 num = num.substring(0,num.length-(4*i+3)) + '.' + num.substring(num.length-(4*i+3));
		field.value = sinal + num + ',' + cents;
	}
}

function formatData(field) {
	var data = field.value.split('/');
	var dia;
	var mes;
	var ano;

	if(data.length == 3) {
		dia = data[0];
		mes = data[1];
		ano = data[2];
	} else {
		mes = data[0];
		ano = data[1];
	}

	if(trim(field.value) == '') {
		return;
	}

	if(dia && String(dia).length < 2 && parseInt(dia) < 10) {
		dia = '0' + dia;
	}

	if(!mes || 0 > parseInt(mes) || parseInt(mes) > 12) {
		return;
	} 
	
	if(String(mes).length < 2 && parseInt(mes) < 10) {
		mes = '0' + mes;
	}

	if(!ano || parseInt(ano) < 0) {
		return;
	}
	
	if(String(ano).length < 3 && parseInt(ano) < 100){
		ano = '20' + ano;
	} 

	field.value = mes + '/' + ano;

	if(dia) {
		field.value = dia + '/' + field.value;
	}
}

function desabilitaComponentesForm(pForm, pDisabled, pComponenteExcluido) {
	  for (var i = 0; i < pForm.elements.length; i++) {
			if( pForm.elements[i].type == 'text' || pForm.elements[i].type == 'button' || 
				pForm.elements[i].type == 'select-one' || pForm.elements[i].type == 'textarea'
				|| pForm.elements[i].type == 'checkbox'){
				if ( pForm.elements[i].name !== pComponenteExcluido )
					pForm.elements[i].disabled = pDisabled;
			}
	  }
}

/* checkbox do topo da lista */
function checkBoxAll(obj, checkBxs) {
	if(checkBxs.length) {
		for(i = 0; i < checkBxs.length; i++) {
			checkBxs[i].checked = obj.checked;
		}
	} else {
		checkBxs.checked = obj.checked;
	}
}

/* 
	Recebe um array de objetos checkbox (Ex: document.frm.checkReg) e uma url (Ex: 'cadUsr.asp?id_usuario=').
*/
function chkBxEditar(checkBxs, url) {
	var cont = 0;
	var id;
	if(checkBxs.length) {
		for(i = 0; i < checkBxs.length; i++) {
			if(checkBxs[i].checked) {
				cont++;
				id = checkBxs[i].value;
			}	
		}
	} else {
		if(checkBxs.checked) {
			cont++;
			id = checkBxs.value;
		}	
	}
	
	if(cont < 1) {
		alert('É necessário a seleção de pelo menos 1 registro.');
	} else if(cont > 1) {
		alert('Selecione apenas 1 registro.');
	} else {
		window.navigate(url + id);
	}
}

/* 
	Recebe um array de objetos checkbox (Ex: document.frm.checkReg) e uma url (Ex: 'cadUsr.asp?id_usuario=').
*/
function chkBxExcluir(checkBxs, url) {
	var cont = 0;
	var ids = '';
	if(checkBxs.length) {
		for(i = 0; i < checkBxs.length; i++) {
			if(checkBxs[i].checked) {
				cont++;
				ids += checkBxs[i].value + ',';
			}	
		}
	} else {
		if(checkBxs.checked) {
			cont++;
			ids = checkBxs.value;
		}	
	}
	
	if(cont < 1) {
		alert('É necessário a seleção de pelo menos 1 registro.');
	} else {
		if(confirm('Confirma a exclusão do(s) registro(s)?'))
			window.navigate(url + ids)//.substring(0, ids.length - 1));
	}
}

/* 
	Recebe um array de objetos checkbox (Ex: document.frm.checkReg) e uma url (Ex: 'cadUsr.asp?id_usuario=').
*/
function chkBxAprovar(checkBxs, url) {
	var cont = 0;
	var ids = '';
	if(checkBxs.length) {
		for(i = 0; i < checkBxs.length; i++) {
			if(checkBxs[i].checked) {
				cont++;
				ids += checkBxs[i].value + ',';
			}	
		}
	} else {
		if(checkBxs.checked) {
			cont++;
			ids = checkBxs.value;
		}	
	}
	
	if(cont < 1) {
		alert('É necessário a seleção de pelo menos 1 registro.');
	} else {
		if(confirm('Confirma a aprovação do(s) registro(s)?'))
			window.navigate(url + ids)//.substring(0, ids.length - 1));
	}
}

function chkBxBoletos(checkBxs, url) {
	var cont = 0;
	var ids = '';
	if(checkBxs.length) {
		for(i = 1; i < checkBxs.length; i++) {
			if(checkBxs[i].checked) {
				cont++;
				ids += checkBxs[i].value + ',';
			}	
		}
	} else {
		if(checkBxs.checked) {
			cont++;
			ids = checkBxs.value;
		}	
	}
	
	if(cont < 1) {
		alert('É necessário a seleção de pelo menos um Boleto!');
	} else {		
			window.open(url + ids,'teste',' toolbar=no ,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=850,height=300,top=150,left=140');
	}
}

function FormataValor(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( ".", "" );

	if (vr.length > 0){ vr = parseInt(vr,10); }
	vr = '' + vr

	tam = vr.length;

	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 ){ 
	 		// document.form[campo].value = vr ; 
	 		//event.srcElement.value = vr ; 
			if (tam == 1){ 
				event.srcElement.value = "0,0" + vr ; 
			}else if (tam == 2){ 
				event.srcElement.value = "0," + vr ; 
			}else{
				event.srcElement.value = "" ; 
			}

		}
	 	if ( (tam > 2) && (tam <= 5) ){
	 		//document.form[campo].value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; 
	 		event.srcElement.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; 
		}
	 	if ( (tam >= 6) && (tam <= 8) ){
	 		//document.form[campo].value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; 
	 		event.srcElement.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; 
		}
	 	if ( (tam >= 9) && (tam <= 11) ){
	 		//document.form[campo].value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; 
	 		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) ){
	 		//document.form[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 ) ; 
	 		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) ){
	 		//document.form[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 ) ;
	 		event.srcElement.value = vr.substr( 0, tam - 15 ) + '.' + vr.substr( tam - 15, 3 ) + '.' + vr.substr( tam - 12, 3 ) + '.' + vr.substr( tam - 9, 3 ) + ',' + vr.substr( tam - 8, 0 )  ;
		}
	}		
}

// Exemplos:
// CEP
// OnKeyPress="formatar(this, '#####-###')"
// CPF
// OnKeyPress="formatar(this, '###.###.###-##')"

	function formatar(src, mask) 
		{
		 var i = src.value.length;
		 var saida = mask.substring(0,1);
		 var texto = mask.substring(i)
		 if (texto.substring(0,1) != saida) 
			{
				src.value += texto.substring(0,1);
			}
		}



// Funcoes CORP


function mask_generica(codigo,mascara){
  str = mascara;
  fim = str.length;
  valor = codigo.value;
  posicao = valor.length -1;
  tipo = str.charAt(posicao);
  
  if ((tipo == "a") || (tipo == "A")){
     if ((valor.charCodeAt(posicao) >= 48) && (valor.charCodeAt(posicao) <= 57) ||
		(valor.charCodeAt(posicao) >= 65) && (valor.charCodeAt(posicao) <= 90) ||
		(valor.charCodeAt(posicao) >= 97) && (valor.charCodeAt(posicao) <= 122)) {
		tipo = str.charAt(posicao+1);
             cont = posicao + 1;
		while ((tipo!="a") && (tipo!="A") && (tipo!="9") && (tipo!="") ) {
			codigo.value=codigo.value+tipo;
                    cont = cont + 1;
 		       tipo = str.charAt(cont);
		}
	 } else { 
		codigo.value = codigo.value.substr(0,posicao);
	 }
  } else {
	if (tipo == "9") {
		if ((valor.charCodeAt(posicao) >= 48) && (valor.charCodeAt(posicao) <= 57)) {
			tipo = str.charAt(posicao+1);
            cont = posicao + 1;
			while ((tipo!="a") && (tipo!="A") && (tipo!="9") && (tipo!="")) {
				codigo.value=codigo.value+tipo;
                           cont = cont + 1;
 	   	              tipo = str.charAt(cont);
			}
		} else { 
			codigo.value = codigo.value.substr(0,posicao);
		}
	} else {
        	tipo = str.charAt(posicao+1);
            cont = posicao + 1;
			while ((tipo!="a") && (tipo!="A") && (tipo!="9") && (tipo!="")) {
				codigo.value=codigo.value+tipo;
                           cont = cont + 1;
 	   	              tipo = str.charAt(cont);
			}
	}
  }
  codigo.value = codigo.value.substr(0,fim - 1) ;
  return true;
}


/**************************************************************
 Funcao que valida CPF e CGC com máscara 
 
 Parametros : frm - nome do formulario
			  acao - acao (INCLUIR/EXCLUIR/CONSULTAR/etc..)

*************************************************************/							  

function valida_CPF_mascara(tx_cpf){
		var cpf 
		
		cpf = tx_cpf.value
		
		cpf = cpf.replace(/\./g,"");
		cpf = cpf.replace("/","");
		cpf = cpf.replace(/-/g,"");
		if (!valida_cpf(cpf)){
			return false;
		}
	return true;
}



/**************************************************************
 Funcao que valida CPF e CGC
 
 Parametros : frm - nome do formulario
			  acao - acao (INCLUIR/EXCLUIR/CONSULTAR/etc..)

*************************************************************/							  
// funcao de validacao de cgc & cpf
var cpf_;
cpf_ = new Array(10);
cpf_[0]="11111111111";
cpf_[1]="22222222222";
cpf_[2]="33333333333";
cpf_[3]="44444444444";
cpf_[4]="55555555555";
cpf_[5]="66666666666";
cpf_[6]="77777777777";
cpf_[7]="88888888888";
cpf_[8]="99999999999";
cpf_[9]="00000000000";

//********* valida cpf
function valida_cpf(msCPF_CGC){
	if ((msCPF_CGC.length != 14) && (msCPF_CGC.length !=11)){
		return false;
	}

	if ((!(modulo(msCPF_CGC.substring(0,msCPF_CGC.length - 2)).toString()+modulo(msCPF_CGC.substring(0,msCPF_CGC.length - 1)).toString() == msCPF_CGC.substring(msCPF_CGC.length - 2,msCPF_CGC.length))) && (modulo_cic(msCPF_CGC.substring(0,msCPF_CGC.length - 2)) + "" + modulo_cic(msCPF_CGC.substring(0,msCPF_CGC.length - 1)) != msCPF_CGC.substring(msCPF_CGC.length - 2,msCPF_CGC.length))){
		return false;
	}
	return true;
}

function modulo(msCPF_CGC){
	soma=0;
	ind=2;

	for(pos=msCPF_CGC.length-1;pos>-1;pos=pos-1){
		soma = soma + (parseInt(msCPF_CGC.charAt(pos)) * ind);
		ind++;

		if(msCPF_CGC.length>11){
			if(ind>9) ind=2;
        }
	}

	resto = soma - (Math.floor(soma / 11) * 11);

	if(resto < 2){
		return 0;
	}
	else{
		return (11 - resto);
	}
}
function modulo_cic(msCPF_CGC){
   	soma=0;
	ind=2;

	for(pos=msCPF_CGC.length-1;pos>-1;pos=pos-1){
		 soma = soma + (parseInt(msCPF_CGC.charAt(pos)) * ind);
		 ind++;

		 if(msCPF_CGC.length>11){
		    if(ind>9) ind=2;
		 }
	}

	resto = soma - (Math.floor(soma / 11) * 11);

	if(resto < 2){
		return 0;
	}
	else{
		return 11 - resto;
	}
}


// -- *****************************
//  check for valid numeric strings	
function IsNumeric(strString)
   {
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
   }

// -- ********************************************
// -- Funcao que valida se a data eh ou nao valida

function isValidDate(dateStr, strDesc) {
	var datePat = /^(\d{2})(\/|-)(\d{2})\2(\d{4})$/;
	var matchArray = dateStr.match(datePat); 

	if (dateStr == '') {
	   return true;
	}
	if (matchArray == null) {
	   alert (strDesc + ' não é uma data válida no formato dd/mm/aaaa!')
	   return false;
	}
	day = matchArray[1];   // parse date into variables
	month = matchArray[3];
	year = matchArray[4];
	if (month < 1 || month > 12) { // check month range
	   alert('O mês de ' + strDesc + ' precisa estar entre 01 e 12.');
	   return false;
	}
	if (day < 1 || day > 31) {
	   alert('O dia de ' + strDesc + ' precisa estar entre 01 e 31.');
	   return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
	   alert ('O mês ' + month + ' em ' + strDesc + ' não tem 31 dias!')
	   return false
	}
	if (month == 2) { // check for february 29th
	   var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
	   if (day>29 || (day==29 && !isleap)) {
		  alert('Fevereiro do ano de ' + year + ' em ' + strDesc + ' não tem ' + day + ' dias!');
		  return false;
	   }
}
return true;  // date is valid
}


 
function abrirEditorTexto(descricao, valor) {
	window.open('../../include/editorTextoPopUp.asp?descricao=' + descricao + '&valor=' + valor, null, "location=no,menubar=no,resizable=no,scrollbars=yes,top=0,left=180,height=700,width=750");
}



function validarNumerico() {
	if (44 <= event.keyCode && event.keyCode <= 57) {
		if(event.keyCode == 45 || event.keyCode == 47) {
		 event.returnValue = false;
		} else {
		 event.returnValue = true;
		}
	} else {
		event.returnValue = false;
	}
}


function formatCurrencyValor(pValue) {
	var sinal;	
	var num = pValue;

	if(num != '') {
		num = num.toString().replace(/\./g,'');
		num = num.toString().replace(/\,/g,'.');
		if(num.charAt(0) == '-')
			sinal = '-';
		else
			sinal = '';
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		if(cents<10)
			cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
			 num = num.substring(0,num.length-(4*i+3)) + '.' + num.substring(num.length-(4*i+3));

		return (sinal + num + ',' + cents);
	}
}





function abreJanelaModal( pPagina, pnmJanela, pLargura, pAltura, pTopo, pEsquerda){

    var ltxtaux;

    if ( ( pAltura == -1 ) || ( pEsquerda == -1 ) ) 
      ltxtaux = ";center:1";
    else ltxtaux = ";dialogTop:"+pTopo+"px;dialogLeft:"+pEsquerda+"px"; 
    return window.showModalDialog( pPagina, pnmJanela, "dialogWidth:"+pLargura+"px;dialogHeight:"+pAltura+"px;scroll:1;help:0;status:0"+ltxtaux );
}

function abrePopCad( pPagina, pnmJanela, pLargura, pAltura, pTopo, pEsquerda, pIframe, pMetodo, pCodigo,pModulo){
    var objIframe
	if (abreJanelaModal(pPagina, pnmJanela, pLargura, pAltura, pTopo, pEsquerda)) {;
      objIframe = eval("document.all."+pIframe);
      objIframe.src = pModulo+"/include/popcombo.asp?metodo="+pMetodo+"&codigo="+pCodigo;
	}
}




/*FUNCOES DE FORMATAÇÃO DE NUMERO*/
function fn_monta_inteiro( valor )
{
   var tam     = valor.length;
   var qtd     =  tam / 3 ;
   var posicao = 0;
   for ( lnx = 1 ; ( lnx < qtd ) ; lnx++)
   {
	  valor = valor.substring( 0, valor.length - (( 3 * lnx )+posicao) ) + '.' + valor.substring( valor.length - (( 3 * lnx ) + posicao++) );
   } 
   return valor;
}
   
function delMascara( strValue ) 
{

  var objRegExp = new RegExp( "\\.", "g" ); 

  return strValue.replace(objRegExp,'');
  
 }


function addMascara( strValue ) 
{
   strValue = delMascara( strValue );

   // Inicio da Mudanca na Mascara 15/05/2003
   lnegativo = "";
   if ( strValue.length > 1 )
   {
      if ( strValue.substring(0,1) == '-' )        
      {           
	     lnegativo = "-";                               
         strValue = strValue.substring( 1 );     
	  }                                          
   }
   // Final da Mudanca na Mascara 15/05/2003
   
   if ( strValue.indexOf( ',' ) != -1  )
      {
	      valor = strValue.substring( 0, strValue.indexOf( ',' )  );
		  fraca = strValue.substring( strValue.indexOf( ',' )  );
	   }	  
	else   
	   {
	     valor = strValue;
		 fraca = "";
	    }	
		
    if (( fraca != "" ) && ( valor == "" )) 
	   valor = "0";
	   
	// strValue  = fn_monta_inteiro( valor ) + fraca;	        // Mudanca na Mascara 15/05/2003  
	strValue  = lnegativo + fn_monta_inteiro( valor ) + fraca;  // Mudanca na Mascara 15/05/2003  
	
  return strValue;
}

function trata_selecao( pcampo, pselecao, ptecla, pisselecao )
{
    /*if ( pisselecao )
    {
	   document.selection.clear();	   	   
	   pselecao.text = String.fromCharCode( ptecla );
       pcampo.value = addMascara( pcampo.value ) ; 
	   pselecao = null;
	}
    return pisselecao;*/
}

function formataMoeda( campo, tammax, decimal, teclapres) 
{
	var vr        = new String( delMascara( campo.value ) );  
	var tecla     = 0;
	var maxint    = tammax - decimal;
	var isvirg    = false;
	var qtddig    = 0;
	var qtdint    = 0;
	var selecao   = null;
	var isselecao = false;
	var virgsele  = false;


	if ( navigator.appName=="Netscape" )
	{
	   tecla     = teclapres.which;
       //selecao   = document.getSelection();	   

	}
	else
	{
	   tecla     = teclapres.keyCode;
       selecao   = document.selection.createRange().duplicate();
	}
    /************************************************************************
       	         Verifica a Existencia de selecao neste campo 	
    ************************************************************************/
	if ( navigator.appName!="Netscape" )
    {
      if ( selecao.text != "" )
	  {
    	 if ( selecao.parentElement().name == campo.name )
	     {
	        isselecao = true;
	        if ( selecao.text.indexOf( ',' ) != -1 ) 
	           virgsele = true; 
		  
	    }
	 }   
   }	 


	// Pressionado o Back-Space
	if ( tecla == 8 ) 
	   return true; 

	   
	if ( selecao != null ) 
	{
	   ltamsele = selecao.text.length;
	}   
	else
	{
	   ltamsele = 0;	
	}

	// Inicio da Mudanca na Mascara 15/05/2003   
    if ( ( vr.length == 0 ) || ( campo.value.length == ltamsele ) )
	{
	
	   if ( tecla == 45 )
	   {
	      return true;
	   }
	}
    // Inicio da Mudanca na Mascara 15/05/2003
	
	// Se ja existe virgula no texto pega as qtd de inteiro e decimal se nao existe coloca zero
    if ( vr.indexOf( ',' )  != -1)  
    {
       isvirg = true;
       qtddig = vr.length - vr.indexOf( ',' ) -1 ;
       qtdint = vr.indexOf( ',' );
	}
	else
	{
   	   qtdint  = vr.length ;
	}
	// Se a qtd digitada for menor que o tamanho do campo ou houver selecao ele aceita 
	if ( ( vr.length <= tammax ) || ( isselecao ) )	
	{

	    if ( ( tecla == 44 ) && ( decimal != 0 ) ) 
		{
	       // Se ja existe uma virgula e a tecla pressionada e virgula ou existe uma virgula na selecao 
   	       if ( ( isvirg ) && ( virgsele ) )		   
		      return true;
			  
		   if ( ( !isvirg ) || ( virgsele ) )	  
		      return true;
		
		   return false;	  
		}
	    if ( ( tecla >= 48 ) && ( tecla <= 57 ) )
		{
		   if ( ( isvirg ) && ( qtddig >= decimal ) && ( !virgsele ) )
		      return false;


		   if ( ( ( isvirg ) && ( qtddig <= decimal ) ) || ( isselecao ) )
		      return true;
			  
		   if ( ( ( !isvirg ) && ( qtdint < maxint ) ) || ( isselecao ) )
		      return true;
			  
			  
  		   return false;
		}
		
		return false;
				   
	}
	else 
	{
	   return false;
	}

	
}	

	
function fn_MostraMascara( campo, tecla )
{

   // Acrescentou na Mudanca na Mascara 15/05/2003 
   // ( ( tecla.keyCode == 45 ) || ( tecla.keyCode == 109 ) ) )

   if ( (tecla.keyCode==8) || ( ( tecla.keyCode >= 48 ) && ( tecla.keyCode <= 57 )) || 
      ( ( tecla.keyCode >= 96 ) && ( tecla.keyCode <= 105 )) ||
      ( tecla.keyCode == 44 ) || ( ( tecla.keyCode == 45 ) || ( tecla.keyCode == 109 ) ) || ( tecla.keyCode == 46 ) )
   { 
	 campo.value = addMascara( campo.value ) ;
   }  
	return true;
}

function mask_mes_ano(field){
  var numero = new Array ();
  var str = field.value.replace("/","")
  
	//permite o backspace
	if (event.keyCode  == 13){
		numero.pop();
		return true;   
	}
	
	//coloca / no vetor, se o cara digitar na posicao correta
	if ((str.length == 2) && (event.keyCode == 47)){
		numero.push("/");	    	
		return true;		
	}
		
	//testa se é um numero de 0 a 9
	if ((event.keyCode  < 48) || (event.keyCode  > 57)){  
		field.focus();     
		return false
	}   		


	//coloca toda a string num vetor	
	for (i=0; i<str.length; i++){
		numero.push(str.substring(i, i+1));
		if (i == 1)
			numero.push("/");	    
	}

field.value = numero.join("");
return true;
}






