var now  = new Date();
var data = now.getDate()+"/"+(now.getMonth() + 1)+"/"+now.getYear();
var h    = now.getHours();
var m    = now.getMinutes();
var hora = h + ":" + m

//**********************************************
// Biblioteca de Rotinas e Funções Javascript 
// Data: 01/11/2007 18h 47m
// Por: Cristiano dos Santos Ferreira
// Empresa: Easy System Informática
// Última atualização: 01/11/2007 18h 48m
//**********************************************

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function abrePopUp(url, name)
{     
	var str = "left=100,screenX=0,top=0,screenY=0,status=1,scrollbars=1";

     if (window.screen) {
       var ah = screen.availHeight - 350;
       var aw = screen.availWidth - 450;
       str += ",height=" + ah;
       str += ",innerHeight=" + ah;
       str += ",width=" + aw;
       str += ",innerWidth=" + aw;
     } else {
       str += ",resizable"; // redimensiona a janela para o usuário
     }

	var janela = window.open(url, name, str);

	if (!janela)
	{
		alert("Por favor, desative seu anti-popup para usar o sistema.");
	}
}

function abre(url, name)
{     
	var str = "left=0,screenX=0,top=0,screenY=0,status=1,scrollbars=1";

     if (window.screen) {
       var ah = screen.availHeight - 50;
       var aw = screen.availWidth - 10;
       str += ",height=" + ah;
       str += ",innerHeight=" + ah;
       str += ",width=" + aw;
       str += ",innerWidth=" + aw;
     } else {
       str += ",resizable"; // redimensiona a janela para o usuário
     }

	var janela = window.open(url, name, str);

	if (!janela)
	{
		alert("Por favor, desative seu anti-popup para usar o sistema.");
	}
}

// Load de carregamento
// Parâmetros: div = Nome da DIV / state = Estado de carregamento

// Redimenciona a janela depois de aberto

function abre2(url, name)
{     
	var str = "status=1,scrollbars=1";

     if (window.screen) {
       var ah = 600;//screen.availHeight - 50;
       var aw = 650;//screen.availWidth - 10;
       str += ",height=" + ah;
       str += ",innerHeight=" + ah;
       str += ",width=" + aw;
       str += ",innerWidth=" + aw;
	   str += ",top=" + (screen.height-ah)/2;
	   str += ",left=" + (screen.width-aw)/2;
	   str += ",screenY=" + (screen.height-ah)/2;
	   str += ",screenX=" + (screen.width-aw)/2;
     } else {
       str += ",resizable"; // redimensiona a janela para o usuário
     }

	var janela = window.open(url, name, str);

	if (!janela)
	{
		alert("Por favor, desative seu anti-popup para usar o sistema.");
	}
}

function abrir(wd, hg){
var l;
var a;

if ((wd == 0) && (hg == 0)){
	wd = screen.availWidth;
	hg = screen.availHeight ;
	l = 1;
	a =  1; 
}else{
	l = (screen.width/2) - wd/2;
	a =  (screen.height/2) - hg/2; 
}

parent.resizeTo( Math.ceil( wd ) , Math.ceil( hg ) );
parent.moveTo  ( Math.ceil( l ), Math.ceil( a ));
parent.resizeTo( Math.ceil( wd ) , Math.ceil( hg ) );
}

function display_control(div,state){
	if(state=='show')
	{
		document.getElementById(div).style.display = "block";
	} else {
		document.getElementById(div).style.display = "none";
	}
}

// Reload na página ao carregar 

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}

// Verigica o click para salvar senha
var checkobj

var checkobj

function agreesubmit(el){
checkobj=el
if (document.all||document.getElementById){
for (i=0;i<checkobj.form.length;i++){  //hunt down submit button
var tempobj=checkobj.form.elements[i]
if(tempobj.type.toLowerCase()=="submit")
tempobj.disabled=!checkobj.checked
}
}
}

function defaultagree(el){
if (window.checkobj&&checkobj.checked)
alert("CUIDADO: Ao selecionar este campo, você estará salvando seus dados de acesso neste computador, dando acesso a qualquer um que esteja utilizando o mesmo!")
return false
}

// HighLight Mouse

function mouseover(src,clrOver)
{
	if (!src.contains(event.fromElement))
	{
		src.style.cursor='hand';
		src.bgColor=clrOver;
	}
}

function mouseout(src,clrIn)
{
	if (!src.contains(event.toElement))
	{
		src.style.cursor='default';
		src.bgColor=clrIn;
	}
}

function mouseclick(src)
{
	if(event.srcElement.tagName=='TD')
	{
		src.children.tags('A')[0].click();
	}
}

// Abre nova janela com propriedades definidas

function abreNew(theURL,winName,features) 
{
  window.open(theURL,winName,features);
}

function enableCh(d,i){

	if (document.getElementById(d).checked == true) {
			document.getElementById(i).value="";
			document.getElementById(i).disabled=false;	
			document.getElementById(i).style.backgroundColor="#ffffff";
			document.getElementById(i).focus();
	} else {
			document.getElementById(i).value="";
			document.getElementById(i).disabled=true;
			document.getElementById(i).style.backgroundColor="#f0f0f0";
	}
}

function enableCh_envia(d,i,v){
	if (document.getElementById(d).checked == true) {
			var teste = v;
			document.getElementById(i).value=v;			
			document.getElementById(i).disabled=false;	
			document.getElementById(i).style.backgroundColor="#ffffff";
			document.getElementById(i).focus();
	} else {
			document.getElementById(i).value="";
			document.getElementById(i).disabled=true;
			document.getElementById(i).style.backgroundColor="#f0f0f0";
	}
}

/*
Carrega ComoboBox
*/

var xmlHttp

function MandaID(str,pag,campo,strProfissao,cod_profissao)
{ 
	if (str != "0") {
		xmlHttp=GetXmlHttpObject()
		if (xmlHttp==null)
		{
			alert ("Este browser nao suporta HTTP Request")
			return
		}
		
		var url="ajax/" + pag
		url=url+"?cod_cliente="+str+"&cod_contrato="+strProfissao+"&cod_profissao="+cod_profissao
		url=url+"&sid="+Math.random()
		document.getElementById("guarda").value=campo;
		xmlHttp.onreadystatechange=stateChanged 
		xmlHttp.open("GET",url,true)
		xmlHttp.send(null)
	} else {
		document.getElementbyId("atividade").value = "";
	}
}

/* AJAX */

function ajaxGet(url,elemento_retorno,exibe_carregando){
var ajax1 = pegaAjax();
    if(ajax1){
        url = antiCacheRand(url)
        ajax1.onreadystatechange = ajaxOnReady
        ajax1.open("GET", url ,true);
        ajax1.setRequestHeader("Cache-Control", "no-cache");        
        ajax1.setRequestHeader("Pragma", "no-cache");        
        ajax1.setRequestHeader("Content-Type", "text/html; charset=ISO-8859-1");		
        if(exibe_carregando){ put("Carregando ...")    }        
        ajax1.send(null)        
        return true;    
        }else{        
        return false;    
        }    
        
        function ajaxOnReady(){        
        if (ajax1.readyState==4){            
           if(ajax1.status == 200){                
                var texto=ajax1.responseText;  
                texto=texto.replace(/\+/g," ");
                texto = unescape(texto);
                              
                if(texto.indexOf(" ")<0) texto=texto.replace(/\+/g," ");                
                put(texto);                
                extraiScript(texto);            
                }else{                
                if(exibe_carregando){put("Falha no carregamento. " + httpStatus(ajax1.status));}            
                }            
                
                ajax1 = null        
           }else if(exibe_carregando){//para mudar o status de cada carregando                
                put("Carregando ..." )        
           }    
        }    
        
        function put(valor){     
                 if((typeof(elemento_retorno)).toLowerCase()=="string"){ //se for o nome da string            
                       if(valor!="Falha no carregamento"){                    
                           eval(elemento_retorno + '= unescape("' + escape(valor) + '")')            
                       }        
                 }else if(elemento_retorno.tagName.toLowerCase()=="input"){            
                       valor = escape(valor).replace(/\%0D\%0A/g,"")            
                       elemento_retorno.value = unescape(valor);        
                 }else if(elemento_retorno.tagName.toLowerCase()=="select"){                    
                       select_innerHTML(elemento_retorno,valor)        
                 }else if(elemento_retorno.tagName){            
				 
                       valor = escape(valor).replace(/\%0D\%0A/g,"")            
                       elemento_retorno.innerHTML = unescape(valor);           
                       //alert(elemento_retorno.innerHTML)        
                 }        
        }    
        
        function pegaAjax(){ //instancia um novo xmlhttprequest
                 if(typeof(XMLHttpRequest)!='undefined'){return new XMLHttpRequest();}        
                 var axO=['Microsoft.XMLHTTP','Msxml2.XMLHTTP','Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.4.0','Msxml2.XMLHTTP.3.0'];        
                 for(var i=0;i<axO.length;i++){ try{ return new ActiveXObject(axO[i]);}catch(e){} }        
                 return null;    
        }    
                 
        function httpStatus(stat){ //retorna o texto do erro http        
                 switch(stat){            
                 case 0: return "Erro desconhecido";            
                 case 400: return "400: Solicitaçao incompreensível"; break;            
                 case 403: case 404: return "404: Nao foi encontrada a URL solicitada"; break;            
                 case 405: return "405: O servidor nao suporta o método solicitado"; break;            
                 case 500: return "500: Erro desconhecido de natureza do servidor"; break;            
                 case 503: return "503: Capacidade máxima do servidor alcançada"; break;            
                 default: return "Erro " + stat + ". Erro desconhecido"; break;        
                 }    
       }    
                 
       function antiCacheRand(aurl){        
                 var dt = new Date();        
                 if(aurl.indexOf("?")>=0){// já tem parametros            
                 return aurl + "&" + encodeURI(Math.random() + "_" + dt.getTime());        
                 }else{ return aurl + "?" + encodeURI(Math.random() + "_" + dt.getTime());}    
       }
}



function select_innerHTML(objeto,innerHTML){
	objeto.innerHTML = ""    
    var selTemp = document.createElement("micoxselect")    
    var opt;    
    selTemp.id="micoxselect1"    
    document.body.appendChild(selTemp)    
    selTemp = document.getElementById("micoxselect1")    
    selTemp.style.display="none"    
    if(innerHTML.toLowerCase().indexOf("<option")<0){//se nao é option eu converto        
         innerHTML = "<option>" + innerHTML + "</option>"    
    }    
         
         innerHTML = innerHTML.replace(/<option/g,"<span").replace(/<\/option/g,"</span")    
         selTemp.innerHTML = innerHTML    
         for(var i=0;i<selTemp.childNodes.length;i++){        
         if(selTemp.childNodes[i].tagName){            
         opt = document.createElement("OPTION")            
         for(var j=0;j<selTemp.childNodes[i].attributes.length;j++){                
         opt.setAttributeNode(selTemp.childNodes[i].attributes[j].cloneNode(true))            
         }            
         opt.value = selTemp.childNodes[i].getAttribute("value")            
         opt.text = selTemp.childNodes[i].innerHTML            
         if(document.all){ //IEca                
         objeto.add(opt)            
         }else{                
         objeto.appendChild(opt)            
         }                            
	 }        
 }    
         document.body.removeChild(selTemp)    
         selTemp = null}function extraiScript(texto){//Maravilhosa funçao feita pelo SkyWalker.TO do imasters/forum//http://forum.imasters.com.br/index.php?showtopic=165277&    
         // inicializa o inicio ><    
         var ini = 0;    
         // loop enquanto achar um script    
         while (ini!=-1){        
         // procura uma tag de script        
         ini = texto.indexOf('<script', ini); 
         // se encontrar        
         if (ini >=0){            
         // define o inicio para depois do fechamento dessa tag            
         ini = texto.indexOf('>', ini) + 1;            
         // procura o final do script            
         var fim = texto.indexOf('</script>', ini);            
         // extrai apenas o script            
         codigo = texto.substring(ini,fim);            
         // executa o script            
         //eval(codigo);            
         
         novo = document.createElement("script")            
         novo.text = codigo;            
         document.body.appendChild(novo);        
         }    
	 }
 }

/* Masscara */
function RetornaTecla(e)
{
	if (document.all)
	{
		var tecla = event.keyCode;
	}
	else if(document.layers)
	{
		var tecla = e.which;
	}
	
	return tecla;
}

function SomenteNumeros(e)
{
	tecla = RetornaTecla(e);
	
	// tratamento das teclas
	if ( (tecla < 48 || tecla > 57) && (tecla < 96 || tecla > 105) && (tecla < 37 || tecla > 40) && (tecla != 17) && (tecla != 18) && (tecla != 8) && (tecla != 9) && (tecla != 32) && (tecla != 46) && (tecla != 35) && (tecla != 36) && (tecla != 13))
	{
		return false;
	}
	else
	{
		return true;
	}
}


function MascaraCEP (Form1ato, keypress, objeto)
{
campo = eval (objeto);
if (Form1ato=='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;
	}
}

/*function MascaraPIS (objeto)
{

	campo = eval(objeto);
	caracteres = '0123456789`abcdefghi';
	separacoes = 3;
	separacao1 = '.';
	separacao2 = '-';
	conjuntos = 4;
	conjunto1 = 3;
	conjunto2 = 4;
	conjunto3 = 5;
	conjunto4 = 1;

	//if ((caracteres.search(String.fromCharCode(window.event.keyCode))!=-1) && campo.value.length < (conjunto1 + conjunto2 + conjunto3 + conjunto4 + 1))
	if (campo.value.length < (conjunto1 + conjunto2 + conjunto3 + conjunto4 + 1))
		{
			if (campo.value.length == conjunto1) {
			   campo.value = campo.value + separacao1;
			}
			
			if (campo.value.length == conjunto1 + conjunto2) {
			   campo.value = campo.value + separacao1;
			}
			
			if (campo.value.length == conjunto1 + conjunto2 + conjunto3) {
			   campo.value = campo.value + separacao2;
			}
		}
}*/
function MascaraPIS(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)){
			  val.value = "";
		   }

		}else if(i<2){
		   if (lchar.search(expr) != 0){
			  val.value = val.value.substring(0, i);
		   }

		}else if(i==2){
			   
			   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>3 && i<6){
				if (lchar.search(expr) != 0){
				  val.value = val.value.substring(0, i);
			   }			 
		 }else if(i==6){
			
				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;
				}
   		  }else if(i>7 && i<11){
				if (lchar.search(expr) != 0){
				  val.value = val.value.substring(0, i);
			   }
		  }else if(i==11){
			   
			   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>12){
			  if(lchar.search(expr) != 0) {
					var tst1 = val.value.substring(0, (i));
					val.value = tst1;			
			  }
		  }
	 }
	
     if(pass.length>14)
		val.value = val.value.substring(0, 14);
	 	return true;
}

/*function MascaraCPF (objeto)
{
  campo = eval (objeto);
  caracteres = '01234567890';
  separacoes = 3;
  separacao1 = '.';
  separacao2 = '-';
  conjuntos = 4;
  conjunto1 = 3;
  conjunto2 = 7;
  conjunto3 = 11;
  conjunto4 = 14;
  if ((caracteres.search(String.fromCharCode (window.event.keyCode))!=-1) && campo.value.length < (conjunto4))
  {
	  if (campo.value.length == conjunto1) 
		  campo.value = campo.value + separacao1;
	  else if (campo.value.length == conjunto2) 
		  campo.value = campo.value + separacao1;
	  else if (campo.value.length == conjunto3) 
		  campo.value = campo.value + separacao2;
  }
}*/

function MascaraCPF(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)){
			  val.value = "";
		   }

		}else if(i<2){
		   if (lchar.search(expr) != 0){
			  val.value = val.value.substring(0,(i));
		   }

		}else if(i==2){
			   
			   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>3 && i<6){
				if (lchar.search(expr) != 0){
				  val.value = val.value.substring(0,(i));
			   }			 
		 }else if(i==6){
			
				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;
				}
   		  }else if(i>7 && i<10){
				if (lchar.search(expr) != 0){
				  val.value = val.value.substring(0, i);
			   }
		  }else if(i==10){
			   
			   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>11){
			  if(lchar.search(expr) != 0) {
					var tst1 = val.value.substring(0,(i));
					val.value = tst1;			
			  }
		  }
	 }
	
     if(pass.length>14)
		val.value = val.value.substring(0, 14);
	 	return true;
}

function MascaraCPF_objeto(objeto)
{
cpf_conjunto1=objeto.substring(0, 3);
cpf_conjunto2=objeto.substring(3, 6);
cpf_conjunto3=objeto.substring(6, 9);
cpf_conjunto4=objeto.substring(9, 11);
 return cpf_conjunto1+'.'+cpf_conjunto2+'.'+cpf_conjunto3+'-'+cpf_conjunto4 
}

function pega_valor(vPG,vID01, vID02, vDIV) {
	ajaxGet(vPG + '?cod_cliente=' + vID01 + '&cod_contrato=' + vID02, document.getElementById(vDIV),false);
}   

function pega_prof(vPG,vID01, vID02, vID03, vDIV) {
	ajaxGet(vPG + '?cod_cliente=' + vID01 + '&cod_contrato=' + vID02 + '&cod_profissao=' + vID03, document.getElementById(vDIV),false);
}   

/*function enableInput(d){
	document.getElementById('cod_mat').value 		  = "Matrícula"
	document.getElementById('bs_cpf').value 		  = "Busca por CPF"	
	document.getElementById('descricao').value 		  = "Busca por nome"

	document.getElementById('cod_mat').className	  = "bx_off"
	document.getElementById('bs_cpf').className	  	  = "bx_off"	
	document.getElementById('descricao').className	  = "bx_off"

	
	if(d=='O') {
		document.getElementById('descricao').value 		 		  = ""
		document.getElementById('descricao_titulo').style.display = "block"
		document.getElementById('descricao_titulo').innerText	  = "Descriçao"
		document.getElementById('descricao').style.display 		  = "block"
		document.getElementById('cod_mat').style.display 		  = "none"
		document.getElementById('bs_cpf').style.display 		  = "none"
		document.getElementById('descricao').alt 		  		  = "Descreva o motivo"
		document.getElementById('descricao').value 		  		  = "Descreva o motivo"
		document.getElementById('img1').style.display 			  = "none"
		document.getElementById('img2').style.display 			  = "none"
	} else if(d=='S') {
		document.getElementById('cod_mat').style.display 		  = "block"
		document.getElementById('descricao_titulo').style.display = "block"
		document.getElementById('descricao_titulo').innerText	  = "Selecione o cooperado a ser substituido:"
		document.getElementById('descricao').alt 		  		  = "Busca por nome"
		document.getElementById('descricao').style.display 		  = "block"
		document.getElementById('bs_cpf').style.display 		  = "block"
		document.getElementById('img1').style.display 			  = "block"
		document.getElementById('img2').style.display 			  = "block"
	} else {
		document.getElementById('descricao_titulo').style.display = "none"
		document.getElementById('descricao').style.display 		  = "none"
		document.getElementById('cod_mat').style.display 		  = "none"
		document.getElementById('bs_cpf').style.display 		  = "none"
		document.getElementById('img1').style.display 			  = "none"
		document.getElementById('img2').style.display 			  = "none"
	}
}*/

function enableInput(d){
	document.getElementById('opcoes_adicionais').innerHTML="";
	if(d=='O') {
		document.getElementById('opcoes_adicionais').style.display= "none"
	} else if(d=='S') {
		document.getElementById('opcoes_adicionais').style.display= "block"
	} else {
		document.getElementById('opcoes_adicionais').style.display= "none"
	}
}

function retorna_lista(matricula,cpf,nome,div_retorno,url,param,div_carrega){
	var elemento1=document.getElementById(div_retorno)
	var elemento2=document.getElementById(div_carrega)
	
	if (matricula!="" && matricula.length>=1) {
		
		elemento1.style.display="block";
		
		if (elemento2!=""){
			elemento2.style.backgroundImage="url(/emw/system/images/geral/aguarde.gif)";
		}
		ajaxGet(url+'?matricula='+matricula+'&param='+param,elemento1,true);
	
	} else if (cpf!="" && cpf.length>=4) {
		
		elemento1.style.display="block";
		
		if (elemento2!=""){
			elemento2.style.backgroundImage="url(/emw/system/images/geral/aguarde.gif)";
		}
		ajaxGet(url+'?cpf='+cpf+'&param='+param,elemento1,true);
		
	} else if (nome!="" && nome.length>=4) {
		
		elemento1.style.display="block";
		
		if (elemento2!=""){
		elemento2.style.backgroundImage="url(/emw/system/images/geral/aguarde.gif)";
		}
		ajaxGet(url+'?nome='+nome+'&param='+param,elemento1,true);	
	} else {
		elemento2.style.backgroundImage="";
		elemento1.style.display="none";
	}	
}

function busca_coop(matricula,nome,div_retorno,url,div_carrega){
	var elemento1=document.getElementById(div_retorno)
	var elemento2=document.getElementById(div_carrega)
	
	//alert(matricula+","+nome+","+div_retorno+","+url+","+div_carrega);
	
	if (matricula!="" && matricula.length>=1) {
		
		elemento1.style.display="block";
		elemento2.value = ""
		
		if (elemento2!=""){
			elemento2.style.backgroundImage="url(/emw/system/images/geral/aguarde.gif)";
		}
		
		ajaxGet(url+'?matricula='+matricula,elemento1,true);
	
	
	}	
}

function mouseClickBusca2(valorMatricula,valorNome,param){
	valorNome	= valorNome.replace(/\+/g," ");
	valorNome 	= unescape(valorNome);
	
	document.getElementById("cod_mat"+param).value					 = valorMatricula;
	document.getElementById("descricao"+param).value				 = valorNome;
	
	document.getElementById("cod_mat"+param).className				 = "bx";
	document.getElementById("descricao"+param).className			 = "bx";
	

	document.getElementById("retorno_mat"+param).style.display		 = "none";
	document.getElementById("descricao"+param).style.backgroundImage ="";
}

function mouseClickBuscaGes(valorNome,id){
	valorNome	= valorNome.replace(/\+/g," ");
	valorNome 	= unescape(valorNome);
	
	//alert(valorNome);
	//alert(param);
	
	document.getElementById("descricao").value				 = valorNome;
	
	document.getElementById("descricao").className			 = "bx";
	
	document.getElementById("descricao").style.backgroundImage ="";
	
	document.getElementById("cod_mat").value				 = id;
	
	document.getElementById("retorno_mat").style.display = "none";
}

function mouseClickBusca(valorMatricula,valorCpf,valorNome,param){
	valorNome	= valorNome.replace(/\+/g," ");
	valorNome 	= unescape(valorNome);
	
	document.getElementById("cod_mat"+param).value					 = valorMatricula;
	document.getElementById("bs_cpf"+param).value					 = MascaraCPF_objeto(valorCpf);
	document.getElementById("descricao"+param).value				 = valorNome;
	
	document.getElementById("cod_mat"+param).className				 = "bx";
	document.getElementById("bs_cpf"+param).className				 = "bx";
	document.getElementById("descricao"+param).className			 = "bx";
	

	document.getElementById("retorno_mat"+param).style.display		 = "none";
	document.getElementById("descricao"+param).style.backgroundImage ="";
}

function retorna_lista_candidatos(cod_cand,nome_cand,div_retorno,url,param,div_carrega){
	var elemento1=document.getElementById(div_retorno)
	var elemento2=document.getElementById(div_carrega)
	
	if (cod_cand!="" && cod_cand.length>=1) {
		
		elemento1.style.display="block";
		
		if (elemento2!=""){
			elemento2.style.backgroundImage="url(/emw/system/images/geral/aguarde.gif)";
		}
		ajaxGet(url+'?cod_cand='+cod_cand,elemento1,true);
	
	} else if (nome_cand!="" && nome_cand.length>=4) {
		
		elemento1.style.display="block";
		
		if (elemento2!=""){
		elemento2.style.backgroundImage="url(/emw/system/images/geral/aguarde.gif)";
		}
		ajaxGet(url+'?nome_cand='+nome_cand,elemento1,true);	
	} else {
		elemento2.style.backgroundImage="";
		elemento1.style.display="none";
	}	
}

function mouseClickBuscaCand(valorCodigo,valorNome){
	valorNome	= valorNome.replace(/\+/g," ");
	valorNome 	= unescape(valorNome);
	
	document.getElementById("cod_cand").value					= valorCodigo;
	document.getElementById("nome_cand").value				 	= valorNome;
	
	document.getElementById("cod_cand").className				= "bx";
	document.getElementById("nome_cand").className			 	= "bx";
	

	document.getElementById("retorno_mat").style.display		= "none";
	document.getElementById("nome_cand").style.backgroundImage 	="";
}

// 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 MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, 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;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux. substr(len - 2, len);
    }
    return false;
}


function mascara_hora(hora,nCampo){ 
  var myhora = ''; 
  var campo
  myhora = myhora + hora; 
  if (myhora.length == 2){ 
	  myhora = myhora + ':'; 
	  nCampo.value = myhora; 
  } 
  if (myhora.length == 5){ 
	  verifica_hora(nCampo); 
  } 
} 

function verifica_hora(nCampo){ 
  hrs = (nCampo.value.substring(0,2)); 
  mnt = (nCampo.value.substring(3,5)); 
				 
  situacao = ""; 
  // verifica hora 
  if ((hrs < 00 ) || (hrs > 23) || ( mnt < 00) ||( mnt > 59)){ 
	  situacao = "falsa"; 
  } 
   
   /*
  if (nCampo.value == "") { 
	  situacao = "falsa"; 
  } 
	*/
  if (situacao == "falsa") { 
	  alert("Hora inválida!"); 
	  nCampo.focus(); 
  } 
}

function mascara_hora_total(hora,nCampo){ 
  var myhora = ''; 
  var campo
  myhora = myhora + hora; 
  if (myhora.length == 3){ 
	  myhora = myhora + ':'; 
	  nCampo.value = myhora; 
  } 
  if (myhora.length == 6){ 
	  verifica_hora(nCampo); 
  } 
} 

function verifica_hora_total(nCampo){ 
  hrs = (nCampo.value.substring(0,3)); 
  mnt = (nCampo.value.substring(4,6)); 
  
  situacao = ""; 
  // verifica hora 
  if ((hrs < 00 ) || (hrs > 300) || ( mnt < 00) ||( mnt > 59)){ 
	  situacao = "falsa"; 
  } 
   
   /*
  if (nCampo.value == "") { 
	  situacao = "falsa"; 
  } 
	*/
  if (situacao == "falsa") { 
	  alert("Total de Horas inválido!"); 
	  nCampo.focus(); 
  } 
}

function mascara_mes(mes,nCampo){ 
  var mymes = ''; 
  var campo
  mymes = mymes + mes; 
  if (mymes.length == 2){ 
	  mymes = mymes + '/'; 
	  nCampo.value = mymes; 
  } 
  if (mymes.length == 7){ 
	  verifica_mes(nCampo); 
  } 
} 

function verifica_mes(nCampo){ 
  mes = (nCampo.value.substring(0,2)); 
  ano = (nCampo.value.substring(3,7)); 
				 
  situacao = ""; 
  // verifica mes 
  if (nCampo.value != ""){ 
	  if ((mes < 01 ) || (mes > 12)){ 
		  situacao = "falsa"; 
	  } 
	   
	  if (situacao == "falsa") { 
		  alert("Mês inválido!"); 
		  nCampo.focus(); 
	  } 
  }
}

function replicaCampos(quantidade,replica,onde_replica){
	document.getElementById("descricao_titulo").style.display = "none";
			
	if (quantidade>0){
		if (replica=='S'){
			ajaxGet("/emw/system/vagas/ajax/quantidade_substituicoes.asp?quantidade="+quantidade,onde_replica,true)
		}
		onde_replica.style.display="block";
		repl();		
	}else if (quantidade==0){
		onde_replica.style.display="none";
		repl();	
		
		if (replica=="S"){
			document.getElementById("motivo").value = "0";
			alert("Preencha corretamente o campo Quantidade.");
		}
	}else{
		onde_replica.style.display = "none";
		repl();
	}
	
	function repl(){
		if (replica=='O'){
			document.getElementById("descricao_titulo").innerText     = "Descreva o motivo";
			document.getElementById("descricao_titulo").style.display = "block";
			
			ajaxGet("/emw/system/vagas/ajax/quantidade_substituicoes.asp?quantidade=outros",onde_replica,true)			
			onde_replica.style.display="block";			
		}				
	}
	
}


/*** 
* Descrição.: formata um campo do formulário de 
* acordo com a máscara informada... 
* Parâmetros: - objForm (o Objeto Form) 
* - strField (string contendo o nome 
* do textbox) 
* - sMask (mascara que define o 
* formato que o dado será apresentado, 
* usando o algarismo "9" para 
* definir números e o símbolo "!" para 
* qualquer caracter... 
* - evtKeyPress (evento) 
* Uso.......: <input type="textbox" 
* name="xxx"..... 
* onkeypress="return txtBoxFormat(document.rcfDownload, 'str_cep', '99999-999', event);"> 
* Observação: As máscaras podem ser representadas como os exemplos abaixo: 
* CEP -> 99.999-999 
* CPF -> 999.999.999-99 
* CNPJ -> 99.999.999/9999-99 
* Data -> 99/99/9999 
* Tel Resid -> (99) 999-9999 
* Tel Cel -> (99) 9999-9999 
* Processo -> 99.999999999/999-99 
* C/C -> 999999-! 
* Hora -> 99:99:99 
* E por aí vai... 
***/

function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {
var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

if(document.all) { // Internet Explorer
nTecla = evtKeyPress.keyCode; }
else if(document.layers) { // Nestcape
nTecla = evtKeyPress.which;
}

sValue = objForm[strField].value;

// Limpa todos os caracteres de formatação que
// já estiverem no campo.
sValue = sValue.toString().replace( "-", "" );
sValue = sValue.toString().replace( "-", "" );
sValue = sValue.toString().replace( ".", "" );
sValue = sValue.toString().replace( ".", "" );
sValue = sValue.toString().replace( "/", "" );
sValue = sValue.toString().replace( "/", "" );
sValue = sValue.toString().replace( "(", "" );
sValue = sValue.toString().replace( "(", "" );
sValue = sValue.toString().replace( ")", "" );
sValue = sValue.toString().replace( ")", "" );
sValue = sValue.toString().replace( " ", "" );
sValue = sValue.toString().replace( " ", "" );
sValue = sValue.toString().replace( ":", "" );
sValue = sValue.toString().replace( ":", "" );
fldLen = sValue.length;
mskLen = sMask.length;

i = 0;
nCount = 0;
sCod = "";
mskLen = fldLen;

while (i <= mskLen) {
bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " ") || (sMask.charAt(i) == ":"))

if (bolMask) {
sCod += sMask.charAt(i);
mskLen++; }
else {
sCod += sValue.charAt(nCount);
nCount++;
}

i++;
}

objForm[strField].value = sCod;

if (nTecla != 8) { // backspace
if (sMask.charAt(i-1) == "9") { // apenas números...
return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
else { // qualquer caracter...
return true;
} }
else {
return true;
}
}
//Fim da Função Máscaras Gerais


startList = function() {
if (document.all&&document.getElementById) {
navRoot = document.getElementById("menu");
for (i=0; i<navRoot.childNodes.length; i++) {
node = navRoot.childNodes[i];
if (node.nodeName=="LI") {
node.onmouseover=function() {
this.className+=" over";
  }
  node.onmouseout=function() {
  this.className=this.className.replace(" over", "");
   }
   }
  }
 }
}

// Auto Tabulaçao

var isNN = (navigator.appName.indexOf("Netscape")!=-1);

function autoTab(input,len, e) {
    var keyCode = (isNN) ? e.which : e.keyCode; 
    var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
    if(input.value.length >= len && !containsElement(filter,keyCode)) {
        input.value = input.value.slice(0, len);
        input.form[(getIndex(input)+1) % input.form.length].focus();
}

function containsElement(arr, ele) {
    var found = false, index = 0;
    while(!found && index < arr.length)
        if(arr[index] == ele)
            found = true;
        else
            index++;
        return found;
    }

function getIndex(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;
    }
return true;
}

/* Formataçao de Campos */
function formataCampo(campo, Mascara, evento) { 
    var boleanoMascara; 
    
    var Digitato = evento.keyCode;
    exp = /\-|\.|\/|\(|\)| /g
    campoSoNumeros = campo.value.toString().replace( exp, "" ); 
   
    var posicaoCampo = 0;     
    var NovoValorCampo="";
    var TamanhoMascara = campoSoNumeros.length;; 
    
    if (Digitato != 8) { // backspace 
        for(i=0; i<= TamanhoMascara; i++) { 
            boleanoMascara  = ((Mascara.charAt(i) == "-") || (Mascara.charAt(i) == ".")
                                || (Mascara.charAt(i) == "/")) 
            boleanoMascara  = boleanoMascara || ((Mascara.charAt(i) == "(") 
                                || (Mascara.charAt(i) == ")") || (Mascara.charAt(i) == " ")) 
            if (boleanoMascara) { 
                NovoValorCampo += Mascara.charAt(i); 
                  TamanhoMascara++;
            }else { 
                NovoValorCampo += campoSoNumeros.charAt(posicaoCampo); 
                posicaoCampo++; 
              }            
          }     
        campo.value = NovoValorCampo;
          return true; 
    }else { 
        return true; 
    }
}


// Adiciona Máscara de numeros inteiros 
function mascaraInteiro(){
    if (event.keyCode < 48 || event.keyCode > 57){
        event.returnValue = false;
        return false;
    }
    return true;
}

//adiciona mascara ao telefone
function MascaraTelefone(tel){    
    if(mascaraInteiro(tel)==false){
        event.returnValue = false;
    }    
    return formataCampo(tel, '0000-0000', event);
}

function limpa_string(S){
	// Deixa so' os digitos no numero
	var Digitos = "0123456789";
	var temp = "";
	var digito = "";

	for (var i=0; i<S.length; i++)	{
		digito = S.charAt(i);
		if (Digitos.indexOf(digito)>=0)	{
			temp=temp+digito	}
	} //for

	return temp
}

// Valida PIS

var ftap="3298765432";
var total=0;
var i;
var resto=0;
var numPIS=0;
var strResto="";

function ChecaPIS(pis)
{

total=0;
resto=0;
numPIS=0;
strResto="";

	numPIS=pis;
			
	if (numPIS=="" || numPIS==null)
	{
		return false;
	}
	
	for(i=0;i<=9;i++)
	{
		resultado = (numPIS.slice(i,i+1))*(ftap.slice(i,i+1));
		total=total+resultado;
	}
	
	resto = (total % 11)
	
	if (resto != 0)
	{
		resto=11-resto;
	}
	
	if (resto==10 || resto==11)
	{
		strResto=resto+"";
		resto = strResto.slice(1,2);
	}
	
	if (resto!=(numPIS.slice(10,11)))
	{
		return false;
	}
	
	return true;
}

function ValidaPis(nCampo)
{
	pis=nCampo.value;
	
	if (!ChecaPIS(pis))
	{
		alert("PIS INVALIDO!");
		nCampo.focus();
		return false;
	}
	return true;
}

// Valida CPF

function valida_CPF(s)	{
	var i;
	s = limpa_string(s);
	var c = s.substr(0,9);
	var dv = s.substr(9,2);
	var d1 = 0;
	for (i = 0; i < 9; i++)
	{
		d1 += c.charAt(i)*(10-i);
	}
        if (d1 == 0) return false;
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1)
	{
		return false;
	}

	d1 *= 2;
	for (i = 0; i < 9; i++)
	{
		d1 += c.charAt(i)*(11-i);
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1)
	{
		return false;
	}
        return true;
}

//Limpa String

function limpa_string(S){
	// Deixa so' os digitos no numero
	var Digitos = "0123456789";
	var temp = "";
	var digito = "";

	for (var i=0; i<S.length; i++)	{
		digito = S.charAt(i);
		if (Digitos.indexOf(digito)>=0)	{
			temp=temp+digito	}
	} //for

	return temp
}

// Passa somente o primeiro nome

function passa_primeiro_nome (nValor, nCampo) {
	var tudo = nValor;
	var partes = tudo.split(' ');
	document.getElementById(nCampo).value = partes[0];
}

function limpa_caminho (nValor, nCampo) {
	var tudo = nValor;
	var partes = tudo.split('/');
	var tt_partes = partes[partes.length - 1];
	
	document.getElementById(nCampo).value = tt_partes;
}

function mostra(pri) {
	var d = document.getElementById(pri);
	if (d.style.display=='') {
	 d.style.display='none';
	} else {
	 d.style.display=''
	}
}
	
function mostradiv(npag, nElemento) {
	ajaxGet(npag, document.getElementById(nElemento), true);
	document.getElementById(nElemento).style.visibility = 'visible'; 
	document.getElementById(nElemento).style.display = 'block';	
	
}

function mostradiv2(npag, cod_cliente, nElemento) {
	//alert(npag + "?cod_cliente=" + cod_cliente + " - " + nElemento);
	ajaxGet(npag + "?cod_cliente=" + cod_cliente, document.getElementById(nElemento), true);	
}
function checkemail(email){
	var str=email;
	var filter=/^.+@.+\..{2,3}$/;
	if (filter.test(str))
		testresults=true;
	else{
		alert("Por Favor insira um email válido!");
		testresults=false;
	}
	return testresults;
}


function formPeloNome(formName){
// recebe uma string de texto e retorna o seu
// formulário correspondente
// caso inexistente, retornará null
// utilização:
//		evento="formPeloNome('nomeDoForm').metodo();"
// pré-requisitos:
//		nenhum;
	var Forms = document.forms;
	for(var i=0; i<Forms.length; i++){
		if(Forms[i].name==formName){
			return Forms[i];
		}
	}
	return null;
}
function elementPeloNome(formName, elementName){
// recebe uma string de texto e retorna o seu
// objeto do form correspondente
// caso inexistente, retornará null
// utilização:
//		evento="elementPeloNome('nomeDoForm','nomeDoObjeto').metodo();"
// pré-requisitos:
//		formPeloNome();
	var Form;
	try{
		Form = formPeloNome(formName);
	}catch(ex){
		Form = formName;
	}
	try{
		for(var i=0; i<Form.length; i++){
			if(Form.elements[i].name==elementName){
				return Form.elements[i];
			}
		}
	}catch(ex){
		return null;
	}
}
function postaForm(formName){
// recebe uma string de texto envia os dados do formulário correspondente
// caso form inexistente, não executará comando algum
// utilização:
//		evento="postaForm('nomeDoForm');"
// pré-requisitos:
//		formPeloNome();
	try{
		formPeloNome(formName).submit();
	}catch(ex){}
}

function verifica_datas(nCampo){ 
  dia = (nCampo.value.substring(0,2)); 
  mes = (nCampo.value.substring(3,5)); 
  ano = (nCampo.value.substring(6,10)); 
		
  // verifica data
  if (nCampo.value != "") {
	  if ((dia < 01 ) || (dia > 31) || (mes < 01) ||(mes > 12) || (ano < 1990)){ 
		  alert("Data inválida!");
		  nCampo.focus(); 
		  return false;
	  } 
  }
}

function numdias(mes,ano) {   
	//mês ímpar menor que 8 ou mês par maior que 7 tem 31 dias   
	if((mes<8 && mes%2==1) || (mes>7 && mes%2==0)) return 31;   
	//se não for fevereiro, os outros meses que não os de cima têm 30 dias   
	if(mes!=2) return 30;   
	//ano bissexto é múltiplo de 4   
	if(ano%4==0) return 29;   
	return 28;
}

function formataDataMDA(data) {   // data deve ser uma string
	data=data.split('/');  
	dia=parseInt(data[0]);  
	mes=parseInt(data[1]);  
	ano=parseInt(data[2]);  
	return mes+"/"+dia+"/"+ano; // retorna no formato data MDA
}

function formataDataDMA(data) {   // data deve ser um Date
	var dia, ano, mes
	dia = data.getDate();
	mes = (data.getMonth()+1);
	ano = data.getFullYear();
	if (dia < 10){
		dia = ('0'+dia);
	}
	if (mes < 10){
		mes = ('0'+mes);
	}
	return dia+"/"+mes+"/"+ano; // retorna no formato data MDA
}

function somadias(data, dias) {   // data deve ser uma string, dias deve ser inteiro
	var i;
	i = 0;
	data=data.split('/');  
	diafuturo=data[0];  
	if (diafuturo.substring(0,1) == '0'){
		diafuturo=parseInt(diafuturo.substring(1,2));  
	}else{
		diafuturo=parseInt(diafuturo);  
	}
	mes=data[1];  
	if (mes.substring(0,1) == '0'){
		mes=parseInt(mes.substring(1,2));  
	}else{
		mes=parseInt(mes);  
	}
	ano=parseInt(data[2]);  
	for (i=0; i<dias; i++){ 
		diafuturo++;      
		if (diafuturo > numdias(mes,ano)){
			diafuturo = 1;
			mes++;      
			if(mes>12) {          
				mes=1;          
				ano++;      
			}  
		}
	}  
	if(diafuturo<10) diafuturo='0'+diafuturo;  
	if(mes<10) mes='0'+mes;  
	return new Date(mes+"/"+diafuturo+"/"+ano); // retorna no formato data
}

    function gravaPlanilha(nForm){
		var d = new Date(formataDataMDA(document.getElementById('dataIni').value));
		var	dia, mes, ano, sData, total, s;
		total = eval(document.getElementById('totDias').value);
		for (contador=0; contador<total; contador++){ 
			dia	= d.getDate();
			mes	= (d.getMonth()+1);
			ano	= d.getFullYear();
			if (parseInt(dia) < 10){
				//alert('mudando dia de '+dia+' para 0'+dia);
				dia = '0'+dia;
			}
			if (parseInt(mes) < 10){
				mes = '0'+mes;
			}
			sData 	= (dia+mes+ano);
			s 		= (dia+'/'+mes+'/'+ano);
			//alert(s+' = '+sData);
			//document.write('/emw/system/apontahoras/grava_apontamento.asp?dini='+document.getElementById('dataIni').value+'&dfin='+document.getElementById('dataFin').value+'&data='+s+'&e='+document.getElementById('entrada_'+sData).value+'&s='+document.getElementById('saida_'+sData).value+'&t='+document.getElementById('total_'+sData).value+'&a='+document.getElementById('acao_'+sData).value+'&cli='+document.getElementById('codCli').value+'&con='+document.getElementById('codCon').value+'&seq='+document.getElementById('seq_'+sData).value);
			ajaxGet('/emw/system/apontahoras/grava_apontamento.asp?dini='+document.getElementById('dataIni').value+'&dfin='+document.getElementById('dataFin').value+'&data='+s+'&he='+document.getElementById('entrada_'+sData).value+'&hs='+document.getElementById('saida_'+sData).value+'&ht='+document.getElementById('total_'+sData).value+'&a='+document.getElementById('acao_'+sData).value+'&cli='+document.getElementById('codCli').value+'&con='+document.getElementById('codCon').value+'&seq='+document.getElementById('seq_'+sData).value,document.getElementById('gravacao'),true);
			d = somadias(s,1); 
		}
		alert('Dados Gravados com Sucesso');
    }
