
// 
// Function.: Permite a digitação somente de números, sem hífen ou pontuação
// Usage....: <input type="text" onKeypress="return checkDigit(event)">
// Exception: nenhuma
function checkDigit(event)
{
  if (window.event.keyCode == 13) return (0)
  if ((window.event.keyCode < 48) || (window.event.keyCode > 57)) window.event.keyCode = 0
}

// Zera o campo se igual a ''
function zeraDigit(obj){
	if (obj.value==''){
		obj.value='0';
	}
}


// Zera o campo se igual a ''
function zeraDigitVal(obj){
	if (obj.value==''){
		obj.value='0,00';
	}
}



// Tira Brancos da frente e de trás
function trim(val){

	if(val==null){
		return val;
	}

	var i1, i2;
	i1=-1;
	i2=val.length;

	for(var i=0; i<val.length; i++){
		if(val.substring(i, i+1)!=' '){
			i1=i;
			break;
		}	
	}

	for(var i=val.length-1; i>=0; i--){
		if(val.substring(i, i+1)!=' '){
			i2=i;
			break;
		}	
	}

	if(i1==-1){
		return '';
	}
	
	i2=i2+1;
	return val.substring(i1, i2);
}


// Transforma a digitação para maiúsculas ao perder o foco
// Ex: onblur="uppercase(this)"
function uppercase(obj){
	if((/[^0-9A-Z] /.test(obj.value))){
		obj.value=obj.value.toUpperCase()
	}else{
		if((/[^0-9A-Z]/.test(obj.value))){
			obj.value=obj.value.toUpperCase()
		}
	}
}


// Compara 2 datas ("dd/MM/yyyy") e retorna -1 se 1a>2a, 0 se iguais, 1 se 1a<2a.
function comparaDatas(dat1, dat2){
	var d1, d2;
	d1 = dat1.substring(6,10) + dat1.substring(3,5) + dat1.substring(0,2);
	d2 = dat2.substring(6,10) + dat2.substring(3,5) + dat2.substring(0,2);
	if(d1>d2){return -1;}
	if(d1==d2){return  0;}
	if(d1<d2){return  1;}
	return 0;
}
//Devolve o intervalo de duas datas 
//Observação: recebe as datas no formato 
// - MM/DD/YYYY
function dataDiff(Date1,Date2)

{       
             var Diff
             var Date1 = Date.parse(Date1);
             var Date2 = Date.parse(Date2);
             Diff = ((Date2-Date1)/(24*60*60*1000)); 
             if(Diff < 0 )Diff = Diff *(-1);
             return Diff;   
}
//Transforma a data do formato DD/MM/YYYY par os 
//formatos MM/DD/YYYY Ou YYYY/MM/DD Ou  YYYYMMDD 
function datFormat(str,ConvertTo)
{
	var dia="";
	var mes="";
	var ano="";
	var data="";
	 
	
    ano = str.substring(6)
	mes = str.substring(5,3)
	dia = str.substring(0,2)
	
	if(ConvertTo==1) data = mes + "/" + dia + "/" + ano;
	if(ConvertTo==2) data = ano + "/" + mes + "/" + dia;
	if(ConvertTo==3) data = mes + "/" + dia + "/" + ano;
	
	return data;    
}
// Formata campo HORA, no momento da digitação
// Utilizar como : onkeydown="javascript:MaskHora(formX.txtX,12,2,event)"
// A dica é colocar o textbox alinhado à direita: style="text-align:right"
function MaskHora(campo,tammax,pos,teclapres){
	var tecla = teclapres.keyCode;
	vr = campo.value;
	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 == 88 || tecla >= 48 && tecla <= 57  ){
		if ( tam <= 2 ){
	 		campo.value = vr ;}
		if ( tam > pos && tam <= tammax ){
			campo.value = vr.substr( 0, tam - pos ) + ':' + vr.substr( tam - pos, tam );}
	}
}        


// Formata campo digitado em horas (HH:MM)
// Utilizar como : onBlur="JavaScript: fmtHR(this);"
function fmtHR(objHR) {

	var sTmpHoras
	var sTmpRet

	var sHoras
	var sMinutos

	// Obtém cadeia
	sTmpHoras = new String(objHR.value)

	// Força atribuição do formato hora, caso a digitação seja inferior a 24, formatando para 23:00 (p.ex.)
	if(!(sTmpHoras=='' || sTmpHoras=='-' || sTmpHoras==':'))
		if(sTmpHoras.length<=2)
			if(eval(objHR.value)<24) sTmpHoras+='00'

	// Campo vazio?
	if(sTmpHoras=='' || sTmpHoras=='-' || sTmpHoras==':') {
		objHR.value=''
		return(0)
	}

	// Retira caracter separador da hora
	sTmpHoras = sTmpHoras.replace('-','')
	sTmpHoras = sTmpHoras.replace(':','')
	sTmpRet = ''

	// Somente minutos
	if(sTmpHoras.length<=2) {
		// Verifica se a quantidade de minutos não ultrapassa 59
		if(eval(sTmpHoras)>59) {
			alert('A quantidade de minutos não pode ultrapassar 59.')
			objHR.value=''
			objHR.focus()
			return(0)
		}

		// Ajusta para duas posições os minutos
		for (var nCount=0; nCount < sTmpHoras.length; nCount++) {
			sTmpRet = sTmpRet + '0'
		}

		sTmpHoras = sTmpRet + ':' + sTmpHoras
	}
	else
	{
		// Horas e minutos
		sMinutos = new String(sTmpHoras)
		sMinutos = sMinutos.substr(sMinutos.length-2,2)

		// Verifica se a quantidade de minutos não ultrapassa 59
		if(eval(sMinutos)>59) {
			alert('A quantidade de minutos não pode ultrapassar 59.')
			objHR.value=''
			objHR.focus()
			return(0)
		}

		sHoras = new String(sTmpHoras)
		sHoras = sHoras.substr(0,sHoras.length-2)

		sTmpHoras = sHoras + ':' + sMinutos
	}


	// Comple com +1 "0" à esquerda
	if(sTmpHoras.length==4) {
		sTmpHoras='0'+sTmpHoras
	}

	objHR.value = sTmpHoras
}



// Converte Horas (formato HH:MM) em Minutos (formato numérico)
function ConvHR2NUM(sHoras) {

	var nPos
	var sTmpHoras
	var sTmpMinutos
	var nHoras
	var nMinutos

	// Obtém cadeia
	sTmpHoras = new String(sHoras)

	// Determina posição do delimitador :
	nPos = sTmpHoras.indexOf(":",0)

	// Obtém horas
	nHoras=0
	if(nPos>0) {
		nHoras = eval(sTmpHoras.substring(0, nPos))
		nHoras = nHoras * 60
	}

	// Obtém cadeia
	sTmpMinutos = new String(sHoras)

	// Determina posição do delimitador :
	nPos = sTmpMinutos.indexOf(":",0)

	// Obtém minutos
	nMinutos=0
	if(nPos>0) {
		nMinutos = eval(sTmpMinutos.substring(nPos+1, sTmpMinutos.length))
	}

	return nHoras + nMinutos
}


// Formata Mês/Ano
// Alteração: Se maxlength == 10 então trata como dia/mes ou dia/mes/ano
// Usage..: <input type="text" name="x" onkeypress="MesAnoFormata(this)" maxlangth="10">

function MesAnoFormat(txt) {
	// Ao Digitar LETRAS não passa nenhum valor
		 if ((event.keyCode < 48) || (event.keyCode > 57))
			event.returnValue = false;
			else if (txt.value.length == 2) 
				// Adiciona "/" na Data
				txt.value += '/';
	            if (txt.value.length==5 && txt.maxLength==10) txt.value+='/'
	            
}


// Permite a digitação somente de números ou, no máximo, uma vírgula ou um hífen
function checkDigitVal(valor)
{
  if (event.keyCode == 13) return (0);
  if ((event.keyCode >= 48) && (event.keyCode <= 57))
  	 {return(0);}
  if (event.keyCode == 44) // Vírgula
	if (valor.value.indexOf(',')==-1) {return(0)}
  if (event.keyCode == 45) return(0) // Hífen
event.keyCode = 0;
}

// Remove PONTO do formato MOEDA (para milhar) e substitui VIRGULA por PONTO para decimal
// Necessário quando se faz uma soma de valores através de JS
function parseMoney(obj) {
	var num=obj
	stmp=new String(num)
	stmp=stmp.replace('.','')
	stmp=stmp.replace(',','.')
	return stmp
}


// Permite a formatação de um número no formato Moeda
function formatCurrency(obj1) {

	var num = obj1.value;
	var isNegative = false;

	// Retira pontuação para efetuar a verificação com um número 'puro'
	sTmp = new String(num)
	sTmp = sTmp.replace('.','')
	sTmp = sTmp.replace(',','.')
	num = sTmp

	// Caso não tenha digitado número
	if( isNaN( num ) ) {
		num = "0";
	}

	// Caso número negativo
    if ( num < 0 ) {
      num = Math.abs( num );
      isNegative = true;
    }

	// Obtém trechos do número
    cents = Math.floor( ( num * 100 + 0.5 ) % 100 );
    num = Math.floor( ( num * 100 + 0.5 ) / 100 ).toString();
    if ( cents < 10 ) {
      cents = "0" + cents;
    }
    for ( 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 ) );
    }

	// Prepara cadeia de saída
	var result = '' + num + ',' + cents;
	if ( isNegative ) {
	  result = "-" + result;
	}
	return result;
}



/**
* Script pronto transforma  2195440.3517 para 2.195.440,35
* Javascript prototypes - String.pad() and Number.format()
* 
*
*/
String.PAD_LEFT  = 0;
String.PAD_RIGHT = 1;
String.PAD_BOTH  = 2;

String.prototype.pad = function(size, pad, side) {
  var str = this, append = "", size = (size - str.length);
  var pad = ((pad != null) ? pad : " ");
  if ((typeof size != "number") || ((typeof pad != "string") || (pad == ""))) {
    throw new Error("Wrong parameters for String.pad() method.");
  }
  if (side == String.PAD_BOTH) {
    str = str.pad((Math.floor(size / 2) + str.length), pad, String.PAD_LEFT);
    return str.pad((Math.ceil(size / 2) + str.length), pad, String.PAD_RIGHT);
  }
  while ((size -= pad.length) > 0) {
    append += pad;
  }
  append += pad.substr(0, (size + pad.length));
  return ((side == String.PAD_LEFT) ? append.concat(str) : str.concat(append));
}

Number.prototype.format = function(d_len, d_pt, t_pt) {
  var d_len = d_len || 0;
  var d_pt = d_pt || ".";
  var t_pt = t_pt || ",";
  if ((typeof d_len != "number")
    || (typeof d_pt != "string")
    || (typeof t_pt != "string")) {
    throw new Error("wrong parameters for method 'String.pad()'.");
  }
  var integer = "", decimal = "";
  var n = new String(this).split(/\./), i_len = n[0].length, i = 0;
  if (d_len > 0) {
    n[1] = (typeof n[1] != "undefined") ? n[1].substr(0, d_len) : "";
    decimal = d_pt.concat(n[1].pad(d_len, "0", String.PAD_RIGHT));
  }
  while (i_len > 0) {
    if ((++i % 3 == 1) && (i_len != n[0].length)) {
      integer = t_pt.concat(integer);
    }
    integer = n[0].substr(--i_len, 1).concat(integer);
  }
  return (integer + decimal);
}




// Permite a formatação de um número no formato Moeda vindo através de uma variavel numerica
function formatCurrencyNumber2Text(num) {

	var isNegative = false;

	// Retira pontuação para efetuar a verificação com um número 'puro'
	sTmp = new String(num)
	sTmp = sTmp.replace('.','')
	sTmp = sTmp.replace(',','.')
	num = sTmp

	// Caso não tenha digitado número
	if( isNaN( num ) ) {
		num = "0";
	}

	// Caso número negativo
    if ( num < 0 ) {
      num = Math.abs( num );
      isNegative = true;
    }

	// Obtém trechos do número
    cents = Math.floor( ( num * 100 + 0.5 ) % 100 );
    num = Math.floor( ( num * 100 + 0.5 ) / 100 ).toString();
    if ( cents < 10 ) {
      cents = "0" + cents;
    }
    for ( 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 ) );
    }

	// Prepara cadeia de saída
	var result = '' + num + ',' + cents;
	if ( isNegative ) {
	  result = "-" + result;
	}
	return result;
}

// Permite a digitação somente de letras (sem acentos) 
function checkDigitL(){
	if ((event.keyCode >= 65) && (event.keyCode <= 90)) return(0); //LETRAS MAISC.
    if ((event.keyCode >= 97) && (event.keyCode <= 122)) return(0); //LETRAS MINUSC.
    event.keyCode = 0;
}

//Verifica se ao campo possui um valor menor que 100
function ValidaPorcentagem(num) {
	if(num.value>100){
		alert('Valor Inválido. Deve ser menor que 100.');
		num.value='';
		num.focus();
	}
}

// Checa todos os checkboxes da página
function checkaTodos(form,chkPai) {
	f = form;
	for (i=0; i<f.length; i++){
		if (f.elements[i].type == "checkbox" && f.elements[i].disabled==false){
			if (f.elements[i].name != chkPai.name){
				if (chkPai.checked == true) {
		     			f.elements[i].checked = true
				}else{
			     		f.elements[i].checked = false
				}
	   		}
	  	}
	}
}

//Valida valor máximo
function validaMax(valor,i,Max){
	var nvalor;
	nvalor=parseFloat((valor.value).replace(',','.'),10)
			
	if(nvalor > Max){
		alert('Digite um valor menor ou igual a ' + Max + '.');
		//Verifica se existe disponibilidade de i´s 
		if(i==-1){
			eval('frmMain.'+ valor.name +'.value=\'\'');
			eval('frmMain.'+ valor.name +'.focus()');
		}else{
			eval('frmMain.'+ valor.name +'[i].value=\'\'');
			eval('frmMain.'+ valor.name +'[i].focus()');
		}
		return(0);		
	}	
}

// Torna visível ou invisível os campos em função do checkbox (seleção)
function HabilitaTable(objCheck,objTable) {
	if(objCheck.checked)
		objTable.style.display=''
	else
	objTable.style.display='none'
}

// Bloqueia checkbox sem desabilitar o envio de valores
function doTrava(item){ 
	if (item.checked) { 
		item.checked = false; 
	} else{ 
		item.checked = true; 
	}
} 

//Obtém o índice Checked num Radio informado
function indexChecked(obj){
	var iChecked=-1;
	for(i=0; i<obj.length; i++){
		if(obj[i].checked){
			iChecked=i;
			break;
		}
	}
	return iChecked;
}

//Mostra Status
function mostraStatus(string){
	window.status=string
}

// Permite a formatação de um campo para valor monetário
function FormataValor(campo,teclapres) {
	var tecla = teclapres.keyCode;
	var tammax = 17;
	
	// Remove caracteres inválidos
	vr = campo.value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	tam = vr.length;

	// Proporciona backspace	 
	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }
	if (tecla == 8 ){ tam = tam - 1 ; }

	// Efetua a formatação dos dados	  
	if ( 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.: Permite apenas digitação de letra maiúscula e números
// Usage....: <input type="text" onattrmodified="UpperLetterNumber(this)" onpropertychange="UpperLetterNumber(this)">
// Exception: Funciona somente no IE6
function UpperLetterNumber(o){
	if(/[^0-9A-Z]/.test(o.value))
	  o.value=o.value.toUpperCase().replace(/([^0-9A-Z])/g,"")
}

// Function.: Permite validação do CPF
// Usage....: <input type="text" onblur="if(!cpf(this)) alert('CPF inválido')">
// Exception: nenhuma
function valida_cpf(pcpf) {

	if (pcpf.length != 11) sim=false
	else sim=true

	if (sim) {
		for (i=0; i<=(pcpf.length-1) && sim; i++) {
			val=pcpf.charAt(i)

		if ((val!="9") && 
		    (val!="0") &&
            (val!="1") &&
            (val!="2") &&
            (val!="3") &&
            (val!="4") &&
            (val!="5") &&
            (val!="6") &&
            (val!="7") &&
            (val!="8") ) sim=false
		}

		if (sim) {
			soma = 0
			for (i=0;i<=8;i++) {
				val = eval(pcpf.charAt(i))
				soma = soma + (val*(i+1))
			}

			resto = soma % 11
			if (resto>9) dig = resto -10
			else dig = resto

			if (dig != eval(pcpf.charAt(9))) sim=false
			else {
				soma = 0
				for (i=0;i<=7;i++) {
					val = eval(pcpf.charAt(i+1))
					soma = soma + (val*(i+1))
				}	
				soma = soma + (dig * 9)
				resto = soma % 11
				if (resto>9) dig = resto -10
				else dig = resto
	
				if (dig != eval(pcpf.charAt(10))) sim = false
				else sim = true
			}
		}
	}

	if (sim) return(true)
	else return(false)
}

// Function.: Permite digitação em máscara CPF
// Usage....: <input type="text" name="cpf" onKeyUp="mascara_cpf(this.value)" maxlength="14" size="15">
// Exception: existe um problema ao excluir o CPF, pois quando chegamos na posição do "." ele não permite...
//            a solução é manter o backspace pressionado para não disparar o evento.
function mascara_cpf(cpf)
{
    var mycpf = '';
    mycpf = mycpf + cpf.value;
    if (mycpf.length == 3) {
        mycpf = mycpf + '.';
        cpf.value = mycpf;
    }
    if (mycpf.length == 7) {
        mycpf = mycpf + '.';
        cpf.value = mycpf;
    }
    if (mycpf.length == 11) {
        mycpf = mycpf + '-';
        cpf.value = mycpf;
    }
}

// Function.: Permite digitação em máscara CNPJ
// Usage....: <input type="text" name="cnpj" onKeyUp="mascara_cnpj(this)" maxlength="19" size="20">
// Exception: existe um problema ao excluir o CNPJ, pois quando chegamos na posição do "." ele não permite...
//            a solução é manter o backspace pressionado para não disparar o evento.
function mascara_cnpj(cnpj)
{
    var mycnpj = '';
    mycnpj = mycnpj + cnpj .value;
    if (mycnpj .length == 2) {
        mycnpj = mycnpj + '.';
        cnpj.value = mycnpj; 
    }
    if (mycnpj .length == 6) {
        mycnpj = mycnpj + '.';
        cnpj.value = mycnpj;
    }
    if (mycnpj .length == 10) {
        mycnpj = mycnpj + '/';
        cnpj.value = mycnpj;
    }
    if (mycnpj .length == 15) {
        mycnpj = mycnpj + '-';
        cnpj.value = mycnpj;
    }
}

// Function.: Permite digitação em máscara IM (Inscrição Municipal) e IE (Inscrição Estadual)
// Usage....: <input type="text" name="im" onKeyUp="mascara_imie(this)" maxlength="15" size="16">
// Exception: existe um problema ao excluir a IM/IE, pois quando chegamos na posição do "." ele não permite...
//            a solução é manter o backspace pressionado para não disparar o evento.
function mascara_imie(imie)
{
    var myimie= '';
    myimie = myimie + imie.value;
    if (myimie.length == 3) {
        myimie = myimie + '.';
        imie.value = myimie;
    }
    if (myimie.length == 7) {
        myimie = myimie + '.';
        imie.value = myimie;
    }
    if (myimie.length == 11) {
        myimie = myimie + '.';
        imie.value = myimie;
    }
}

// Function.: Permite digitação em máscara CEP
// Usage....: <input type="text" name="cep" onKeyUp="mascara_cep(this)" maxlength="9" size="10">
// Exception: existe um problema ao excluir o CEP, pois quando chegamos na posição do "." ele não permite...
//            a solução é manter o backspace pressionado para não disparar o evento.
function mascara_cep(cep)
{
    var mycep= '';
    mycep = mycep + cep.value;
    if (mycep.length == 5) {
        mycep = mycep + '-';
        cep.value = mycep;
    }
}

// Function.: Permite digitação em máscara de valor
// Usage....: <input type="text" name="cep" style="text-align:right" onKeyPress="javascript:return mascara_moeda(this,'','.',event)" maxlength="9" size="10">
// Exception: nenhum.
function mascara_moeda(fld, milSep, decSep, e)
{
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13) return true;  // Enter
    key = String.fromCharCode(whichCode);  // Get key value from key code
    if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
    len = fld.value.length;
    for(i = 0; i < len; i++)
        if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) fld.value = '';
    if (len == 1) fld.value = '0'+ decSep + '0' + aux;
    if (len == 2) fld.value = '0'+ decSep + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
            aux2 += milSep;
            j = 0;
            }
        aux2 += aux.charAt(i);
        j++;
        }
        fld.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        fld.value += aux2.charAt(i);
        fld.value += decSep + aux.substr(len - 2, len);
    }
	return false;
}
// Function:Permite formatar o campo telefone
// Usage:..:<input type="text" name="a"  onkeyup="mask_tel(this);"  maxlength="14">
// Exeption:Nenhum
 
function mask_tel(obj)
{
    var mask; 
    mask=obj.value;
    
        if(mask.length==1){mask = '('+ mask;}
        if(mask.length==3){mask=mask +')';}
        if(mask.length==4){mask=mask + " ";}
        if(mask.length==9){mask = mask +'-';}
        
    obj.value=mask;
}

// Permite a digitação em formato de máscara
function mask(str,textbox,loc,delim){
	var locs = loc.split(',');

	for (var i = 0; i <= locs.length; i++){
		for (var k = 0; k <= str.length; k++){
		 if (k == locs[i]){
		  if (str.substring(k, k+1) != delim){
		    str = str.substring(0,k) + delim + str.substring(k,str.length)
		  }
		 }
		}
	 }
	textbox.value = str
}

//Premite a Validação do email 
// Usage:..:<input type="text" name="DES_EMAIL"  onBlur="valida_email(this)" >
function valida_email(obj)
    {
        email = obj.value;
        delim=''
        p=''
        if(obj.value!=''){
        for(i=0;i<=email.length;i++)
        {
 
            if(email.charAt(0)=='.' ||email.charAt(0)=='@' ){alerta(obj);return false;}
            if(email.charAt(i)=='@')
            {  
                delim='@'
                if(email.charAt(i)=='@' && email.charAt(i+1)=='.'){alerta(obj);return false;}
            }
          
         if(delim=='@')
         {
            if(email.charAt(i)=='.')
            { 
               p=p+1
               if(email.charAt(i+1)==''){alerta();return false;}
               if(email.charAt(i)=='.'&& email.charAt(i+1)=='.'){alerta(obj);return false;}
            } 
         }
            
            
         if(email.charAt(i)==';' ||
            email.charAt(i)==',' || 
            email.charAt(i)=='*' ||
            email.charAt(i)==']' ||
            email.charAt(i)=='[' ||
            email.charAt(i)=='(' ||
            email.charAt(i)==')' ||
            email.charAt(i)=='/' ||
            email.charAt(i)=='|' ||
            email.charAt(i)=='´' ||
            email.charAt(i)=='^' ||
            email.charAt(i)=='+' ||
            email.charAt(i)=='?' ||
            email.charAt(i)=='~' ||
            email.charAt(i)=='-' ||
            email.charAt(i)=='¨' ||
            email.charAt(i)=='*' ||
            email.charAt(i)=='!' 
           ){alerta(obj);return false;}
        }
              
        if(delim==''){alerta(obj);return false;} 
        if(p==''){alerta(obj);return false;}
        }
    }
 function alerta(obj)
   {
        alert("Digite um endereço eletrônico válido.");
        obj.value='';
        return false;
   }