// 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 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.Width - 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.Width-50) < paLar || (screen.availHeight-50) < paAlt)
	{
		winX = 10;
		winY = 10;
		paLar = screen.Width-50;
		paAlt = screen.availHeight-50;
	}
	else
	{
		winX = (screen.Width - 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, atributo;
	if ((screen.Width-50) < paLar || (screen.availHeight-50) < paAlt)
	{
		winX = 10;
		winY = 10;
		paLar = screen.Width-50;
		paAlt = screen.availHeight-50;
	}
	else
	{
		winX = (screen.Width - 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 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 validaCNPJ(paCnpj)
{
	if (paCnpj.length != 14 || !numeros_diferentes(paCnpj)){
		return false;
	}else{
		m2 = 2;
		soma1 = 0;
		soma2 = 0;
		for (i=11;i>=0;i--){
			val = eval(paCnpj.charAt(i));
			m1 = m2;
			if (m2<9) 
				m2 = m2+1;
			else
				m2 = 2;
			soma1 = soma1 + (val * m1);
			soma2 = soma2 + (val * m2);
		}

		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;
		
		if ((d1==paCnpj.charAt(12)) && (d2==paCnpj.charAt(13)))
			return true; 
		else
			return false;
	}
}

function CNPJ(paStr){
	var er=/^\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}$/;
	if(er.test(paStr))
		return validaCNPJ(paStr.substr(0,2)+paStr.substr(3,3)+paStr.substr(7,3)+paStr.substr(11,4)+paStr.substr(16,2));
	else
		return false;
}


function validaCPF ( 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 CPF(paStr){
	var er=/^\d{3}\.\d{3}\.\d{3}-\d{2}$/;
	if(er.test(paStr))		
		return validaCPF(paStr.substr(0,3)+paStr.substr(4,3)+paStr.substr(8,3)+paStr.substr(12,2));
	else
		return false;
}

function CEP(paStr){
	var er=/^\d{5}-\d{3}$/;
	if(er.test(paStr))
		return true;
	else
		return false;
}



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 && hora.length!=5))
	{
		retorno = false;
	}
	else
	{
		hor = hora.substring(0,2);
		se1 = hora.substring(2,3);
		min = hora.substring(3,5);
		
		if((hor<00 || hor>23) || (se1!=":") || (min<00 || min>59))
		{
			retorno = false;
		}
		
		if(hora.length==8)
		{
			se2 = hora.substring(5,6);
			seg = hora.substring(6,8);
			
			if((se2!=":") || (seg<00 || seg>59))
			{
				retorno = false;
			}
		}
	}
	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 valida_email(paCampo) // verifica a validade do e-mail
{
	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 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 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;
		}
	}
}

 //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;
      }*/
      
      if(document.all) { // Internet Explorer
        nTecla = evtKeyPress.keyCode; }
      else { // 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( ":", "" );
      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) == "/") || (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) 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 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 mostraHintClassico(id,caminho,texto){
  document.getElementById('hint').style.display = 'block';
  el = document.getElementById(id);
  el.onmouseout=escondeHint;
  el.onmousemove = acompanhaMouse;
  ajxHint(caminho,"hint");  
}

function mostraHintDinamico(id,caminho,local,admin){
	document.getElementById('hint').style.display = 'block';
	// document.getElementById('hint').style.top = '100px';
	el = document.getElementById(id);
	//el.onmouseout=escondeHint;
	if (admin){
		el.onmousemove = acompanhaMouseAdmin;
	}else{
		el.onmousemove = acompanhaMouseSite;
	}
	document.getElementById("hint").style.left=-500;
	ajxHint(caminho,"conteudo",local);  
}

function escondeHint(e){
  document.getElementById('hint').style.display = 'none';
  document.getElementById('hint').innerHTML = "";
}

function acompanhaMouseSite(e){
  var posx=0,posy=0;
if(e==null) e=window.event;
if(e.pageX || e.pageY){
	posx=e.pageX; posy=e.pageY;
	}
else if(e.clientX || e.clientY){

	if(document.documentElement.scrollTop){
		posx=e.clientX+document.documentElement.scrollLeft;
		posy=e.clientY+document.documentElement.scrollTop;
		}
	else{
		posx=e.clientX+document.body.scrollLeft;
		posy=e.clientY+document.body.scrollTop;			
		}
	}
if(posy-450>190){
	posy=posy-450;
}else{
	posy=190;
}
if(posx-50>400){
	posx=400;
}else{
	posx=posx-50;
}
document.getElementById("hint").style.top=posy+"px";
document.getElementById("hint").style.left=posx+"px";
//document.getElementById("hint").style.left=(posx-100)+"px";
  
}

function acompanhaMouseAdmin(e){
  var posx=0,posy=0;
if(e==null) e=window.event;
if(e.pageX || e.pageY){
	posx=e.pageX; posy=e.pageY;
	}
else if(e.clientX || e.clientY){

	if(document.documentElement.scrollTop){
		posx=e.clientX+document.documentElement.scrollLeft;
		posy=e.clientY+document.documentElement.scrollTop;
		}
	else{
		posx=e.clientX+document.body.scrollLeft;
		posy=e.clientY+document.body.scrollTop;			
		}
	}

document.getElementById("hint").style.top=(posy-100)+"px";
document.getElementById("hint").style.left=100+"px";
  
}

function ajxHint(paCaminho,tipo,local){
	var exibeResultado = document.getElementById('hint'); // div que exibirá o resultado da busca.
	if(tipo == "conteudo"){
	  carrega("hint",local,'');
	}
	var ajax = openAjax(); // Inicia o Ajax.
	ajax.open("GET", paCaminho , true); // Envia o termo da busca como uma querystring, nos possibilitando o filtro na busca.
	
	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) {
				var resultado = ajax.responseText; // Coloca o resultado (da busca) retornado pelo Ajax nessa variável (var resultado).
				exibeResultado.innerHTML = resultado;
				//extraiScript(resultado);
			} else {
				exibeResultado.innerHTML = "Erro no componente AJAX.";
			}
		}
	}
	ajax.send(null);
}

function prepara(id){
  el = document.getElementById(id);
  el.onmouseout=escondeHint;
  el.onmousemove = acompanhaMouse;
}

//fecha hint
function fecha(){
  document.getElementById('hint').innerHTML = "";
}

function encode64(input) {
   var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);
   
   return output;
}

function getParam (paForm)
{
	var form		= document.getElementById(paForm);
	var vtForm     	= form.getElementsByTagName('input');
	var vtTextArea 	= form.getElementsByTagName('textarea');
	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)
				{
				  param = param + "&"+vtForm[i].name+"="+vtForm[i].value;
				}
			}
			else if (vtForm[i].type == 'checkbox')
			{
				if(vtForm[i].checked)
				{
					  param = param + "&"+vtForm[i].name+"="+vtForm[i].value;
				}
			}
			else
			{
				param = param + "&"+vtForm[i].name+"="+vtForm[i].value;
			}
		}
	}
	
	for( var p=0; p<vtTextArea.length;p++ ) 
	{
		param = param + "&"+vtTextArea[p].name+"="+vtTextArea[p].value;
	}
	
	var vtForm = form.getElementsByTagName('select');
	
	for(var i=0;i<vtForm.length;i++)
	{
		if(vtForm[i].id != "")
		{
	  		param = param + "&"+vtForm[i].id+"="+vtForm[i].value;
		}
	}
	return param;
}

function carrega(paDiv,local) 
{
    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(document.getElementById(paDiv))
    {
    	document.getElementById(paDiv).innerHTML = tbody.innerHTML;
    }
}

function ajxGenerico(paResultado, paCaminho, paForm, local)
{
	
	var exibeResultado = document.getElementById(paResultado); // div que exibirá o resultado da busca.
	var ajax = openAjax(); // Inicia o Ajax.
		
	if(paForm != "")
	{
		var param = getParam(paForm);
		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");	
	}
	else
	{
		var param = null;
	  	ajax.open("GET", paCaminho , true);
	}
    
	ajax.onreadystatechange = function()
	{
		if(ajax.readyState == 1)
		{ // Quando estiver carregando, exibe: carregando...
			exibeResultado.style.display = 'block';
			carrega(paResultado,local);
		}
		if(ajax.readyState == 4)
		{ // Quando estiver tudo pronto.
			
			if(ajax.status == 200)
			{
				var resultado = ajax.responseText; // Coloca o resultado (da busca) retornado pelo Ajax nessa variável (var resultado).
				exibeResultado.innerHTML = resultado;
				extraiScript(resultado);
			} 
			else 
			{
				exibeResultado.innerHTML = "Erro no componente AJAX.";
			}
		}
	}
	ajax.send(param);
}

/*function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5) && (document.body.filters))
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }   
}
window.attachEvent("onload", correctPNG);*/

function botaoNovo(paTitulo,paUrl)
{
	var vmA = document.createElement("A");
	
	//seta o link
	vmA.setAttribute("href",paUrl);	
	//vmA.setAttribute("target","_blank");	

	vmA.className = 'link_acao';	
	
	//pega o html do link
	vmA.innerHTML = paTitulo;
document.getElementById("idxBotao").innerHTML="";
document.getElementById("idxBotao").appendChild(vmA);



}

function limiteTexto(textarea, maxChars)
{
	if(typeof(textarea.onkeypress.arguments[0]) != 'undefined')
		var keyCode = textarea.onkeypress.arguments[0].keyCode;
	else
	{
		if(document.selection.createRange().text.length != 0) return true;
		var keyCode = event.keyCode;
	}

	var allowedChars = new Array(8, 37, 38, 39, 40, 46);	//Backspace, delete and arrow keys
	for(var x=0; x<allowedChars.length; x++) if(allowedChars[x] == keyCode) return true;

	if(textarea.value.length < maxChars) return true;

	return false;
}
