// 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;
	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 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) 
	{
		//Job 362-0-07 - Nro: 16216 - Formulário de cadastro de imobiliária
		if (pcgc.length == 18)  {
			pcgc = pcgc.toString().replace( ".", "" );
			pcgc = pcgc.toString().replace( ".", "" );
			pcgc = pcgc.toString().replace( "/", "" );
			pcgc = pcgc.toString().replace( "-", "" );
			sim=true;
		} else {
			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;
	}
	
	// comentei o for abaixo para não ser in serido no numero os pontos separando as milhares, pq os pontos estavam dando 
	// problema para efetuar calculos (soma,subtração,divisão...).
	/*
	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,x;
	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 { // 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) 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){
  document.getElementById('hint').style.display = 'block';
  el = document.getElementById(id);
  //el.onmouseout=escondeHint;
  el.onmousemove = acompanhaMouse;
  ajxHint(caminho,"conteudo",local);  
}

function escondeHint(e){
  document.getElementById('hint').style.display = 'none';
  document.getElementById('hint').innerHTML = "";
}

function acompanhaMouse(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+20)+"px";
document.getElementById("hint").style.left=(posx-30)+"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 = "";
}