// Início das Funções de Calendário

var oldLink = null;
// code to change the active stylesheet
function setActiveStyleSheet(link, title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
  if (oldLink) oldLink.style.fontWeight = 'normal';
  oldLink = link;
  link.style.fontWeight = 'bold';
  return false;
}

// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
 // if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3"))
    // if we add this call we close the calendar on single-click.
    // just to exemplify both cases, we are using this only for the 1st
    // and the 3rd field, while 2nd and 4th will still require double-click.
 if (cal.dateClicked)
	  cal.callCloseHandler();
}

function mostra_thumbs(paLink, paNome)
{
	var wind;
	wind = window.open(paLink,paNome,"width=100, height=100");
	if (parseInt(navigator.appVersion) >= 4) { wind.window.focus(); }
}


// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, format,pos) { 
  var el = document.getElementById(id);
  if (calendar != null) {
    // we already have some calendar created
    calendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(false, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    calendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  calendar.setDateFormat(format);    // set the specified date format
  calendar.parseDate(el.value);      // try to parse the text in field
  calendar.sel = el;                 // inform it what input field we use

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  calendar.showAtElement(el.nextSibling, "Br",pos);        // show the calendar
  
  return false;
}

var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;

// If this handler returns true then the "date" given as
// parameter will be disabled.  In this example we enable
// only days within a range of 10 days from the current
// date.
// You can use the functions date.getFullYear() -- returns the year
// as 4 digit number, date.getMonth() -- returns the month as 0..11,
// and date.getDate() -- returns the date of the month as 1..31, to
// make heavy calculations here.  However, beware that this function
// should be very fast, as it is called for each day in a month when
// the calendar is (re)constructed.
function isDisabled(date) {
  var today = new Date();
  return (Math.abs(date.getTime() - today.getTime()) / DAY) > 10;
}

function flatSelected(cal, date) {
  var el = document.getElementById("preview");
  el.innerHTML = date;
}

function showFlatCalendar() {
  var parent = document.getElementById("display");

  // construct a calendar giving only the "selected" handler.
  var cal = new Calendar(false, null, flatSelected);

  // hide week numbers
  cal.weekNumbers = false;

  // We want some dates to be disabled; see function isDisabled above
  cal.setDisabledHandler(isDisabled);
  cal.setDateFormat("DD, M d");

  // this call must be the last as it might use data initialized above; if
  // we specify a parent, as opposite to the "showCalendar" function above,
  // then we create a flat calendar -- not popup.  Hidden, though, but...
  cal.create(parent);

  // ... we can show it here.
  cal.show();
}

// Fim das Funções de Calendário

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function erro(paObjeto,paMsg)
{
	alert(paMsg);
	paObjeto.focus();
	return true;
}

function copia( paIni, paQde, paForm, paObjeto, paMarca, paTipo ) //Copia a propriedade de um campo para outros baseado no primeiro (paIni)
{
	if (paMarca==paIni)
	{
		for (i=paIni+1;i<paQde ;i++ )
		{
			switch (paTipo)
			{
			case "t":
				if (document.getElementById(paForm).elements[paObjeto+"["+i+"]"].value=="")
				{
					document.getElementById(paForm).elements[paObjeto+"["+i+"]"].value = document.getElementById(paForm).elements[paObjeto+"["+paIni+"]"].value;
				}
				break;
			case "c":
				if (document.getElementById(paForm).elements[paObjeto+"["+paIni+"]"].checked==true)
					document.getElementById(paForm).elements[paObjeto+"["+i+"]"].checked=true;
				else
					document.getElementById(paForm).elements[paObjeto+"["+i+"]"].checked=false;
				break;
			case "r":
				if (document.getElementById(paForm).elements[paObjeto+"["+paIni+"]"][0].checked==true)
					document.getElementById(paForm).elements[paObjeto+"["+i+"]"][0].checked=true;
				else
					document.getElementById(paForm).elements[paObjeto+"["+i+"]"][1].checked=true;
				break;
			}
		}
	}
}

function replica( paIni, paQde, paForm, paObjeto, paMarca, paTipo ) //Copia a propriedade de um campo para outros baseado no atual (paMarca)
{
	for (i=paIni;i<paQde ;i++ )
	{
		if (paMarca!=i)
		{
			switch (paTipo)
			{
			case "t":
				document.getElementById(paForm).elements[paObjeto+"["+i+"]"].value = document.getElementById(paForm).elements[paObjeto+"["+paMarca+"]"].value;
				break;
			case "b":
				document.getElementById(paForm).elements[paObjeto+"["+i+"]"].selectedIndex = document.getElementById(paForm).elements[paObjeto+"["+paMarca+"]"].selectedIndex;
				break;
			case "c":
				if (document.getElementById(paForm).elements[paObjeto+"["+paMarca+"]"].checked==true)
					document.getElementById(paForm).elements[paObjeto+"["+i+"]"].checked=true;
				else
					document.getElementById(paForm).elements[paObjeto+"["+i+"]"].checked=false;
				break;
			case "r":
				if (document.getElementById(paForm).elements[paObjeto+"["+paMarca+"]"][0].checked==true)
					document.getElementById(paForm).elements[paObjeto+"["+i+"]"][0].checked=true;
				else
					document.getElementById(paForm).elements[paObjeto+"["+i+"]"][1].checked=true;
				break;
			}
		}
	}
}

function ClicaBotao(paForm,paCampo,paValor) //Funcao utilizada no botam Flash
{ 
	document.forms[paForm].elements[paCampo].value= paValor;
}

function DesclicaBotao(paForm,paCampo) //Funcao utilizada no botam Flash
{
	document.forms[paForm].elements[paCampo].value='';
}
	
function isNum( caractere ) //verifica se o caractere é um numero
{ 
         var strValidos = "0123456789" 
         if ( strValidos.indexOf( caractere ) == -1 ) 
                 return false; 
         return true; 
} 

function validaTecla(campo, event) //verifica a tecla pressionada
{ 
         var BACKSPACE=  8; 
         var key; 
         var tecla; 


         CheckTAB=true; 
         if(navigator.appName.indexOf("Netscape")!= -1) 
                 tecla= event.which; 
         else 
                 tecla= event.keyCode; 


         key = String.fromCharCode( tecla); 
//         alert( 'key: ' + tecla + '  -> campo: ' + campo.value); 


         if ( tecla == 13 ) 
                 return false; 
         if ( tecla == BACKSPACE ) 
                 return true;
		 if ( tecla == 37 ) //seta
                 return true;
		 if ( tecla == 39 ) //seta
                 return true;
		 if ( tecla == 46 ) // del
                 return true;
  		 if ( tecla == 16 ) // shift
                 return true;
         return ( isNum(key)); 
} 

function mascara_data_simples(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 verificaData(data,id){
	if(data != "")
	  if(!checadata(data)){
	    alert('Data inválida!');
	    document.getElementById(id).focus();
	  }
}

function validaCPF_CNPJ(pega, tipo,nome){
  if(pega.length > 0){
  	var erro = false;
    if(validaNumero(pega, tipo)){
  	  if(pega.length < 12){ 
  	    if(!cpf ( pega)){
  	      alert('CPF inválido!');
  	      document.getElementById(nome).focus();	
  	      erro = true;
  	    }
  	  }else{
  	    if(!cgc ( pega)){
  	      alert('CNPJ inválido!');
  	      document.getElementById(nome).focus();	
  	      erro = true;
  	    }
  	  }
    }else{
  	  alert('Somente números são aceitos!');
  	  erro = true;
  	  document.getElementById(nome).focus();
    }
    return erro;
  }
}

function mask_data( paObj,paEvent ) //Insere Mascara de DATA no campo utlizar "onKeyUp=mascara_data(this,event); onFocus=this.select();"
{ 
	if (!validaTecla(paObj,paEvent))
	{
		data    = paObj.value;
		total   = data.length;
		
		data = converte_numero ( data );
		if (data.length<7)
			paObj.value = data.substring(0,2) + '/' + data.substring(2,6);
		else
			paObj.value = data.substring(0,2) + '/' + data.substring(2,4) + '/' + data.substring(4,8);
	}
}

function mascara_data( paObj,paEvent ) //Essa Tem bug, mas tem soft q ainda usa ela. A mask_data ej melhor
{ 
		data    = paObj.value;
		total   = data.length;
		
		data = converte_numero ( data );
		if (data.length<7)
			paObj.value = data.substring(0,2) + '/' + data.substring(2,6);
		else
			paObj.value = data.substring(0,2) + '/' + data.substring(2,4) + '/' + data.substring(4,8);
}

function tamanhoJanela( paLargura, paAltura)
{
	var winX, winY, vmLar, vmAlt;
	vmLar= paLargura;
	vmAlt= paAltura;
	winX = (screen.availWidth - vmLar) / 2;
	winY = (screen.availHeight - vmAlt) / 2;
	window.resizeTo( vmLar, vmAlt);
	window.moveTo( winX, winY);
}

function janela(paLink, paNome, paLar, paAlt) // abre uma janela do browser nova
{
	var winX, winY, wind;
	if ((screen.availWidth-50) < paLar || (screen.availHeight-50) < paAlt)
	{
		winX = 10;
		winY = 10;
		paLar = screen.availWidth-50;
		paAlt = screen.availHeight-50;
	}
	else
	{
		winX = (screen.availWidth - paLar) / 2;
		winY = (screen.availHeight - paAlt) / 2;
	}

	wind = window.open(paLink,paNome,"width="+paLar+",height="+paAlt+",toolbars=no,status=no,scrollbars=yes,resizable=yes,top="+winY+",left="+winX+"");
	if (parseInt(navigator.appVersion) >= 4) { wind.window.focus(); }
}

function popUp(paLink, paNome, paLar, paAlt, paScrol, paResize) // abre uma janela do browser nova com a opção de scrol
{
	var winX, winY, wind;
	if ((screen.availWidth-50) < paLar || (screen.availHeight-50) < paAlt)
	{
		winX = 10;
		winY = 10;
		paLar = screen.availWidth-50;
		paAlt = screen.availHeight-50;
	}
	else
	{
		winX = (screen.availWidth - paLar) / 2;
		winY = (screen.availHeight - paAlt) / 2;
	}
		
	wind = window.open(paLink,paNome,"width="+paLar+",height="+paAlt+",toolbars=no,status=no,scrollbars="+paScrol+",resizable="+paResize+",top="+winY+",left="+winX+"");
	if (parseInt(navigator.appVersion) >= 4) { wind.window.focus(); }
}


/*function cpf ( paCpf ) // verifica a validação de CPF
{
	var i; 
	s = paCpf; 
	var c = s.substr(0,9); 
	var dv = s.substr(9,2); 
	var d1 = 0; 
	vmRetorno = true;	

	for (i = 0; i < 9; i++) 
	{ 
		d1 += c.charAt(i)*(10-i); 
	} 
	
	if (d1 == 0){ 
		vmRetorno = false; 
	} 
	
	d1 = 11 - (d1 % 11); 
	
	if (d1 > 9) d1 = 0; 
	
	if (dv.charAt(0) != d1) 
	{ 
		vmRetorno = 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) 
	{ 
		vmRetorno = false; 
	} 

	return vmRetorno;
}


function cgc(pcgc) // faz verificação de CNPJ
{
	// verifica o tamanho
	if (pcgc.length != 14) 
	{
		sim=false;
	}
	else 
	{
		sim=true;
	}

	if (sim )  // verifica se e numero
	{
		for (i=0;((i<=(pcgc.length-1))&& sim); i++)
		{
			val = pcgc.charAt(i)
			// alert (val)
			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)  // se for numero continua
		{
			m2 = 2
			soma1 = 0
			soma2 = 0
			for (i=11;i>=0;i--)
			{
				val = eval(pcgc.charAt(i))
				// alert ("Valor do Val: "+val)
				m1 = m2
				if (m2<9) 
				{ 
					m2 = m2+1;
				}
				else 
				{
					m2 = 2;
				}
				soma1 = soma1 + (val * m1)
				soma2 = soma2 + (val * m2)
			}  // fim do for de soma

			soma1 = soma1 % 11
			if (soma1 < 2) 
			{
				d1 = 0;
			}
			else 
			{ 
				d1 = 11- soma1;
			}

			soma2 = (soma2 + (2 * d1)) % 11
			if (soma2 < 2) 
			{ 
				d2 = 0;
			}
			else 
			{ 
				d2 = 11- soma2;
			}
			// alert (d1)
			// alert (d2)
			if ((d1==pcgc.charAt(12)) && (d2==pcgc.charAt(13)))
			{ 
				return true; 
			}
			else 
				return false;
		}
	}
}
*/

function cpf ( paCpf )
{
	var i; 
	s = paCpf; 
	var c = s.substr(0,9); 
	var dv = s.substr(9,2); 
	var d1 = 0; 
	vmRetorno = true;	

	if (paCpf.length>11)
	{
		vmRetorno = false;
	}
	else
	{
		if (!numeros_diferentes(paCpf))
		{
			vmRetorno = false;
		}
		else
		{
			for (i = 0; i < 9; i++) 
			{ 
				d1 += c.charAt(i)*(10-i); 
			} 
			
				if (d1 == 0){ 
					vmRetorno = false; 
				} 
			
			d1 = 11 - (d1 % 11); 
			
			if (d1 > 9) d1 = 0; 
			
			if (dv.charAt(0) != d1) 
			{ 
				vmRetorno = 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) 
			{ 
				vmRetorno = false; 
			} 
		}
	}

	return vmRetorno;

}

function numeros_diferentes( num )
{
	tam		= num.length;
	vmStr	= num.substring(0,1);
	vmIgual	= false;

	for (i=0;i<tam ;i++ )
	{
		if (vmStr != num.substring(i,i+1))
		{
			vmIgual = true;
		}
		vmStr = num.substring(i,i+1);
	}

	return vmIgual;
}

function cgc(pcgc)
{
// verifica o tamanho
	if (pcgc.length != 14) 
	{
	sim	= false;
	//alert ("Tamanho Invalido de CGC")
	}
	else
	{
		sim=true;
	}

    if (sim )  // verifica se e numero
	{
		for (i=0;((i<=(pcgc.length-1))&& sim); i++)
		{
			val = pcgc.charAt(i);
       // alert (val)
			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)  // se for numero continua
	{
		m2 = 2;
		soma1 = 0;
		soma2 = 0;
		for (i=11;i>=0;i--)
	    {
			val = eval(pcgc.charAt(i));
	       // alert ("Valor do Val: "+val)
			m1 = m2;
			if (m2<9) 
				{ 
				m2 = m2+1;
				}
			else 
				{
				m2 = 2;
				}
			
			soma1 = soma1 + (val * m1);
			soma2 = soma2 + (val * m2);
		}  // fim do for de soma

		soma1 = soma1 % 11;

		if (soma1 < 2)
			{
			d1 = 0;
			}
		else
			{
			d1 = 11- soma1;
			}

		soma2 = (soma2 + (2 * d1)) % 11
  
		if (soma2 < 2)
			{
			d2 = 0;
			}
		else
			{
			d2 = 11- soma2;
			}
			// alert (d1)
			// alert (d2)
		
		if (!numeros_diferentes(pcgc))
		{
			return false;
		}
		else
		{
			if ((d1==pcgc.charAt(12)) && (d2==pcgc.charAt(13)))
			{
				return true; 
			}
			else
			{
				return false;
			}
		}
   }
 }

 }

function CPF_CNPJ( paStr )
{
	valido = false;
	if ( cgc( paStr ) || cpf( paStr ) )
	{
		valido = true;
	}
	return valido;
}

function compara_data(data, data_ant)
{
	 dia = eval(data.substring(0,2));
	 mes = eval(data.substring(3,5));
	 ano = eval(data.substring(6,10));
	 
	 td  = eval(data_ant.substring(0,2));
	 tm  = eval(data_ant.substring(3,5));
	 ta  = eval(data_ant.substring(6,10));

	 if (td >= 0 && td <= 9)
	 {
		 td = '0'+td;
	 }
	 if (tm >= 0 && tm <= 9)
	 {
		 tm = '0'+tm;
	 }
	 if (dia >= 0 && dia <= 9)
	 {
		 dia = '0'+dia;
	 }
	 if (mes >= 0 && mes <= 9)
	 {
		 mes = '0'+mes;
	 }

	 data_anterior = eval(ta+''+tm+''+td);
	 data_atual   = eval(ano+''+mes+''+dia);


	 if (data_anterior <= data_atual)
	 {
		 return false;
	 }
	 else
		 return true;

}

function data_inferior(data, data_ant)
{
	 dia = eval(data.substring(0,2));
	 mes = eval(data.substring(3,5));
	 ano = eval(data.substring(6,10));
	 
	 td  = eval(data_ant.substring(0,2));
	 tm  = eval(data_ant.substring(3,5));
	 ta  = eval(data_ant.substring(6,10));

	 if (td >= 0 && td <= 9)
	 {
		 td = '0'+td;
	 }
	 if (tm >= 0 && tm <= 9)
	 {
		 tm = '0'+tm;
	 }
	 if (dia >= 0 && dia <= 9)
	 {
		 dia = '0'+dia;
	 }
	 if (mes >= 0 && mes <= 9)
	 {
		 mes = '0'+mes;
	 }

	 data_anterior = eval(ta+''+tm+''+td);
	 data_atual   = eval(ano+''+mes+''+dia);


	 if (data_anterior < data_atual)
		 return true;
	 else
		 return false;
}

function checadata(data) // faz verificação de data
{
	
	retorno = true;

	if (data == '' && data.length!=10 && data.length!=7)
		{
		retorno = false;
		}
	else
		{

		vet_dia    = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
		vet_dia_bi = new Array(31,29,31,30,31,30,31,31,30,31,30,31);
		
		if (data.length==10)
			{
			ba2 = data.substring(5,6);
			ba1 = data.substring(2,3);
			vtData = data.split("/");	
			dia = vtData[0];
			mes = vtData[1];			
			year = String(vtData[2]);
			}
		else
			{
			dia = 15;
			ba2 = '/';
			mes = data.substring(0,2);
			ba1 = data.substring(2,3);
			year = data.substring(3,7);
			}

		if (!sonumero(dia, 'i') || !sonumero(mes, 'i') || !sonumero(year, 'i'))
			{
			retorno = false;
			}
		else
			{

			if ( (ba1 != '/') || (ba2 != '/'))
				{
				retorno = false;
				}

			if (eval(year) < 1900)
				{
				retorno = false;
				}

			if ( (eval(mes) < 1) || (eval(mes) > 12))
				{
				retorno = false;
				}

			if ((eval(year) % 4 ) == 0)
				{
				if ( (eval(dia) < 1) || (eval(dia) > vet_dia_bi[eval(mes)-1]) )
					retorno = false;
				}
			else
				{
				if ( (eval(dia) < 1) || (eval(dia) > vet_dia[eval(mes)-1]) )
					retorno = false;
				}
			}
		}

	return retorno;
}

function checahora(hora) // faz verificação de hora
{
	retorno = true;
	if (hora == '' || hora.length!=8)
	{
		retorno = false;
	}
	else
	{
		hor = hora.substring(0,2);
		se1 = hora.substring(2,3);
		min = hora.substring(3,5);
		se2 = hora.substring(5,6);
		seg = hora.substring(6,8);
		if((hor<00 || hor>23) || (se1!=":") || (min<00 || min>59) || (se2!=":") || (seg<00 || seg>59))
		{
			retorno = false;
		}
		else
		{
			retorno = true;
		}
	}
	return retorno;
}

function converte_numero ( paString ) //Converte uma string em numero
{
	tam		= paString.length;
	indice  = 0;
	vmString= "";

	for (cont=0;cont<tam ;cont++ )
	{
		if (paString.charAt(cont)==",")
		{
			vmString += "." ;
		}
		else
		{
			if (paString.charAt(cont)<=9)
			{
			vmString += paString.charAt(cont);
			}
		}
	}

	return vmString;
}

function retiraPontos( paString ) //Retorna somente os numeros de uma String
{
	tam		= paString.length;
	indice  = 0;
	vmString= "";

	for (cont=0;cont<tam ;cont++ )
	{
		if (paString.charAt(cont)<=9)
		{
			vmString += paString.charAt(cont);
		}
	}

	return vmString;
}

function sonumero(pega, tipo) // faz verificação de número
{
	retorno = true;
	if ( tipo=="m" && qde_chars(pega, ",")>0 && qde_chars(pega, ".")>0 )
		retorno = false;
	else if ( qde_chars(pega, ",")>1 || qde_chars(pega, ".")>1 )
		retorno = false;
	else
	{
		if (tipo=="m")
			tipo="f";

		for (w=0; w<pega.length; w++)
			{
			ponto=0;
			if ( (pega.substring(w,w+1) < '0') || (pega.substring(w,w+1) > '9') )
				{
				if (tipo == 'f' && (pega.substring(w,w+1)=="." || pega.substring(w,w+1)=="," || pega.substring(0,1)=="-") && ponto==0)
					{ponto=1;}
				else
				retorno = false;
				}
			}
	}
	return retorno;
}

function qde_chars(texto, caracter) // faz verificação de quantos carateres caracter tem em pega
{
	qde=0;
	for (ind=0; ind<texto.length; ind++)
		{
		if ( (texto.substring(ind,ind+1) == caracter ) )
			qde++;
		}
	return qde;
}

function formata(num) { 
var sign, cents; 
num = num.toString().replace(/\$|\,/g,''); 
if(isNaN(num)) 
num = "0"; 
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 (((sign)?'':'-') + num + ',' + cents); 
}

function decimal(pega)
{
	var string;
	string = "";
	for (x=0; x<pega.length; x++)
	{
		if (pega.substring(x,x+1) == ",")
		{
			string = string + ".";
		}
		else
		{
			string = string + pega.substring(x,x+1);				
		}
	}
	return string;
}

function num_real( num )
{
	tam = num.length;
	ret	= '';
	str = '';

	if (tam>0)
	{
		for (z=0;z<tam ;z++ )
		{
			str = num.substring(z,z+1);
			if (num.substring(z,z+1)==".")
				str = "";
			else
			{
				if (num.substring(z,z+1)==",")
					str = ".";
			}
			ret = ret + str;				
		}
	}

	return ret;
}

function validaEmailBlur(email,id){
  if(email.length > 0)
    if(valida_email(email)){
  	  alert('E-mail inválido!')
  	  document.getElementById(id).focus();
    }
}

function checkMail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if(typeof(mail) == "string"){
        if(er.test(mail)){ return true; }
    }else if(typeof(mail) == "object"){
        if(er.test(mail.value)){ 
                    return true; 
                }
    }else{
        return false;
        }
}

function valida_email(paCampo) // verifica a validade do e-mail
{
	var erros = false;
	if (paCampo == "")
	{
		erros = true;
	}
	else{
		prim = paCampo.indexOf("@")
		if(prim < 2)
			{
				erros = true;
			}
		if(paCampo.indexOf("@",prim + 1) != -1)
			{
				erros = true;
			}
		if(paCampo.indexOf(".") < 1)
			{
				erros = true;
			}
		if(paCampo.indexOf(" ") != -1)
			{
				erros = true;
			}
		if(paCampo.indexOf(".@") > 0)
			{
				erros = true;
			}
		if(paCampo.indexOf("@.") > 0)
			{
				erros = true;
			}
		if(paCampo.indexOf(".com.br.") > 0)
			{
				erros = true;
			}
		if(paCampo.indexOf("/") > 0)
			{
				erros = true;
			}
		if(paCampo.indexOf("[") > 0)
			{
				erros = true;
			}
		if(paCampo.indexOf("]") > 0)
			{
				erros = true;
			}
		if(paCampo.indexOf("(") > 0)
			{
				erros = true;
			}
		if(paCampo.indexOf(")") > 0)
			{
				erros = true;
			}
		if(paCampo.indexOf("..") > 0)
			{
				erros = true;
			}
	}
	if (!erros)
	{
		return false;
	}
	else
	{
		return true;
	}
}

function seleciona_todos( paForm, paMarca, paCampo, paQde )
{
	form = document.getElementById(paForm);
	if (form.elements[paMarca+"[0]"].checked)
	{
		for ( z=0; z<(paQde);z++ )
		{
			form.elements[paCampo+"["+z+"]"].checked=true;
		}
	}
	else
	{
		for ( z=0; z<(paQde);z++ )
		{
			form.elements[paCampo+"["+z+"]"].checked=false;
		}
	}
}

function ver_seleciona_todos( paForm, paMarca, paCampo, paQde, paInd )
{
	form = document.getElementById(paForm);
	if (form.elements[paCampo+"["+paInd+"]"].checked==false)
		form.elements[paMarca+"[0]"].checked=false;
	else
	{
		check = true;
		for ( z=0; z<(paQde);z++ )
		{
			if ( check && form.elements[paCampo+"["+z+"]"].checked==false)
			{
				check=false;
			}
		}
		if (check==false)
		{
			form.elements[paMarca+"[0]"].checked=false;
		}
		else
		{
			form.elements[paMarca+"[0]"].checked=true;
		}
	}
}

function formata_cep(e,src,mask) {
    if(window.event) { _TXT = e.keyCode; } 
    else if(e.which) { _TXT = e.which; }
    if(_TXT > 47 && _TXT < 58) { 
 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); } 
    return true; } else { if (_TXT != 8) { return false; } 
 else { return true; }
    }
}

 //Esta Função eu alterei os campos de entrada e melhorei algumas coisas. Manter esta
    function mascara(obj, 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 = obj.value;

      if (sMask == '(99) 999-9999') {
	     if (sValue.length > 12) {
		    sMask = '(99) 9999-9999';
		 }
	  }
	  
	  if (sMask == '99/9999') {
	     if (sValue.length < 5) {
		    sMask = '9999';
		 }
	  }

      // 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( " ", "" );
      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) == " "))

        if (bolMask) {
          sCod += sMask.charAt(i);
          mskLen++; }
        else {
          sCod += sValue.charAt(nCount);
          nCount++;
        }

        i++;
      }

      obj.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;
      }
    }

// função que verifica se tem algum check selecionado. Precisa passar document.nome_do_form no primeiro parametreo e o nome do campo no segundo
function verificaChecSelecionado(form,paCampo)
{
	x=0;
	checado = false;
	while ( form.elements(paCampo+'['+x+']')!= null && !checado)
	{
		campo = form.elements(paCampo+'['+x+']');
		checado = campo.checked;
		x++;	
	}
	
	return checado;
}

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 || whichCode == 8 || whichCode == 0) 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 getParam (paForm, paOutraJanela){
	if(paOutraJanela){
		var form = window.opener.document.getElementById(paForm);
	}else{
  	var form = document.getElementById(paForm);
	}
	
	try{
	  var vtForm = form.getElementsByTagName('input');
	  var param = "";
	  param = param + vtForm[0].id+"="+vtForm[0].value;
	  for(var i=1;i<vtForm.length;i++){
	  	if(vtForm[i].id != ""){
	  	  if(vtForm[i].type == 'radio'){
	  	  	if(vtForm[i].checked){
	  	  	  var parametro = vtForm[i].value;
	  	  	  while(parametro.indexOf("&") != -1){
	  	  	    parametro = parametro.replace("&","#E#");
	  	  	  }
	          param = param + "&"+vtForm[i].id+"="+parametro;  	  	  
	  	  	}
	  	  }else if(vtForm[i].type == 'checkbox'){
	  	  	if(vtForm[i].checked){
	  	  	  var parametro = vtForm[i].value;
	  	  	  while(parametro.indexOf("&") != -1){
	  	  	    parametro = parametro.replace("&","#E#");
	  	  	  }
	          param = param + "&"+vtForm[i].id+"="+parametro;  	  	  
	  	  	}
	  	  }else{
	  	  	var parametro = vtForm[i].value;
	  	  	  while(parametro.indexOf("&") != -1){
	  	  	    parametro = parametro.replace("&","#E#");
	  	  	  }
	          param = param + "&"+vtForm[i].id+"="+parametro; 
	  	  }
	  	}
	  }
	  var vtForm = form.getElementsByTagName('select');
	  for(var i=0;i<vtForm.length;i++){
	  	if(vtForm[i].id != ""){
	      var parametro = vtForm[i].value;
	  	  	  while(parametro.indexOf("&") != -1){
	  	  	    parametro = parametro.replace("&","#E#");
	  	  	  }
	          param = param + "&"+vtForm[i].id+"="+parametro; 
	  	}
	  }
	  var vtForm = form.getElementsByTagName('textarea');
	  for(var i=0;i<vtForm.length;i++){
	  	if(vtForm[i].id != ""){
	      var parametro = vtForm[i].value;
	  	  	  while(parametro.indexOf("&") != -1){
	  	  	    parametro = parametro.replace("&","#E#");
	  	  	  }
	          param = param + "&"+vtForm[i].id+"="+parametro; 
	  	}
	  }
	  return param;
	}catch(e){
		return false;
	}
}

function openAjax() {
  var ajax;
	try{
	    ajax = new XMLHttpRequest(); // XMLHttpRequest para browsers decentes, como: Firefox, Safari, dentre outros.
	}catch(ee){
	    try{
	        ajax = new ActiveXObject("Msxml2.XMLHTTP"); // Para o IE da MS
	    }catch(e){
	        try{
	            ajax = new ActiveXObject("Microsoft.XMLHTTP"); // Para o IE da MS
	        }catch(E){
	            ajax = false;
	        }
	    }
	}
	return ajax;
}

function extraiScript(texto){
    var ini = 0;
    while (ini!=-1) {
        ini = texto.indexOf('<script', ini);
        if (ini >=0) {
            ini = texto.indexOf('>', ini) + 1;
            var fim = texto.indexOf('</script>', ini);
            codigo = texto.substring(ini,fim);
            eval(codigo);
        }
    }
}

function getQtdPaginacao(){
	var pag = 0;
	if (parseInt(navigator.appVersion)>3) {
		 if (navigator.appName=="Netscape") {
		  winW = screen.width;
		  winH = screen.height;
		  if((winW - winH) == 200){
		  	pag = 10;
		  }
		  
		  if((winW - winH) == 256){
		  	pag = 17;
		  }
		  
		  if((winW - winH) > 256){
		  	pag = 18;
		  }
		 }
		 if (navigator.appName.indexOf("Microsoft")!=-1) {
		  winW = screen.width;
		  winH = screen.height;
		  if((winW - winH) == 200){
		  	pag = 12;
		  }
		  
		  if((winW - winH) == 256){
		  	pag = 19;
		  }
		  
		  if((winW - winH) > 256){
		  	pag = 20;
		  }
		 }
	}
	
	return pag;
}

function carrega( paDiv, local, paOutraJanela ) {
	try{
    tbody = document.createElement("tbody");
    table = document.createElement("table");
    table.className = "carregando";
    tr    = document.createElement("tr");
    td    = document.createElement("td");
    label = document.createElement("label")

    label.innerHTML = " <img src='"+local+"apoio/img/carregando.gif"+"'> ";
    
    td.appendChild( label );
    tr.appendChild( td );
    table.appendChild( tr );
    
    table1 = document.createElement("table");
    table1.setAttribute( "width", '100%' );
    table1.setAttribute( "height", '100%' );
    tr1    = document.createElement("tr");
    td1    = document.createElement("td");
    td1.setAttribute( "align", 'center' );
    td1.appendChild( table )
    tr1.appendChild( td1 );
    table1.appendChild( tr1 );

    tbody.appendChild( table1 );
    
    if(paOutraJanela){
    	window.opener.document.getElementById(paDiv).innerHTML = tbody.innerHTML;
    }else{
			document.getElementById(paDiv).innerHTML = tbody.innerHTML;
    }
	}catch(e){
		//nada
	}
}

function buscaGen(paResultado, paCaminho,paForm,local,paOutraJanela, paFechaJanela){
	try{
		if(paOutraJanela){
			var exibeResultado = window.opener.document.getElementById(paResultado);
		}else{
			var exibeResultado = document.getElementById(paResultado); // div que exibirá o resultado da busca.
		}
		/*alert(exibeResultado.id);
		alert(paCaminho);*/
		var ajax = openAjax(); // Inicia o Ajax.
	
		if(paForm != ""){
		var param = getParam(paForm, paOutraJanela);
			//param = param + "&vfPaginacao="+getQtdPaginacao();
			ajax.open("POST", paCaminho , true); // Envia o termo da busca como uma querystring, nos possibilitando o filtro na busca.
			ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		    ajax.setRequestHeader("Content-length", param.length);
		    ajax.setRequestHeader("Connection", "close");
		    ajax.send(param);
	    }else{
		  ajax.open("GET", paCaminho , true);	
		  ajax.send(null);
		}
		carrega(paResultado,local,paOutraJanela);
	    
		ajax.onreadystatechange = function() {
			if(ajax.readyState == 1) { // Quando estiver carregando, exibe: carregando...
				exibeResultado.style.display = 'block';
			}
			if(ajax.readyState == 4) { // Quando estiver tudo pronto.
				if(ajax.status == 200) {
					try{
						var resultado = ajax.responseText; // Coloca o resultado (da busca) retornado pelo Ajax nessa variável (var resultado).
						exibeResultado.innerHTML = resultado;
						extraiScript(resultado);
						if(paFechaJanela){
							self.close();
						}
					}catch(e){
						//nada
					}
				} else {
					try{
						exibeResultado.innerHTML = "Erro no componente AJAX.";
					}catch(e){
						//nada
					}
				}
			}
		}
	}catch(e){
		//nada
	}
}

//Faz o controle de abas, funciona em ambos os browsers
function stAba(bgRelatorioLabel,conteudo) {
	this.bgRelatorioLabel = bgRelatorioLabel;
	this.conteudo = conteudo;
}

//os nros depois dos nomes indicam os códigos dos grupos
var arAbas = new Array();
arAbas[0] = new stAba('td_opcao1','vfGrupo1');
arAbas[1] = new stAba('td_opcao2','vfGrupo2');
arAbas[2] = new stAba('td_opcao3','vfGrupo3');
var CC_LOCAL_BASE = window.location.toString().replace("#","");
var nome_abas = new Array();
nome_abas[0] = 'td_opcao1';
nome_abas[1] = 'td_opcao2';
nome_abas[2] = 'td_opcao3';

function AlternarAbas(menu,conteudo) {
	for (i=0;i<arAbas.length;i++) {	 		
		c = document.getElementById(arAbas[i].conteudo);
		
		if (c != null ) {						
			document.getElementById(nome_abas[i]+"Direita").src = CC_LOCAL_BASE+"apoio/img/bkg_bt_08.gif";
			document.getElementById(nome_abas[i]+"Interna").background = CC_LOCAL_BASE+"apoio/img/bkg_bt_09.gif";
			document.getElementById(nome_abas[i]+"Esquerda").src = CC_LOCAL_BASE+"apoio/img/bkg_bt_11.gif";			
			c.style.display = 'none';
		}
		
	}
	c = document.getElementById(conteudo);
	
	if (c != null ) {
		document.getElementById(menu+"Direita").src = CC_LOCAL_BASE+"apoio/img/bkg_bt_03.gif";
		document.getElementById(menu+"Interna").background = CC_LOCAL_BASE+"apoio/img/bkg_bt_04.gif";
		document.getElementById(menu+"Esquerda").src = CC_LOCAL_BASE+"apoio/img/bkg_bt_06.gif";
		c.style.display = '';
	} else {
		document.getElementById(menu+"Direita").src = CC_LOCAL_BASE+"apoio/img/bkg_bt_03.gif";
		document.getElementById(menu+"Interna").background = CC_LOCAL_BASE+"apoio/img/bkg_bt_04.gif";
		document.getElementById(menu+"Esquerda").src = CC_LOCAL_BASE+"apoio/img/bkg_bt_06.gif";
	}
}

function validaNumero(pega, tipo) // faz verificação de número
{
	retorno = true;
	if ( tipo=="m" && qde_chars(pega, ",")>0 && qde_chars(pega, ".")>0 )
		retorno = false;
	else if ( qde_chars(pega, ",")>1 || qde_chars(pega, ".")>1 )
		retorno = false;
	else
	{
		if (tipo=="m")
			tipo="f";

		for (w=0; w<pega.length; w++)
			{
			ponto=0;
			if ( (pega.substring(w,w+1) < '0') || (pega.substring(w,w+1) > '9') )
				{
				if (tipo == 'f' && (pega.substring(w,w+1)=="." || pega.substring(w,w+1)=="," || pega.substring(0,1)=="-") && ponto==0)
					{ponto=1;}
				else
				retorno = false;
				}
			}
	}
	
	return retorno;
}

function verificaTemAnexo(paJson){
	for(var i=0;i < paJson.length;i++){
		$('#jqAnexo_'+paJson[i].anx_anexo).html('Sim');
		if($('#jqAtivo_'+paJson[i].anx_anexo).html().indexOf('Ativo') != -1 ){
			$('#jqPublicado_'+paJson[i].anx_anexo).html('Sim');
		}
	}
}


function executaAjaxJquery(paCaminhoAjax, paForm){
	var param = getParam(paForm)
	
	vmRetorno = $.ajax( { type: 'GET'
											, url: paCaminhoAjax
											, data: param
											, dataType: 'text'
											, async: false
											, cache: false
											}).responseText;

	$('#resultadoAcao').html(vmRetorno);
	/*alert(vmRetorno);*/
	$('#janela').dialog('close');
	$('#janela').dialog('close');
	$('#janela').dialog('close');
}
