function currencyFormat(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;
var whichCode = (window.addEventListener) ? e.which : e.keyCode;
//alert(whichCode);
if (whichCode == 13) return true;  // Enter
if (whichCode == 8) 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 validaData(str) { 

	dia = (str.value.substring(0,2)); 
    mes = (str.value.substring(3,5)); 
	ano = (str.value.substring(6,10)); 

	cons = true; 
	
	// verifica se foram digitados números
	if (isNaN(dia) || isNaN(mes) || isNaN(ano)){
		alert("Preencha a data somente com números."); 
		str.value = "";
		str.focus(); 
		return false;
	}
		
    // verifica o dia valido para cada mes 
    if ((dia < 01)||(dia < 01 || dia > 30) && 
		(mes == 04 || mes == 06 || 
		 mes == 09 || mes == 11 ) || 
		 dia > 31) { 
    	cons = false; 
	} 

	// verifica se o mes e valido 
	if (mes < 01 || mes > 12 ) { 
		cons = false; 
	} 

	// verifica se e ano bissexto 
	if (mes == 2 && ( dia < 01 || dia > 29 || 
	   ( dia > 28 && 
	   (parseInt(ano / 4) != ano / 4)))) { 
		cons = false; 
	} 
    
	if (cons == false) { 
		alert("A data inserida não é válida: " + str.value); 
		str.value = "";
		str.focus(); 
		return false;
	} 
}

// colocar no evento onKeyUp passando o objeto como parametro
function formata(val)
{
   	var pass = val.value;
	var expr = /[0123456789]/;
		
	for(i=0; i<pass.length; i++){
		// charAt -> retorna o caractere posicionado no índice especificado
		var lchar = val.value.charAt(i);
		var nchar = val.value.charAt(i+1);
	
		if(i==0){
		   // search -> retorna um valor inteiro, indicando a posição do inicio da primeira
		   // ocorrência de expReg dentro de instStr. Se nenhuma ocorrencia for encontrada o método retornara -1
		   // instStr.search(expReg);
		   if ((lchar.search(expr) != 0) || (lchar>3)){
			  val.value = "";
		   }
		   
		}else if(i==1){
			   
			   if(lchar.search(expr) != 0){
				  // substring(indice1,indice2)
				  // indice1, indice2 -> será usado para delimitar a string
				  var tst1 = val.value.substring(0,(i));
				  val.value = tst1;				
 				  continue;			
			   }
			   
			   if ((nchar != '/') && (nchar != '')){
				 	var tst1 = val.value.substring(0, (i)+1);
				
					if(nchar.search(expr) != 0) 
						var tst2 = val.value.substring(i+2, pass.length);
					else
						var tst2 = val.value.substring(i+1, pass.length);
	
					val.value = tst1 + '/' + tst2;
			   }

		 }else if(i==4){
			
				if(lchar.search(expr) != 0){
					var tst1 = val.value.substring(0, (i));
					val.value = tst1;
					continue;			
				}
		
				if	((nchar != '/') && (nchar != '')){
					var tst1 = val.value.substring(0, (i)+1);

					if(nchar.search(expr) != 0) 
						var tst2 = val.value.substring(i+2, pass.length);
					else
						var tst2 = val.value.substring(i+1, pass.length);
	
					val.value = tst1 + '/' + tst2;
				}
   		  }
		
		  if(i>=6){
			  if(lchar.search(expr) != 0) {
					var tst1 = val.value.substring(0, (i));
					val.value = tst1;			
			  }
		  }
	 }
	
     if(pass.length>10)
		val.value = val.value.substring(0, 10);
	 	return true;
}

//Formata número tipo moeda usando o evento onKeyDown

 function formatamoney(c) {  
     var t = this; if(c == undefined) c = 2;        
     var p, d = (t=t.split("."))[1].substr(0, c);  
     for(p = (t=t[0]).length; (p-=3) >= 1;) {  
            t = t.substr(0,p) + "." + t.substr(p);  
     }  
     return t+","+d+Array(c+1-d.length).join(0);  
 }  
   
 String.prototype.formatCurrency=formatamoney  
   
 function demaskvalue(valor, currency){  
 /* 
 * Se currency é false, retorna o valor sem apenas com os números. Se é true, os dois últimos caracteres são considerados as  
 * casas decimais 
 */  
 var val2 = '';  
 var strCheck = '0123456789';  
 var len = valor.length;  
    if (len== 0){  
       return 0.00;  
    }  
   
    if (currency ==true){     
       /* Elimina os zeros à esquerda  
       * a variável  <i> passa a ser a localização do primeiro caractere após os zeros e  
       * val2 contém os caracteres (descontando os zeros à esquerda) 
       */  
         
       for(var i = 0; i < len; i++)  
          if ((valor.charAt(i) != '0') && (valor.charAt(i) != ',')) break;  
         
       for(; i < len; i++){  
          if (strCheck.indexOf(valor.charAt(i))!=-1) val2+= valor.charAt(i);  
       }  
   
       if(val2.length==0) return "0.00";  
       if (val2.length==1)return "0.0" + val2;  
       if (val2.length==2)return "0." + val2;  
         
       var parte1 = val2.substring(0,val2.length-2);  
       var parte2 = val2.substring(val2.length-2);  
       var returnvalue = parte1 + "." + parte2;  
       return returnvalue;  
         
    }  
    else{  
          /* currency é false: retornamos os valores COM os zeros à esquerda,  
          * sem considerar os últimos 2 algarismos como casas decimais  
          */  
          val3 ="";  
          for(var k=0; k < len; k++){  
             if (strCheck.indexOf(valor.charAt(k))!=-1) val3+= valor.charAt(k);  
          }           
    return val3;  
    }  
 }  
   
 function reais(obj,event){  
   
 var whichCode = (window.Event) ? event.which : event.keyCode;  
 /* 
 Executa a formatação após o backspace nos navegadores !document.all 
 */  
 if (whichCode == 8 && !documentall) {     
 /* 
 Previne a ação padrão nos navegadores 
 */  
    if (event.preventDefault){ //standart browsers  
          event.preventDefault();  
       }else{ // internet explorer  
          event.returnValue = false;  
    }  
    var valor = obj.value;  
    var x = valor.substring(0,valor.length-1);  
    obj.value= demaskvalue(x,true).formatCurrency();  
    return false;  
 }  
 /* 
 Executa o Formata Reais e faz o format currency novamente após o backspace 
 */  
 FormataReais(obj,'.',',',event);  
 } // end reais  
   
   
 function backspace(obj,event){  
 /* 
 Essa função basicamente altera o  backspace nos input com máscara reais para os navegadores IE e opera. 
 O IE não detecta o keycode 8 no evento keypress, por isso, tratamos no keydown. 
 Como o opera suporta o infame document.all, tratamos dele na mesma parte do código. 
 */  
   
 var whichCode = (window.Event) ? event.which : event.keyCode;  
 if (whichCode == 8 && documentall) {     
    var valor = obj.value;  
    var x = valor.substring(0,valor.length-1);  
    var y = demaskvalue(x,true).formatCurrency();  
   
    obj.value =""; //necessário para o opera  
    obj.value += y;  
      
    if (event.preventDefault){ //standart browsers  
          event.preventDefault();  
       }else{ // internet explorer  
          event.returnValue = false;  
    }  
    return false;  
   
    }// end if        
 }// end backspace  
   
 function FormataReais(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 == 8 ) return true; //backspace - estamos tratando disso em outra função no keydown  
 if (whichCode == 0 ) return true;  
 if (whichCode == 9 ) return true; //tecla tab  
 if (whichCode == 13) return true; //tecla enter  
 if (whichCode == 16) return true; //shift internet explorer  
 if (whichCode == 17) return true; //control no internet explorer  
 if (whichCode == 27 ) return true; //tecla esc  
 if (whichCode == 34 ) return true; //tecla end  
 if (whichCode == 35 ) return true;//tecla end  
 if (whichCode == 36 ) return true; //tecla home  
   
 /* 
 O trecho abaixo previne a ação padrão nos navegadores. Não estamos inserindo o caractere normalmente, mas via script 
 */  
   
 if (e.preventDefault){ //standart browsers  
       e.preventDefault()  
    }else{ // internet explorer  
       e.returnValue = false  
 }  
   
 var key = String.fromCharCode(whichCode);  // Valor para o código da Chave  
 if (strCheck.indexOf(key) == -1) return false;  // Chave inválida  
   
 /* 
 Concatenamos ao value o keycode de key, se esse for um número 
 */  
 fld.value += key;  
   
 var len = fld.value.length;  
 var bodeaux = demaskvalue(fld.value,true).formatCurrency();  
 fld.value=bodeaux;  
   
 /* 
 Essa parte da função tão somente move o cursor para o final no opera. Atualmente não existe como movê-lo no konqueror. 
 */  
   if (fld.createTextRange) {  
     var range = fld.createTextRange();  
     range.collapse(false);  
     range.select();  
   }  
   else if (fld.setSelectionRange) {  
     fld.focus();  
     var length = fld.value.length;  
     fld.setSelectionRange(length, length);  
   }  
   return false;  
   
 }  


function FormatDate(i, delKey, direction, separator)
{
	var intLength = (separator == "/") ? 11 : 9;

	if (i.value.length < parseInt(intLength))
	{
		if (delKey!=9)
		{
			if(delKey!=8 && delKey!=46 && delKey!=16 &&  !(delKey>36 && delKey<41))
			{
				var fieldLen = i.value.length
				if ((delKey >= 48 && delKey <= 57) || (delKey >= 96 && delKey <=105))
				{
					if (fieldLen == 2 || fieldLen == 5)
					{
						i.value = i.value + separator;
					}
				}
				else
				{
					if (direction == 'up')
					{
						if (i.value.length == 0)
						{
							i.value = ''
						}
						
						else
						{
							i.value = i.value.substring(0,i.value.length-1)
                  }
					}
				}
				i.focus()
			}
		}
	}
	else
	{
		i.value = i.value.substring(0,i.value.length-1)
	}
}









function moveSelectedOptions(from,to) {
	// Unselect matching options, if required
	if (arguments.length>3) {
		var regex = arguments[3];
		if (regex != "") {
			unSelectMatchingOptions(from,regex);
			}
		}
	// Move them over
	if (!hasOptions(from)) { return; }
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {
			if (!hasOptions(to)) { var index = 0; } else { var index=to.options.length; }
			to.options[index] = new Option( o.text, o.value, false, false);
			}
		}
	// Delete them from original
	for (var i=(from.options.length-1); i>=0; i--) {
		var o = from.options[i];
		if (o.selected) {
			from.options[i] = null;
			}
		}
	if ((arguments.length<3) || (arguments[2]==true)) {
		sortSelect(from);
		sortSelect(to);
		}
	from.selectedIndex = -1;
	to.selectedIndex = -1;
	}



function unSelectMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"unselect",false);
	}

function hasOptions(obj) {
	if (obj!=null && obj.options!=null) { return true; }
	return false;
	}


function moveAllOptions(from,to) {
	selectAllOptions(from);
	if (arguments.length==2) {
		moveSelectedOptions(from,to);
		}
	else if (arguments.length==3) {
		moveSelectedOptions(from,to,arguments[2]);
		}
	else if (arguments.length==4) {
		moveSelectedOptions(from,to,arguments[2],arguments[3]);
		}
	}


function selectAllOptions(obj) {
	if (!hasOptions(obj)) { return; }
	for (var i=0; i<obj.options.length; i++) {
		obj.options[i].selected = true;
		}
	}



function sortSelect(obj) {
	var o = new Array();
	if (!hasOptions(obj)) { return; }
	for (var i=0; i<obj.options.length; i++) {
		o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
		}
	if (o.length==0) { return; }
	o = o.sort( 
		function(a,b) { 
			if ((a.text+"") < (b.text+"")) { return -1; }
			if ((a.text+"") > (b.text+"")) { return 1; }
			return 0;
			} 
		);

	for (var i=0; i<o.length; i++) {
		obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
		}
	}



function onlynum(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;
}


function change_help(id, show)
	{
		document.getElementById(id).style.display=show;
	}

var remover_char = false;

function formatDate(i, event, direction) {
	
	var delKey = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	
	var separator = "/";
	
	var intLength = parseInt(i.maxLength);

	if (i.value.length < intLength || remover_char) {
		if (delKey!=9) {
			if(delKey!=8 && delKey!=46 && delKey!=16 && !(delKey>36 && delKey<41)) {
				var fieldLen = i.value.length;
				if ((delKey >= 48 && delKey <= 57) || (delKey >= 96 && delKey <=105)) {
					if (fieldLen == 2 || fieldLen == 5) {
						i.value = i.value + separator;
					}
				} else {
					if (remover_char) {
						if (i.value.length == 0) {
							i.value = '';
						} else {
							i.value = i.value.substring(0,i.value.length-1);
						}
					}
					if (direction == 'up') {
						remover_char = false;
					} else {
						remover_char = true;
					}
				}
				i.focus();
			}
			if(delKey==8){
				remover_char = false;
			}
		}
	}
}

function formatNum(i, event, direction) {
	
	var delKey = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	
	var intLength = parseInt(i.maxLength);

	if (i.value.length < intLength || remover_char) {
		if (delKey!=9) {
			if(delKey!=8 && delKey!=46 && delKey!=16 && !(delKey>36 && delKey<41)) {
				var fieldLen = i.value.length;
				if (!((delKey >= 48 && delKey <= 57) || (delKey >= 96 && delKey <=105))) {
					if (remover_char) {
						if (i.value.length == 0) {
							i.value = '';
						} else {
							i.value = i.value.substring(0,i.value.length-1);
						}
					}
					if (direction == 'up') {
						remover_char = false;
					} else {
						remover_char = true;
					}
				}
				i.focus();
			}
			if(delKey==8){
				remover_char = false;
			}
		}
	}
}
function validaData(str) { 

	dia = (str.value.substring(0,2)); 
    mes = (str.value.substring(3,5)); 
	ano = (str.value.substring(6,10)); 

	cons = true; 
	
	// verifica se foram digitados números
	if (isNaN(dia) || isNaN(mes) || isNaN(ano)){
		alert("Preencha a data somente com números."); 
		str.value = "";
		str.focus(); 
		return false;
	}
		
    // verifica o dia valido para cada mes 
    if ((dia < 01)||(dia < 01 || dia > 30) && 
		(mes == 04 || mes == 06 || 
		 mes == 09 || mes == 11 ) || 
		 dia > 31) { 
    	cons = false; 
	} 

	// verifica se o mes e valido 
	if (mes < 01 || mes > 12 ) { 
		cons = false; 
	} 

	// verifica se e ano bissexto 
	if (mes == 2 && ( dia < 01 || dia > 29 || 
	   ( dia > 28 && 
	   (parseInt(ano / 4) != ano / 4)))) { 
		cons = false; 
	} 
    
	if (cons == false) { 
		alert("A data inserida não é válida: " + str.value); 
		str.value = "";
		str.focus(); 
		return false;
	} 
}

// colocar no evento onKeyUp passando o objeto como parametro

function formata(val)
{
   	var pass = val.value;
	var expr = /[0123456789]/;
		
	for(i=0; i<pass.length; i++){
		// charAt -> retorna o caractere posicionado no índice especificado
		var lchar = val.value.charAt(i);
		var nchar = val.value.charAt(i+1);
	
		if(i==0){
		   // search -> retorna um valor inteiro, indicando a posição do inicio da primeira
		   // ocorrência de expReg dentro de instStr. Se nenhuma ocorrencia for encontrada o método retornara -1
		   // instStr.search(expReg);
		   if ((lchar.search(expr) != 0) || (lchar>3)){
			  val.value = "";
		   }
		   
		}else if(i==1){
			   
			   if(lchar.search(expr) != 0){
				  // substring(indice1,indice2)
				  // indice1, indice2 -> será usado para delimitar a string
				  var tst1 = val.value.substring(0,(i));
				  val.value = tst1;				
 				  continue;			
			   }
			   
			   if ((nchar != '/') && (nchar != '')){
				 	var tst1 = val.value.substring(0, (i)+1);
				
					if(nchar.search(expr) != 0) 
						var tst2 = val.value.substring(i+2, pass.length);
					else
						var tst2 = val.value.substring(i+1, pass.length);
	
					val.value = tst1 + '/' + tst2;
			   }

		 }else if(i==4){
			
				if(lchar.search(expr) != 0){
					var tst1 = val.value.substring(0, (i));
					val.value = tst1;
					continue;			
				}
		
				if	((nchar != '/') && (nchar != '')){
					var tst1 = val.value.substring(0, (i)+1);

					if(nchar.search(expr) != 0) 
						var tst2 = val.value.substring(i+2, pass.length);
					else
						var tst2 = val.value.substring(i+1, pass.length);
	
					val.value = tst1 + '/' + tst2;
				}
   		  }
		
		  if(i>=6){
			  if(lchar.search(expr) != 0) {
					var tst1 = val.value.substring(0, (i));
					val.value = tst1;			
			  }
		  }
	 }
	
     if(pass.length>10)
		val.value = val.value.substring(0, 10);
	 	return true;
}

function checkIt(evt) {
    evt = (evt) ? evt : window.event
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        status = "Digite apenas números."
        return false
    }
    status = ""
    return true
}

function comprova_extensao(formulario, arquivo) {
   extensoes_permitidas = new Array(".doc", ".docx", ".pdf");
   meuerro = "";
   if (!arquivo) {
      //Se não tenho arquivo, é porque não se selecionou um arquivo no formulário.
       meuerro = "Não foi selecionado nenhum arquivo";
   }else{
      //recupero a extensão deste nome de arquivo
      extensao = (arquivo.substring(arquivo.lastIndexOf("."))).toLowerCase();
      //alert (extensao);
      //comprovo se a extensão está entre as permitidas
      permitida = false;
      for (var i = 0; i < extensoes_permitidas.length; i++) {
         if (extensoes_permitidas[i] == extensao) {
         permitida = true;
         break;
         }
      }
      if (!permitida) {
         meuerro = "Só são permitidos arquivos com extensões: " + extensoes_permitidas.join();
       }else{
          //submeto!
         formulario.submit();
         return 1;
       }
   }
   //se estou aqui é porque não se pode submeter
   alert (meuerro);
   return 0;
} 


