var popUp; 
var oldRowClass;
var isNav4, isNav, isIE;
if (parseInt(navigator.appVersion.charAt(0)) >= 4) {
  isNav = (navigator.appName=="Netscape") ? true : false;
  isIE = (navigator.appName.indexOf("Microsoft") != -1) ? true : false;
}
if (navigator.appName=="Netscape") {
	isNav4 = (parseInt(navigator.appVersion.charAt(0))==4);
}

function tirarZerosEsquerda(STR){

  var sAux='';
  var i=0;
  STR=new String(STR);

  while (i < STR.length ){
    if ((STR.charAt(i)!='.') && (STR.charAt(i)!=',')){
	  sAux += STR.charAt(i);
    }
	i++;
  }


  STR = new String(sAux);
  sAux = '';
  i=0;

  while (i < STR.length ){
    if (STR.charAt(i) != '0'){
      sAux = STR.substring(i,STR.length)
	  i = STR.length;
	}
    i++;
  }

  return  sAux;
}


if (document.images) 
{
	imgSelectOff = new Image();
	imgSelectOff.src = "imagens/controles/selectOff.gif";
	
	imgSelectOn = new Image();
	imgSelectOn.src = "imagens/controles/selectOn.gif";

	imgCalendarOn = new Image();
	imgCalendarOn.src = "imagens/controles/btn_on_cal.gif";
	
	imgCalendarDis = new Image();
	imgCalendarDis.src = "imagens/controles/btn_dis_cal.gif";
		
   imgUp = new Image();
   imgUp.src = "imagens/controles/up_new.gif";

   imgDn = new Image();
   imgDn.src = "imagens/controles/dn_new.gif";

   imgRight = new Image();
   imgRight.src = "imagens/controles/right_new.gif";

   imgNoMenu = new Image();
   imgNoMenu.src = "imagens/controles/nomenu.gif";

   imgNeutral = new Image();
   imgNeutral.src = "imagens/controles/neutral.gif";
   
   imgTrans = new Image();
   imgTrans.src = "imagens/geral/trans_pixel.gif";
     
   imgPlus = new Image();
   imgPlus.src = "imagens/controles/plus.gif";
   imgMinus = new Image();
   imgMinus.src = "imagens/controles/minus.gif";
   imgProgbar = new Image();
   imgProgbar.src = "imagens/controles/progbar.gif";
   imgClose = new Image();
   imgClose.src ="imagens/controles/close.gif";
   imgCloseOver = new Image();
   imgCloseOver="imagens/controles/close_over.gif";
   imgCloseDown= new Image();
   imgCloseDown="imagens/controles/close_down.gif";

   imgPositivo = new Image();
   imgPositivo.src = "imagens/controles/positivo.gif";

   imgNegativo = new Image();
   imgNegativo.src = "imagens/controles/negativo.gif";
}

	var theobj;

	var sOpenMenuID = "";

	var iChunk = 0;
	var iChunkStep = 10;
	var iChunkDelay = 20;
	var lastid = -1;

	var sMenuPos = "right";   // values: "right", "below"
	var sMenuStyle = "diagonal";	// values: "down", "across", "diagonal"


	function DoCombo(sOpenMenuID,textBox) 
	{
		var			eSrc = window.event.srcElement;
		var         i, j;

		//window.event.cancelBubble = true;
						

			if ("object" == typeof(document.all[sOpenMenuID])) 
			{
				var eMenu = document.all[sOpenMenuID];
				if( eMenu.style.visibility != "visible")
				{
					var max;
					var length;
					document.getElementById(textBox).className = 'TextoComboBranco';
					iChunk = iChunkStep;

					// ----------------------------------------------------------
					// Get the offset of the parent TR and TABLE for positioning the Menu
					// ----------------------------------------------------------

					var eTR;
					var eTABLE = eSrc.parentElement.parentElement.parentElement.parentElement;//imgMenuTitle2;
					eTR = eTABLE.children(0);

									

					// ----------------------------------------------------------
					// Set the right and top offsets based on sMenuPos
					// ----------------------------------------------------------

					if ("right" == sMenuPos) 
					{
	/*					eMenu.style.left = eTABLE.offsetLeft + eSrc.width - 2;
						eMenu.style.top = eTABLE.offsetTop  + eTR.offsetTop;
	*/
						eMenu.style.left = eTABLE.offsetLeft;// + (eSrc.width / 2);
						eMenu.style.top = 0;//eTABLE.offsetTop;
					}
					else 
					{
						eMenu.style.left = eTABLE.offsetLeft + 26;
						eMenu.style.top = eTABLE.offsetTop + eTR.offsetTop + eSrc.height;
					}

					// ----------------------------------------------------------
					// Zero out the Menu size and start the ShowMenu process
					// ----------------------------------------------------------
									
					eMenu.style.clip = "rect(0 0 0 0)";
					eMenu.style.visibility = "visible";
							
					// compute the maximum length of the menu strings		
					return window.setTimeout("ShowMenu(" + eMenu.id + ")", iChunkDelay);
				}
				else
				{
					eMenu.style.visibility = "hidden";
					document.getElementById(textBox).className = 'TextoComboNormal';
				}
				
			}
	}

	function DoMenu(sOpenMenuID) 
	{
		var			eSrc = window.event.srcElement;
		var         i, j;

		//window.event.cancelBubble = true;
						

			if ("object" == typeof(document.all[sOpenMenuID])) 
			{
				var eMenu = document.all[sOpenMenuID];
				if( eMenu.style.visibility != "visible")
				{
					var max;
					var length;
					
					iChunk = iChunkStep;

					// ----------------------------------------------------------
					// Get the offset of the parent TR and TABLE for positioning the Menu
					// ----------------------------------------------------------

					var eTR;
					var eTABLE = eSrc.parentElement.parentElement.parentElement.parentElement;//imgMenuTitle2;
					eTR = eTABLE.children(0);

									

					// ----------------------------------------------------------
					// Set the right and top offsets based on sMenuPos
					// ----------------------------------------------------------

					if ("right" == sMenuPos) 
					{
	/*					eMenu.style.left = eTABLE.offsetLeft + eSrc.width - 2;
						eMenu.style.top = eTABLE.offsetTop  + eTR.offsetTop;
	*/
						eMenu.style.left = eTABLE.offsetLeft + (eSrc.width / 2);
						eMenu.style.top = eTABLE.offsetTop;
					}
					else 
					{
						eMenu.style.left = eTABLE.offsetLeft + 26;
						eMenu.style.top = eTABLE.offsetTop + eTR.offsetTop + eSrc.height;
					}

					// ----------------------------------------------------------
					// Zero out the Menu size and start the ShowMenu process
					// ----------------------------------------------------------
									
					eMenu.style.clip = "rect(0 0 0 0)";
					eMenu.style.visibility = "visible";
							
					// compute the maximum length of the menu strings		
					return window.setTimeout("ShowMenu(" + eMenu.id + ")", iChunkDelay);
				}
				else
				{
					eMenu.style.visibility = "hidden";
				}
			}
	}

	// ----------------------------------------------------------
	// Function which returns the appropriate menu diplay animation
	// ----------------------------------------------------------

	function GetShowStyle() {
		if ("down" == sMenuStyle) return "rect(0 100% " + iChunk + "% 0)";
		if ("across" == sMenuStyle) return "rect(0 " + iChunk + "% 100% 0)";
		if ("diagonal" == sMenuStyle) return "rect(0 " + iChunk + "% " + iChunk + "% 0)";
		else return "rect(0 100% " + iChunk + "% 0)";
	}

	// ----------------------------------------------------------
	// Function which incrementally displays Menu in appropriate style
	// ----------------------------------------------------------

	function ShowMenu(eMenu) {
		eMenu.style.clip = GetShowStyle();
		if (100 >= iChunk) {
			window.setTimeout("ShowMenu(" + eMenu.id + ")", iChunkDelay);
		}
		iChunk += iChunkStep;
	}

function timer(sec,sOpenMenu) {
	seconds=parseInt(sec)
	if(seconds>0) {
		seconds--
		timerID=setTimeout("timer(seconds,'" + sOpenMenu +  "')",1000)
	}else{
		CloseMenu(sOpenMenu)
	}
}

function CloseMenu(sOpenMenuID)
{
	var eMenu = document.all[sOpenMenuID];
	eMenu.style.visibility="hidden";
}
function Calcular() {

	var data1 = document.forms[0].txtDPrevistaDATA.value;
	var data2 = document.forms[0].txtDVencimento.value;	 
	var laterdate = stringtodate(data1);
	var earlierdate = stringtodate(data2);

    var difference = laterdate.getTime() - earlierdate.getTime();

    var daysDifference = Math.floor(difference/1000/60/60/24);
    difference -= daysDifference*1000*60*60*24
    var hoursDifference = Math.floor(difference/1000/60/60);
    difference -= hoursDifference*1000*60*60
    var minutesDifference = Math.floor(difference/1000/60);
    difference -= minutesDifference*1000*60
    var secondsDifference = Math.floor(difference/1000);
	
	var valor1 = parseFloat(document.forms[0].txtTJuros.value.replace(",",".")) / 100
	var valor2 = valor1 * parseFloat(document.forms[0].ValCalculo.value)
	document.forms[0].lblJCalculado.value = 'R$ ';
    document.forms[0].lblJCalculado.value += daysDifference * valor2 + parseFloat(document.forms[0].ValCalculo.value);
	
    
}

function SelectAllGridCheckboxes(gridid){

var theBox=document.getElementById('__chkgrd_' + gridid +'_ALL')
xState=theBox.checked;	

	elm=theBox.form.getElementsByTagName('INPUT');
	for(i=0;i<elm.length;i++)
	{
	
	
	if(elm[i].type=="checkbox" && elm[i].id!=theBox.id  && (elm[i].id.indexOf(gridid) > 0) && elm[i].checked!=xState)
		{
		elm[i].click();
		}
	}
}

function SetDate(formName, id, newDate, postBack)
{
	eval('var theform = document.' + formName + ';');
	popUp.close();
	theform.elements[id].value = newDate;
	if (postBack)
		__doPostBack(id,'');
}		
function VerTextoCombo(idText, idDivMenu)
{
	var			eSrc = window.event.srcElement;
	var			eText = document.getElementById(idText);
	eText.value = eSrc.parentElement.innerText;
	eText.className = 'TextoComboNormal';
	CloseMenu(idDivMenu)
}
function toggle_div(div_id) 
{
if (document.getElementById(div_id).style.display == 'none')
{
		document.getElementById('imgDIV_' + div_id).src = 'imagens/controles/minus.gif';
		document.getElementById(div_id).style.display = 'block';
	
	}
	else
	{
		document.getElementById('imgDIV_' + div_id).src = 'imagens/controles/plus.gif';
	   	document.getElementById(div_id).style.display = 'none';
	 }
		
}

function toggle_div_form(div_id) 
{
if (document.getElementById(div_id).style.display == 'none')
{
		document.getElementById(div_id).src = 'imagens/controles/up_new.gif';
		document.getElementById(div_id).style.display = 'block';
	
	}
	else
	{
		document.getElementById(div_id).src = 'imagens/controles/dn_new.gif';
	   	document.getElementById(div_id).style.display = 'none';
	 }
		
}

function AbreGridXML(div_id, xmlfile, titulo, tampagina, where)
{
	var url = "ResultGridXML.aspx?titulo=" + titulo + "&XMLFile=" + xmlfile + "&tamPagina=" + tampagina + "&sqlWhere=" + URLEncode(where);
	if (document.getElementById(div_id).style.display == 'none')
	{
		document.getElementById(div_id).style.display = 'block';
		document.getElementById(div_id).innerHTML = "<IMG SRC='imagens/controles/progbar.gif'><br>Carregando...";
	}
	var func = 'CarregaDivXML("' + url  + '", "' + div_id + '")';
	window.setTimeout(func, 150);
}

function VerCHKTreeView(chk_id, div_id){
	var theBox=document.getElementById(chk_id);
	
	if( !theBox.checked )
	{ 
		var theDIV = document.getElementById(div_id);
		xState=false;
		//var idestruturaitemx = div_id.substring(3);
		if (theDIV)
		{
			theDIV.style.display = 'none';
			
			// bug
			document.getElementById('img'+ div_id).src = 'imagens/controles/plus.gif';
			elm=theDIV.getElementsByTagName('INPUT');
			//tam = idestruturaitemx.length;
			
			for(i=0;i<elm.length;i++)
			{
				
				
				if(elm[i].type=="checkbox" && elm[i].checked!=xState)
					{
					elm[i].click();
					}
			}		
		}
	}
	else
	{
		var id_pai = chk_id.substring(0,chk_id.lastIndexOf("_")); 
		var id_avo = id_pai.substring(0,id_pai.lastIndexOf("_")); 
		var chkPai=document.getElementById(id_pai);
		var chkAvo=document.getElementById(id_avo);
		if( chkPai )
			if ( ! chkPai.checked )
				chkPai.click();
				
		if( chkAvo )
			if ( ! chkAvo.checked )
				chkAvo.click();
		
	}
}

function toggle_div_tree(idestruturaitemx, nestrutura, nordem, ultimonivel) 
{
	if (document.getElementById('DIV' + idestruturaitemx).style.display == 'none')
	{
		
		document.getElementById('img'+ idestruturaitemx).src = 'imagens/controles/minus.gif';
		document.getElementById('DIV' + idestruturaitemx).style.display = 'block';
		if (document.getElementById('DIV' + idestruturaitemx).parentElement.parentElement.previousSibling.firstChild.nextSibling.firstChild.checked)
			document.getElementById('DIV' + idestruturaitemx).parentElement.parentElement.previousSibling.firstChild.nextSibling.firstChild.click();

		var func = 'CarregaDivXML("NoEstrutura.aspx?IDESTRUTURAITEMXPAI=' + idestruturaitemx +  '&NESTRUTURA=' + nestrutura +'&NORDEM=' + nordem + '&ULTIMONIVEL=' + ultimonivel + '", "' + idestruturaitemx + '")';
		window.setTimeout(func, 150);
		
	}
	else
	{
		document.getElementById('img'+ idestruturaitemx).src = 'imagens/controles/plus.gif';
	   	document.getElementById('DIV' + idestruturaitemx).style.display = 'none';
	 }
			
}
function CarregaDivXML(url,div_id)
{

	if (document.getElementById('DIV' + div_id).innerHTML.substring(0,3) == '<IM')
	{
		var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		xmlhttp.open("GET", url, false);
		xmlhttp.send("");
		var rs = xmlhttp.responseText;
		
		document.getElementById('DIV' + div_id).innerHTML = rs;
	}

}
function URLEncode(plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" + ch + "' cannot be encoded using standard URL encoding.\n" +
				        "(URL encoding only supports 8-bit characters.)\n" +
						"A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	
	return encoded;
};

				
// FUNCAO PARA FUNCIONALIDADES DO SCROLLBAR IMPROVISADO
// fscroll (NOME DO DIV, DIRECAO, VELOCIDADE, LOOP)

function fscroll (DivId, Vdir, Vvel, Vloop) {
	
	Vloop = true;
	Vdirecao = null;
	Vvelocidade = 10;
	Vsincronismo = null;
	Vdiv = null;
						
	if (document.getElementById)
	{
		var Vpagina = eval("document.getElementById('" + DivId + "').style");
	}

	Vdirecao = Vdir;
	Vvelocidade = parseInt(Vvel);
	Vdiv = DivId;
	var Vpos_y = parseInt(Vpagina.top);
	
	if (Vloop == true){
		
		if (Vdirecao == "baixo"){
			Vpagina.top = (Vpos_y - (Vvelocidade));}
		else{				
	
			if (Vdirecao == "cima" && Vpos_y < 50){
				Vpagina.top = (Vpos_y + (Vvelocidade));}
			else{
	
				if (Vdirecao == "top"){Vpagina.top = 0;}
			}
		}
		Vsincronismo = setTimeout("fscroll(Vdiv, Vdirecao, Vvelocidade)", 1);
	}
}

// FUNCAO PARA PARAR O MOVIMENTO QUE O SCROLLBAR ESTA EXECUTANDO
function fscrollStop() {

	Vloop = false;
	clearTimeout(Vsincronismo);
	
}
		
function stringtodate(arg) 
{ 
	var comps;
	
	// Agora está fixo... mas devemos verificar na localização...
	window.dateformat="DD/MM/YYYY";
	var month, day, year;
	var datetime = arg.split(" ");
	var d = datetime[0];
	if (d.indexOf("/") != -1) 
	{ comps = d.split("/");
		if (comps.length == 2) 
		{	month = parseInt(comps[0],10)-1;
			day = 1;
 			year = parseInt(comps[1],10);
		}
		else if (window.dateformat == "DD/MM/YYYY") 
		{ 
			day = parseInt(comps[0],10);
			month = parseInt(comps[1],10)-1;
			year = parseInt(comps[2],10);
		}
		else 
		{ 
			month = parseInt(comps[0],10)-1;
			day = parseInt(comps[1],10);
			year = parseInt(comps[2],10);
		}
	}
	else if (d.indexOf(".") != -1) 
	{ 
		comps = d.split(".");
		if (comps.length == 2) 
		{ 
			day = 1;
			month = parseInt(comps[0],10);
			year = parseInt(comps[1],10)-1;
		}
		else 
		{
			day = parseInt(comps[0],10);
			month = parseInt(comps[1],10)-1;
			year = parseInt(comps[2],10);
		}
	}
	else if (d.indexOf("-") != -1) 
	{ 
		comps = d.split("-");
		var ms = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";
		if (comps.length == 2) 
		{ 
			day = 1;
			month = parseInt(comps[0],10);
			year = ms.indexOf(comps[1].toUpperCase())/3;
		}
		else 
		{ 
			day = parseInt(comps[0],10);
			month = ms.indexOf(comps[1].toUpperCase())/3;
			year = parseInt(comps[2],10);
		}
	}
	 
	var result;
	var t = datetime[1];
	if (t != null) 
	{ 
		comps = t.split(":");
		var hour = parseInt(comps[0],10);
		var min = parseInt(comps[1],10);
		var sec = (comps[2] != null ? parseInt(comps[2],10) : 0);
		if (datetime[2].toLowerCase() == "pm") 
			hour += 12;
		result = new Date(year,month,day,hour,min,sec);
	}
	else 
		result = new Date(year,month,day);
		
	if (year < 50) 
		nlSetFullYear(r, year+2000);
	else if (year < 100) 
		nlSetFullYear(r, year+1900);

	return result;
}

function AtivaTab(id)
{
	
	for(i=1;i<5;i++)
	{
		tab = document.getElementById('HP___tab_ctl' + i);
		if(tab)
			if( i == id )
				tab.className='tab';
			else
				if( tab.className == 'tab' )
					tab.className = 'backtab';
		
		
	}
}

function AtivaTab(prefixo, id)
{
	
	for(i=1;i<5;i++)
	{
		tab = document.getElementById(prefixo + i);
		if(tab)
			if( i == id )
				tab.className='tab';
			else
				if( tab.className == 'tab' )
					tab.className = 'backtab';
		
		
	}
}


function PopupErro(icone,msgErro)

{
	window.open('Msgbox.aspx?img=' + icone + "&erro=" + msgErro ,'Mensagem_de_Erro','width=280,height=140,left=200,top=250');
	return true;
}
 

function MsgStatus(mensagem)
{
	try
	{
		if (parent.parent.frames("status"))
		{
			if(mensagem == "")
			{
				parent.parent.frames("status").document.all.progress.style.display = 'none';
			}
			else
			{
				parent.parent.frames("status").document.all.progress.style.display = 'block';
			}
			parent.parent.frames("status").document.all.msg.innerText = mensagem;
			
		}
	}
	catch (e)
	{
		// Ignora
	}	
}

function HiLightRow(row)
{
	var chk = false;
	if( row.className == 'gridover' )
	{	
		if( row.firstChild.firstChild.type=="checkbox" )
		{
			chk = row.firstChild.firstChild.checked;
		}
		if (chk != true)
		{		
			row.className = oldRowClass;
		}
	}
	else
	{
		oldRowClass = row.className;
		row.className = 'gridover';					
	}
	
}

function GoURL(row)
{
	var url = row.firstChild.firstChild.href;
	location.href = url;
	row.firstChild.firstChild.click();
}

function SelectRow(row)
{
	row.firstChild.firstChild.click();
}






/*Variável global para controlar quando vamos executar a 
 função "ValidaControle" se for 1 executamos...*/

var resp;
//Verifica se os controles são válidos....se os mesmos não forem, 
//faremos um contorno sobre eles...  
function VerificaControle()
{
	var span = document.forms[0].getElementsByTagName("SPAN")
	var valido;
	var controle;
	var retorno = true;

	for (i=0;i<span.length;i++)
	{	
		var texto = span[i].outerHTML;
		
		valido  = texto.substring(texto.indexOf('isvalid'));
		controle = texto.substring(texto.indexOf('controltovalidate'));
						
		controle = retiraLixo(controle);
		valido = retiraLixo(valido);
		
		if (valido == 'false')
		{
			AlteraCorBorda(controle,false);
			retorno = false;
		}
					
	}
		
		return retorno;
}

/*Verifica se foi inserido algum texto no controle.....
Se o parametro "obrigatorio for igual a false, ele volta a cor 
do controle...*/

function ValidaControle(idControle,obrigatorio)
{
	if (resp != '1')
	{
	var text = document.forms[0].getElementsByTagName("INPUT")
	
		for (i=0;i<text.length;i++)
			{
				if (obrigatorio == true)
				{
				if (text[i].id == idControle && text[i].value == '') 
					AlteraCorBorda(idControle,false);
					else
					    {
						if (text[i].id == idControle)
							AlteraCorBorda(idControle,true);
						}
				}
				else
					{
						var campo = text[i].id;
						var campoatual;
						if (idControle.indexOf("_") >0)
							campoatual = campo;
							else
							campoatual = campo.substring(campo.indexOf("_")+1);
						
						if (campoatual == idControle)
							AlteraCorBorda(text[i].id,true);
					}
			
			}
			
	}
	else
		resp = 0;
}
				
	
//Retira infomações que não são nescessárias.....
	function retiraLixo(texto)
	{
		
		var strTexto; 
		
		strTexto = texto.substring(texto.indexOf("\"") + 1);
		strTexto = strTexto.substring(0,strTexto.indexOf("\""));
		
	   return strTexto;
	}

	
//Função para verificar se o conteúdo dos campos são diferentes entre eles
function SenhaDif(val,campo) 
{
	var text = val.id.split('_')

	var texto1 = document.getElementById(text[1]).value;
	var texto2 = document.getElementById(text[2]).value;
	
	
	if (texto1 == texto2) 
		{
		AlteraCorBorda(val.id,true,true);
		}
		else {
		campo.IsValid = false;
		AlteraCorBorda(val.id,false,true);
		}
		
		resp = 1;
	}

//Altera a cor da borda do TextBox
function AlteraCorBorda(id,valid,SplitText)
{
	var i;
	var campo; 
	var color;

	if (valid != true) color='red'; else color='#727771';
	
if (SplitText == true)
{
	if (id.indexOf("_") > 0)
		{i = 1;}
	else {i = 0;}
	
	campo = id.split('_');

	while (i < campo.length)
	{
		
		document.getElementById(campo[i]).style.borderColor = color;
		i++;
	}
}
else
	{
		if (id.indexOf("_cv") > 0)
			campo = id.substring(0,id.indexOf("_cv"));
			else
			campo = id;
			document.getElementById(campo).style.borderColor = color;
	}
}


function fValidaData(val,campo)
{

var a= campo.Value;
var chk = 0;
var maxDay = 0;
var mascara = document.getElementById('masc').value;	
var dd = 0;
var mm = 0;
var yyyy = 0;
var arrData,arrMascara;
var carSplit,carSplitMasc;

		if (mascara.indexOf("/") > -1)
				carSplitMasc = "/";				
			else if (mascara.indexOf(".") > -1)
				carSplitMasc = ".";
			else if (mascara.indexOf("-") > -1)
				carSplitMasc = "-";
					
arrMascara = mascara.split(carSplitMasc);

			
			if (a.indexOf("/") > -1)
				carSplit = "/";				
			else if (a.indexOf(".") > -1)
				carSplit = ".";
			else if (a.indexOf("-") > -1)
				carSplit = "-";
		
if (a.indexOf(carSplit) > -1)
{

arrData = a.split(carSplit);					

	for(i=0;i<arrMascara.length;i++)
		{
			if(arrMascara[i].indexOf("D") > -1)
					dd = arrData[i];
				else if(arrMascara[i].indexOf("M") > -1)
					mm = arrData[i];
				else if(arrMascara[i].indexOf("Y") > -1)
					yyyy = arrData[i];
		}
}
	
maxDay = max_day(mm,yyyy);
	if((dd <= 0) || (dd > maxDay))
	{ chk = 1;}
	else if((mm <=0) || (mm > 12))
	{ chk = 1;}
	else if(yyyy <= 0)
	{ chk = 1; }
	else if(a.length >10)
	{ chk = 1; }
	
	if(chk ==1)
	{
		campo.IsValid = false;
		AlteraCorBorda(val.id,false)
		resp = 1;
		return false;
	}
	else 
	{ 
		AlteraCorBorda(val.id,true)
	
		var strNomeObj = val.id.substring(0,val.id.indexOf("_cv"));
		var strValorAlterado;
	switch(carSplit)
	{
		case "/":
		strValorAlterado = a.replace(/[/]/g,carSplitMasc);
		break;
		case "-":
		strValorAlterado = a.replace(/-/g,carSplitMasc);
		break;
		case ".":
		strValorAlterado = a.replace(/[.]/g,carSplitMasc);
		break;
	}
	
		document.getElementById(strNomeObj).value  = strValorAlterado;
		return true; 
	}
}

function max_day(mn,yr)
{
	var mDay;
	if ((mn == 4) || (mn == 6) || (mn == 11))
	{ mDay = 30; }
	else if (mn == 2)
	{ mDay = isLeapYear(yr) ? 29 : 28; }
	else
	{ mDay = 31; }
	return mDay;
}

function isLeapYear(yr)
{
	if (yr % 2 == 0)
	return true; 
	return false;
}


function SelectAllSubCheckboxes(chk_id,div_id,chk_idPai)
{
	var theBox=document.getElementById(chk_id);
	
		// Adicionar palavra idchave... no id da div... 
		// nos ids dos check boxes... incluir informação nivel...
		// manter um array... com os nomes das chaves...
		// baseado na informação do nivel.... nv_000_idchave_xxxxxxx
		var theDIV = document.getElementById(div_id);
		var theBoxPai = document.getElementById(chk_idPai)
			if (theBoxPai != null)
			{
				theBoxPai.checked = true;
				theBoxPai.click();
			}
			
	if( theBox.checked )
	{ 
		if (theDIV != null)
		{
			var pos = theDIV.id.indexOf('idchave_') + 8;
			var idChave = theDIV.id.substring(pos, theDIV.id.length);
		
			// melhor passar como parametro o nome base do checkbox...
			
			xState=false;
			
			if (theDIV.style.display != 'none')
			{
				theDIV.style.display = 'none';
				//document.getElementById('img'+ idestruturaitemx).src = 'imagens/controles/plus.gif';
				elm=theDIV.getElementsByTagName('INPUT');
				//tam = idestruturaitemx.length;
				
				for(i=0;i<elm.length;i++)
				{
					//if(elm[i].type=="checkbox" && (elm[i].name.substring(9,9+tam) == idestruturaitemx) && elm[i].checked!=xState)
					if(elm[i].type=="checkbox" && elm[i].checked!=xState)
						{
						elm[i].click();
						}
				}
			
			}
		}
	}
}

//Função que coloca as escolhas do TreeView no Textbox quando o mesmo 
// for do tipo CheckBox
	
function PreencheTextCombo(objCheck,desc,textbox)
	{
	try
	{
		var ck = document.getElementById(objCheck);
		var objtextbox = document.getElementById(textbox);

		if (ck.checked)
		{
			if (objtextbox.value == ' ' || objtextbox.value == '')
				objtextbox.value = desc;
			else
				objtextbox.value += desc;
		}
		else
		{
			objtextbox.value = objtextbox.value.replace(desc,'');
			//objtextbox.value = objtextbox.value.replace(desc.replace(';','') + ';','')			
			//objtextbox.value = objtextbox.value.replace(desc.replace(';',''),'')
			
		}
					
		objtextbox.title = objtextbox.value;
		
	}
	catch (e)
	{
		//ignora
	}
	}
	
	
function Mascara2(formato,objeto){
	//TELEFONE 2
	campo = eval (objeto);
	campo.value = campo.value.replace('-','')
    if(formato=='TELEFONE2'){
		separador = '-';
		if(campo.value.length == 7){
				campo.value = campo.value.substring(0,3) + "-" + campo.value.substring(3,7);	
		}else if(campo.value.length == 8){
				campo.value = campo.value.substring(0,4) + "-" + campo.value.substring(4,8);	
		}
  }
}
function Mascara(formato,objeto){
  campo = eval (objeto);
  var keypress = window.event.keyCode;
  
  
  if((keypress >= 48) && (keypress <= 57)) {
  
	// PLACA
    
	
    // CEP
    if (formato=='CEP'){
      separador = '-';	
      conjunto1 = 5;
      if (campo.value.length == conjunto1) {
        campo.value = campo.value + separador;
      }
    }

    // MM/YYYY
    if (formato=='MM/YYYY'){
      separador = '/';	
      conjunto1 = 2;
      if (campo.value.length == 0) {
        if(keypress > 49)  {
          return false;
        }
      }
      if (campo.value.length == conjunto1){
        campo.value = campo.value + separador;
      }
    }


    // DD/MM/YYYY
    if (formato=='DD/MM/YYYY'){
      separador = '/';	
      conjunto1 = 2;
      conjunto2 = 5;

      if (campo.value.length == 0) {
        if(keypress > 51)  {
          return false;
        }
      }
      if (campo.value.length == 2) {
        if(keypress > 51)  {
          return false;
        }
      }
      if (campo.value.length == conjunto1){
        campo.value = campo.value + separador;
      }
      if (campo.value.length == conjunto2){
        campo.value = campo.value + separador;
      }

    }


    // DD/MM/YYYY hh:mm
    if (formato=='DD/MM/YYYY hh:mm'){
      separador1 = '/';	
      separador2 = ' ';	
      separador3 = ':';	
      conjunto1 = 2;
      conjunto2 = 5;
      conjunto3 = 10;
      conjunto4 = 13;
      if (campo.value.length == 0) {
        if(keypress > 51)  {
          return false;
        }
      }
      if (campo.value.length == 3) {
        if(keypress > 49)  {
          return false;
        }
      }      
      if (campo.value.length == 11) {
        if(keypress > 50)  {
          return false;
        }
      }      
      if (campo.value.length == 14) {
        if(keypress > 53)  {
          return false;
        }
      }
      if (campo.value.length == conjunto1){
        campo.value = campo.value + separador1;
      }
      if (campo.value.length == conjunto2){
        campo.value = campo.value + separador1;
      }
      if (campo.value.length == conjunto3){
        campo.value = campo.value + separador2;
      }
      if (campo.value.length == conjunto4){
        campo.value = campo.value + separador3;
      }
      
    }

    // DD/MM/YYYY hh:mm:ss
    if (formato=='DD/MM/YYYY hh:mm:ss'){
      separador1 = '/';	
      separador2 = ' ';	
      separador3 = ':';	
      conjunto1 = 2;
      conjunto2 = 5;
      conjunto3 = 10;
      conjunto4 = 13;
      conjunto5 = 16;
      if (campo.value.length == 0) {
        if(keypress > 51)  {
          return false;
        }
      }
      if ((campo.value.length == 3) || (campo.value.length == 11)) {
        if(keypress > 50)  {
          return false;
        }
      }      
      if ((campo.value.length == 14) || (campo.value.length == 17)) {
        if(keypress > 53)  {
          return false;
        }
      }
      if (campo.value.length == conjunto1){
        campo.value = campo.value + separador1;
      }
      if (campo.value.length == conjunto2){
        campo.value = campo.value + separador1;
      }
      if (campo.value.length == conjunto3){
        campo.value = campo.value + separador2;
      }
      if (campo.value.length == conjunto4){
        campo.value = campo.value + separador3;
      }
      if (campo.value.length == conjunto5){
        campo.value = campo.value + separador3;
      }
    }


    // hh:mm
    if (formato=='hh:mm'){
      separador = ':';	
      conjunto1 = 2;
      if (campo.value.length == 0) {
        if(keypress > 51)  {
          return false;
        }
      }
      if (campo.value.length == 3) {
        if(keypress > 53)  {
          return false;
        }
      }
      if (campo.value.length == conjunto1){
        campo.value = campo.value + separador;
      }
    }
 
    // hh:mm:ss
    if (formato=='hh:mm:ss'){
      separador = ':';	
      conjunto1 = 2;
      conjunto2 = 5;
      if (campo.value.length == 0){
        if(keypress > 50)  {
          return false;
        }
      }
      if ((campo.value.length == 2) || (campo.value.length == 5)) {
        if(keypress > 53)  {
          return false;
        }
      }
      if (campo.value.length == conjunto1){
        campo.value = campo.value + separador;
      }
      if (campo.value.length == conjunto2){
        campo.value = campo.value + separador;
      }
    }

    // TELEFONE
    if (formato=='TELEFONE'){
      separador = '-';	
      conjunto1 = 4;
      if (campo.value.length == conjunto1){
        campo.value = campo.value + separador;
      } 
    }
    
    
    
  // DDDTELEFONE
    if (formato=='DDDTELEFONE'){
	  separador1 = '(';	
      conjunto1 = 0;
      separador2 = ')';	
      conjunto2 = 3;
      separador3 = '-';	
      conjunto3 = 8;
      if (campo.value.length == conjunto1){
        campo.value = separador1 + campo.value;
      } 
      if (campo.value.length == conjunto2){
        campo.value = campo.value + separador2;
      } 
      if (campo.value.length == conjunto3){
        campo.value = campo.value + separador3;
      } 

    }

  // DDD
    if (formato=='DDD'){
	  separador1 = '(';	
      conjunto1 = 0;
      separador2 = ')';	
      conjunto2 = 3;
      if (campo.value.length == conjunto1){
        campo.value = separador1 + campo.value;
      } 
      if (campo.value.length == conjunto2){
        campo.value = campo.value + separador2;
      } 
    }

//CPF
    if (formato=='CPF'){
      separador1 = '.';	
      separador2 = '-';	
      if (campo.value.length == 3){
        campo.value = campo.value + separador1;
      } 

      if (campo.value.length == 7){
        campo.value = campo.value + separador1;
      } 

      if (campo.value.length == 11){
        campo.value = campo.value + separador2;
      } 
    }

    if (formato=='CNPJ'){
      separador1 = '.';	
      separador2 = '/';	
      separador3 = '-';	
      
      if (campo.value.length == 2){
        campo.value = campo.value + separador1;
      } 

      if (campo.value.length == 6){
        campo.value = campo.value + separador1;
      } 

      if (campo.value.length == 10){
        campo.value = campo.value + separador2;
      } 
      if (campo.value.length == 15){
        campo.value = campo.value + separador3;
      } 
    }



  }
  else {
	window.event.keyCode=null;
	return false;
	
  }
}


function VerificaModulo11(valor,mensagem) {

	while (valor.indexOf('.') > -1)
		{
			valor = valor.replace('.','')		
		}
        valor = valor.replace('-','')
		valor = valor.replace('/','') 
				
	primeiro=valor.substr(1,1);
	var falso=true;
	var size=valor.length;
	var proximo;
	for (i=2; i<size-1; ++i){
	  	proximo=(valor.substr(i,1));
	  	if (primeiro!=proximo) {
		falso=false
		}
	}
	if (falso){
	if (mensagem != null)
		alert(mensagem);
	return false;
	}
		
	if(modulo(valor.substring(0,valor.length - 2)) + "" + modulo(valor.substring(0,valor.length - 1)) != valor.substring(valor.length - 2,valor.length)) {
		if (mensagem != null)
			alert(mensagem);
		return false;
	}
	return true
}		

function modulo(str) 
{
	soma=0;
    ind=2;
 	for(pos=str.length-1;pos>-1;pos=pos-1) 
 	{
   		soma = soma + (parseInt(str.charAt(pos)) * ind);
   		ind++;
		if(str.length>11)
			if(ind>9) 
			ind=2;
 	}
    resto = soma - (Math.floor(soma / 11) * 11);
    if(resto < 2)
     	return 0;
	else 
    	return 11 - resto;
}	

function formatarOnKeyDown(OBJ,tammax,teclapres, usadec){
  var decimal,inteiro;
  var i,count;
  STR = new String(OBJ.value);

  inteiro='';

  if (isIE) {
	if (STR.length <= OBJ.maxLength ){
	
	if (usadec == 1)
	{
		if (STR.indexOf(",") == -1)
		{
			if (OBJ.maxLength  <= 6)
			STR = STR.substring(0,OBJ.maxLength - 1);
			else
			STR = STR.substring(0,OBJ.maxLength - 2);
		}
			
	}
	else
	{
		if (STR.indexOf(".") == -1 )
		{
			STR = STR.substring(0,OBJ.maxLength - 2);	
		}
	}
	
	  STR = tirarZerosEsquerda(STR); //ESTA FUNCAO TIRA TAMBEM PONTO E VIRGULA
if (!(event.keyCode > 35 && event.keyCode < 41)) 		
{
		if (((event.keyCode > 47) && (event.keyCode < 59)) || ((event.keyCode > 95) && (event.keyCode < 106))   )
		{	  
			if (STR.length == 0){
			  inteiro  = '0';
			  if( usadec == 1 )
				decimal = '0' + STR;
			}
			else {
			  if (STR.length == 1){
			    if( usadec == 1 )
			    {
				    inteiro  = '0';
					decimal = STR;
				}
				else
					inteiro = STR;
			  }
			  else{
				if( usadec == 1 )
				{
					decimal = STR.substring(STR.length-2,STR.length);
					i=3;
				}
				else
				i=0;
			    count=0;
			    while (i<=STR.length){
			    	if (STR.length >3)
			    	{
						if (count == 3) {
					 		inteiro = '.' + inteiro;
			  				count = 0;
			  		}
			  	}
			  		
					  inteiro = STR.charAt(STR.length-i) + inteiro;
					if (inteiro != "")
			  			count++;
			  		i++;
			    }
			  }
			}

	  }
	  else{
	    if (event.keyCode == 8){

	      if (STR.length == 0){
			  //inteiro  = '0';
			  if( usadec == 1 )
				//decimal = '000';
				s=1;
			}
			else {
			  if (STR.length == 1){
			    if( usadec == 1 )
			    {
    			    inteiro  = '0';
					decimal = '00' + STR;
				}
				else
					inteiro = STR;
				
			  }
			  else {
			    if (STR.length == 2){
   		          if( usadec == 1 )
   				  {
			          inteiro  = '0';
					  decimal = '0' + STR;
				  }
				  else
					var s = 1;//inteiro = STR;
			     }
		         else{
	 			   if( usadec == 1 )
	 			   {
	 					decimal = STR.substring(STR.length-2,STR.length);
						i=3;
					}
					else
						i = 0;
				   count=0;
				 while (i<=STR.length){
					if (STR.length >3)
					{
				 		if (count == 3) {
					 		inteiro = '.' + inteiro;
			  				count = 0;
			  		}
			  	}
			  		
					  inteiro = STR.charAt(STR.length-i) + inteiro;
					if (inteiro != "") 
			  			count++;
			  		i++;
			    }
			     }
			  }
	      }
	    }
	    else {

	      if (STR.length == 1){
		 	  if( usadec == 1 )
		 	  {
  		 	    inteiro  = '0';
				decimal = '0' + STR;
			  }
			  else
				  inteiro = STR;
				
			}
			else {
			  if (STR.length == 2){
				  if( usadec == 1 )
				  {
	    		    inteiro  = '0';
					decimal = STR;
				  }
				  else
					inteiro = STR;
					
				}
				else{
				  if( usadec == 1 )
				  {
					decimal = STR.substring(STR.length-2,STR.length);
					i=3;
				  }
				  else
					i=0;
				  count=0;
				  while (i<=STR.length){
				  	
			 		if (count==3) {
					  inteiro = '.' + inteiro;
					  count = 0;
					}
				
				    inteiro = STR.charAt(STR.length-i) + inteiro;
					count++;
					i++;
				  }
				}
			}
	    }
	   }
	   
	  if (OBJ.value.length == 2) 
	  {
		if (OBJ.value.indexOf(",") != -1)
		{
			OBJ.value = OBJ.value.replace(",","");
		}
	  }

	  if (inteiro == '') {
	    inteiro = '0';
	    s=1;
	  }


	  if (usadec == 1 )
	  {
		if (decimal == '' ) {
			decimal = '00';
			s=1;
		}
		if (inteiro != "0")
			OBJ.value = inteiro+','+decimal;
		}
	  else
	  if (inteiro != "0")
		OBJ.value = inteiro;
		
	}
  }
  else
  {
	var tecla = teclapres.keyCode;
	valorSemFormato = OBJ.value;
	valorSemFormato = valorSemFormato.replace( ",", "" );
	valorSemFormato = valorSemFormato.replace( ".", "" );
	valorSemFormato = valorSemFormato.replace( ".", "" );
	valorSemFormato = valorSemFormato.replace( ".", "" );
	valorSemFormato = valorSemFormato.replace( ".", "" );
	tamanho = valorSemFormato.length;

	if (tecla == 46) {
	     OBJ.value = OBJ.value;

	}if (tamanho < tammax && tecla != 8) {
	    tamanho = valorSemFormato.length + 1;

	}if (tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ) {
	     if (tecla == 8) {
	         tamanho = tamanho - 1;
	     }

	     if (tamanho <= 2) {
	 		 OBJ.value = valorSemFormato;

	 	 }else if ((tamanho > 2) && (tamanho <= 5)) {
	 		 OBJ.value = valorSemFormato.substr(0, tamanho - 2) + ',' +
	 		               valorSemFormato.substr(tamanho - 2, tamanho);

	 	 }else if ((tamanho >= 6) && (tamanho <= 8)) {
	 	 	 OBJ.value = valorSemFormato.substr(0, tamanho - 5) + '.' +
	 	 	               valorSemFormato.substr(tamanho - 5, 3) + ',' +
	 		               valorSemFormato.substr(tamanho - 2, tamanho);

	 	 }else if ((tamanho >= 9) && (tamanho <= 11)) {
	 		 OBJ.value = valorSemFormato.substr(0, tamanho - 8) + '.' +
	 		               valorSemFormato.substr(tamanho - 8, 3) + '.' +
	 		               valorSemFormato.substr(tamanho - 5, 3) + ',' +
	 		               valorSemFormato.substr(tamanho - 2, tamanho);

	 	 }else if ((tamanho >= 12) && (tamanho <= 14)) {
	 	 	 OBJ.value = valorSemFormato.substr(0, tamanho - 11) + '.' +
	 		               valorSemFormato.substr(tamanho - 11, 3) + '.' +
	 		               valorSemFormato.substr(tamanho - 8, 3)  + '.' +
	 		               valorSemFormato.substr(tamanho - 5, 3)  + ',' +
	 		               valorSemFormato.substr(tamanho - 2, tamanho);

	 	 }else if ((tamanho >= 15) && (tamanho <= 17)) {
	 	 	 OBJ.value = valorSemFormato.substr(0, tamanho - 14) + '.' +
	 		               valorSemFormato.substr(tamanho - 14, 3) + '.' +
	 		               valorSemFormato.substr(tamanho - 11, 3) + '.' +
	 		               valorSemFormato.substr(tamanho - 8, 3)  + '.' +
	 		               valorSemFormato.substr(tamanho - 5, 3)  + ',' +
	 		               valorSemFormato.substr(tamanho - 2, tamanho);
	    }
	}
  }  
  
  if (!(event.keyCode > 35 && event.keyCode < 41))
  {
  if (!(event.keyCode > 45 && event.keyCode < 59))
  {
	if(!(event.keyCode > 95 && event.keyCode < 106))
	{
		if (event.keyCode != 8 && event.keyCode != 9)
			{				
				event.keyCode=null;				
				return false;
			}
	}
	
  }
   }      
}
}

function formatarOnKeyUp(OBJ){
  var decimal,inteiro;
  var i,count;
  STR = new String(OBJ.value);
  STR = tirarZerosEsquerda(STR);
  inteiro='';
  if (isIE) {
		if (STR.length == 1){
			//  inteiro  = '0';
			//  decimal = '0' + STR;
			}
			else {
			  if (STR.length == 2){
				  //inteiro  = '0';
				  //decimal = STR;
				}
				else{
				  decimal = STR.substring(STR.length-2,STR.length);
				  i=3;
				  count=0;
				  while (i<=STR.length){
			 		if (count==3) {
					  inteiro = '.' + inteiro;
					  count = 0;
					}
				    inteiro = STR.charAt(STR.length-i) + inteiro;
					count++;
					i++;
				  }
				}
			}


		if (inteiro == '') {
		  //inteiro = '0';
		}

		if (decimal == '') {
		  //decimal = '00';
		}
		OBJ.value = inteiro+','+decimal;
  }
  else
  {

	if (navigator.appName=="Netscape")
	{
		var versao = navigator.userAgent;
		versao=versao.toString();
		menorVersao = versao.search("/6.0");
		if (menorVersao>-1)
		{
			var isNS6="sim";
		}
	}

	if(isNS6=="sim")
		OBJ.style.textAlign	= "left";


	if(STR=="")
		//OBJ.value = "0,00";
	if((STR.length==1 || STR.length==2 || STR.length==3) && OBJ.value.substr(0,1)=='0')
		//OBJ.value = OBJ.value.substr(1,OBJ.value.length-1);
	if((STR.length==2) && OBJ.value.substr(0,1)!='0')
		//OBJ.value = "0," + OBJ.value;
	if((STR.length==1) && OBJ.value.substr(0,1)!='0')
		//OBJ.value = "0,0" + OBJ.value;


	if(isNS6=="sim")
		OBJ.style.textAlign	= "right";

  }

}

function FormataOnKeyPress(obj)
{
if(event.keyCode==13)
  {event.keyCode=9;}
  else{
if (!(event.keyCode > 36 && event.keyCode < 41)) 		
{
if (!(event.keyCode > 45 && event.keyCode < 59))
  {
	if(!(event.keyCode > 95 && event.keyCode < 106))
	{
		if (event.keyCode != 8 && event.keyCode != 9)
			{
				event.keyCode=null;
				return false;
			}
	}
	
  }
  }
}
}


function Mascara(formato,objeto){
  campo = eval (objeto);
  var keypress = window.event.keyCode;
  
  if (formato=='PLACA'){      
		separador2 = '-';		
		if (campo.value.length <= 2){						
			if( (keypress > 47) && (keypress < 58) ){			
				window.event.keyCode=null;
				return false;		
			}
		}else{
			if(!(((keypress > 47)&&(keypress < 58)))) {					
				window.event.keyCode=null;
				return false;				
			}			
			
			//if (campo.value.length == 3){
			//	campo.value += separador2;							
			//}			
		}
		return;
	} 
  
  if((keypress >= 48) && (keypress <= 57)) {
  
	// PLACA
    
	
	/////FormatA Registro RNTC 01-09-01/0000001-3
	if (formato=='RNTRC'){
      separador2 = '/';	
      separador3 = '-';	
      
      if (campo.value.length == 2){
        campo.value = campo.value + separador3;
      } 

      if (campo.value.length == 5){
        campo.value = campo.value + separador3;
      } 

      if (campo.value.length == 8){
        campo.value = campo.value + separador2;
      } 
      if (campo.value.length == 16){
        campo.value = campo.value + separador3;
      } 
    }

/////FormatA Registro TRO 00001/YYYY
	if (formato=='TRO'){
      separador2 = '/';	
           
      
      if (campo.value.length == 5){
        campo.value = campo.value + separador2;
      } 

     }
     
    // CEP
    if (formato=='CEP'){
      separador = '-';	
      conjunto1 = 5;
      if (campo.value.length == conjunto1) {
        campo.value = campo.value + separador;
      }
    }

      //CEP-RNTRC
	if (formato=='CEP-RNTRC'){
      separador1 = '.';	
      separador2 = '/';	
      separador3 = '-';	
      
      if (campo.value.length == 2){
        campo.value = campo.value + separador1;
      } 

      if (campo.value.length == 6){
        campo.value = campo.value + separador2;
      } 
      
    }

    // MM/YYYY
    if (formato=='MM/YYYY'){
      separador = '/';	
      conjunto1 = 2;
      if (campo.value.length == 0) {
        if(keypress > 49)  {
          return false;
        }
      }
      if (campo.value.length == conjunto1){
        campo.value = campo.value + separador;
      }
    }


    // DD/MM/YYYY
    if (formato=='DD/MM/YYYY'){
      separador = '/';	
      conjunto1 = 2;
      conjunto2 = 5;

      if (campo.value.length == 0) {
        if(keypress > 51)  {
          return false;
        }
      }
      if (campo.value.length == 2) {
        if(keypress > 51)  {
          return false;
        }
      }
      if (campo.value.length == conjunto1){
        campo.value = campo.value + separador;
      }
      if (campo.value.length == conjunto2){
        campo.value = campo.value + separador;
      }

    }


    // DD/MM/YYYY hh:mm
    if (formato=='DD/MM/YYYY hh:mm'){
      separador1 = '/';	
      separador2 = ' ';	
      separador3 = ':';	
      conjunto1 = 2;
      conjunto2 = 5;
      conjunto3 = 10;
      conjunto4 = 13;
      if (campo.value.length == 0) {
        if(keypress > 51)  {
          return false;
        }
      }
      if (campo.value.length == 3) {
        if(keypress > 49)  {
          return false;
        }
      }      
      if (campo.value.length == 11) {
        if(keypress > 50)  {
          return false;
        }
      }      
      if (campo.value.length == 14) {
        if(keypress > 53)  {
          return false;
        }
      }
      if (campo.value.length == conjunto1){
        campo.value = campo.value + separador1;
      }
      if (campo.value.length == conjunto2){
        campo.value = campo.value + separador1;
      }
      if (campo.value.length == conjunto3){
        campo.value = campo.value + separador2;
      }
      if (campo.value.length == conjunto4){
        campo.value = campo.value + separador3;
      }
      
    }

    // DD/MM/YYYY hh:mm:ss
    if (formato=='DD/MM/YYYY hh:mm:ss'){
      separador1 = '/';	
      separador2 = ' ';	
      separador3 = ':';	
      conjunto1 = 2;
      conjunto2 = 5;
      conjunto3 = 10;
      conjunto4 = 13;
      conjunto5 = 16;
      if (campo.value.length == 0) {
        if(keypress > 51)  {
          return false;
        }
      }
      if ((campo.value.length == 3) || (campo.value.length == 11)) {
        if(keypress > 50)  {
          return false;
        }
      }      
      if ((campo.value.length == 14) || (campo.value.length == 17)) {
        if(keypress > 53)  {
          return false;
        }
      }
      if (campo.value.length == conjunto1){
        campo.value = campo.value + separador1;
      }
      if (campo.value.length == conjunto2){
        campo.value = campo.value + separador1;
      }
      if (campo.value.length == conjunto3){
        campo.value = campo.value + separador2;
      }
      if (campo.value.length == conjunto4){
        campo.value = campo.value + separador3;
      }
      if (campo.value.length == conjunto5){
        campo.value = campo.value + separador3;
      }
    }


    // hh:mm
    if (formato=='hh:mm'){
      separador = ':';	
      conjunto1 = 2;
      if (campo.value.length == 0) {
        if(keypress > 51)  {
          return false;
        }
      }
      if (campo.value.length == 3) {
        if(keypress > 53)  {
          return false;
        }
      }
      if (campo.value.length == conjunto1){
        campo.value = campo.value + separador;
      }
    }
 
    // hh:mm:ss
    if (formato=='hh:mm:ss'){
      separador = ':';	
      conjunto1 = 2;
      conjunto2 = 5;
      if (campo.value.length == 0){
        if(keypress > 50)  {
          return false;
        }
      }
      if ((campo.value.length == 2) || (campo.value.length == 5)) {
        if(keypress > 53)  {
          return false;
        }
      }
      if (campo.value.length == conjunto1){
        campo.value = campo.value + separador;
      }
      if (campo.value.length == conjunto2){
        campo.value = campo.value + separador;
      }
    }

    // TELEFONE
    if (formato=='TELEFONE'){
      separador = '-';	
      conjunto1 = 4;
      if (campo.value.length == conjunto1){
        campo.value = campo.value + separador;
      } 
    }
    
    // TELEFONE-RNTRC
    if (formato=='TELEFONE-RNTRC'){
      separador = '-';	
      conjunto1 = 4;
      
      if (campo.value.length == 3){
        campo.value = campo.value + separador;
      } 
      
      if (campo.value.length == 8){
        campo.value = campo.value + separador;
      } 
    }

  // DDDTELEFONE
    if (formato=='DDDTELEFONE'){
	  separador1 = '(';	
      conjunto1 = 0;
      separador2 = ')';	
      conjunto2 = 3;
      separador3 = '-';	
      conjunto3 = 8;
      if (campo.value.length == conjunto1){
        campo.value = separador1 + campo.value;
      } 
      if (campo.value.length == conjunto2){
        campo.value = campo.value + separador2;
      } 
      if (campo.value.length == conjunto3){
        campo.value = campo.value + separador3;
      } 

    }

	// DDD
    if (formato=='DDD'){
	  separador1 = '(';	
      conjunto1 = 0;
      separador2 = ')';	
      conjunto2 = 3;
      if (campo.value.length == conjunto1){
        campo.value = separador1 + campo.value;
      } 
      if (campo.value.length == conjunto2){
        campo.value = campo.value + separador2;
      } 
    }

	//CPF
    if (formato=='CPF'){
      separador1 = '.';	
      separador2 = '-';	
      if (campo.value.length == 3){
        campo.value = campo.value + separador1;
      } 

      if (campo.value.length == 7){
        campo.value = campo.value + separador1;
      } 

      if (campo.value.length == 11){
        campo.value = campo.value + separador2;
      } 
    }

    if (formato=='CNPJ'){
      separador1 = '.';	
      separador2 = '/';	
      separador3 = '-';	
      
      if (campo.value.length == 2){
        campo.value = campo.value + separador1;
      } 

      if (campo.value.length == 6){
        campo.value = campo.value + separador1;
      } 

      if (campo.value.length == 10){
        campo.value = campo.value + separador2;
      } 
      if (campo.value.length == 15){
        campo.value = campo.value + separador3;
      } 
    }



  }
  else {
	window.event.keyCode=null;
	return false;
	
  }
}

function EscondeDiv(obj)
{
	if(obj.checked == true)
	{				
		div1.style.display = '';
        div2.style.display = 'none';
        //Limpar();
	}else{
		div1.style.display = 'none';
        div2.style.display = '';
        //Limpar()
	}   
}




function MontaTela(obj)
{
	document.all.txtCpfCnpj.value = '';
	
	if(obj.checked == false)
	{
		lblNome.innerText = '*Razão Social / Nome da Empresa:';
		lblCpf.innerText = '*CGC / CNPJ:';		
		document.all.txtCpfCnpj.outerHTML = document.all.txtCpfCnpj.outerHTML.replace('CPF','CNPJ');
		document.all.ibtEnviar.outerHTML = document.all.ibtEnviar.outerHTML.replace('CPF','CNPJ');
		document.all.txtCpfCnpj.maxLength=18;
		document.all.hdPessoa.value = 'J';		
	}else{
		lblNome.innerText = '*Nome Completo:';
		lblCpf.innerText = '*CPF:';		
		document.all.txtCpfCnpj.outerHTML = document.all.txtCpfCnpj.outerHTML.replace('CNPJ','CPF');
		document.all.ibtEnviar.outerHTML = document.all.ibtEnviar.outerHTML.replace('CNPJ','CPF');
		document.all.txtCpfCnpj.maxLength=14;
		document.all.hdPessoa.value = 'F';
	}
}


function Limpar()
{
	var icampos = document.all.length;
	for(i=0; i < icampos; i++)
	{
		if (document.all.item[i].type == 'text')
			document.all.item[i].value = '';
		else			
			document.all.item[i].innerText = '';
	}
}

var gskn;
//document.onmousemove = get_mouse;
function pop_detalhe_status(msg) 
{

var nav = (document.layers); 
var iex = (document.all);
var skn = (nav) ? document.all.topdeck : topdeck.style;
gskn = skn;
if (nav) document.captureEvents(Event.MOUSEMOVE);

  var content= "<TABLE WIDTH=300 BORDER=0 CELLPADDING=2 CELLSPACING=0 class=form2><TR><TD width=239 align=center class=tbl-vermelho>Detalhes</TD><TD width=51 align=center class=tbl-vermelho><a href='javascript:kill();' title='Fechar detalhes'; class=tbl-vermelho>Fechar</a></TD></TR><TR><TD colspan=2 class=fundo-cinza3>" + msg + "</TD></TR></TABLE>"
  if (nav) 
  { 
   get_mouse(nav,document.onmousemove,skn);
    skn.document.write(content); 
   skn.document.close();
   skn.display.style = "none";
  }
    else if (iex) 
  {
   get_mouse(nav,document.onmousemove,skn);
   document.all("topdeck").innerHTML = content;
   skn.visibility = "visible";  
  }
}
function get_mouse(e,nav,skn)
{
	var x = (nav) ? e.pageX : event.x+document.body.scrollLeft; 
	var y = (nav) ? e.pageY : event.y+document.body.scrollTop;
	skn.left = x - 60;
  skn.top  = y+10;
}
function kill() 
{
  gskn.visibility = "hidden";
}
function mostradetalhestatus()
{
	//não faz nada
}




function DoCombo1(sOpenMenuID) 
	{
		var			eSrc = window.event.srcElement;
		var         i, j;

		//window.event.cancelBubble = true;
						

			if ("object" == typeof(document.all[sOpenMenuID])) 
			{
				var eMenu = document.all[sOpenMenuID];
				if( eMenu.style.visibility != "visible")
				{
					var max;
					var length;
					
					iChunk = iChunkStep;

					// ----------------------------------------------------------
					// Get the offset of the parent TR and TABLE for positioning the Menu
					// ----------------------------------------------------------

					var eTR;
					var eTABLE = eSrc.parentElement.parentElement.parentElement.parentElement;//imgMenuTitle2;
					eTR = eTABLE.children(0);

									

					// ----------------------------------------------------------
					// Set the right and top offsets based on sMenuPos
					// ----------------------------------------------------------

					if ("right" == sMenuPos) 
					{
	/*					eMenu.style.left = eTABLE.offsetLeft + eSrc.width - 2;
						eMenu.style.top = eTABLE.offsetTop  + eTR.offsetTop;
	*/
						eMenu.style.left = eTABLE.offsetLeft;// + (eSrc.width / 2);
						eMenu.style.top = 0;//eTABLE.offsetTop;
					}
					else 
					{
						eMenu.style.left = eTABLE.offsetLeft + 26;
						eMenu.style.top = eTABLE.offsetTop + eTR.offsetTop + eSrc.height;
					}

					// ----------------------------------------------------------
					// Zero out the Menu size and start the ShowMenu process
					// ----------------------------------------------------------
									
					eMenu.style.clip = "rect(0 0 0 0)";
					eMenu.style.visibility = "visible";
							
					// compute the maximum length of the menu strings		
					return window.setTimeout("ShowMenu(" + eMenu.id + ")", iChunkDelay);
				}
				else
				{
					eMenu.style.visibility = "hidden";
					
				}
				
			}
	}

function MudaCampo(obj)
{
	if(event.keyCode==13) event.keyCode=9;
}

function RetiraCaracter()
{
	if (event.keyCode == 60 || event.keyCode == 62 || event.keyCode == 37)
		 event.keyCode = null;
}


if (document.layers) {navigator.family = "nn4"}
if (document.all) {navigator.family = "ie4"}
if (window.navigator.userAgent.toLowerCase().match("gecko")) {navigator.family = "gecko"}

descarray = new Array(
"Os Fundos Municipais dos Direitos da Criança e do Adolescente são contas bancárias, abertas em bancos oficiais, administradas pelos Conselhos Municipais dos Direitos da Criança e Adolescente, instituídas pelo Estatuto da Criança e do Adolescente. Esses fundos podem receber recursos de diversas fontes, inclusive de contribuintes Pessoa Física e Pessoa Jurídica, sendo que estes recursos são utilização na promoção e atendimento aos direitos da criança e adolescente.",
"O Conselho Municipal dos Direitos da Criança e Adolescente é um órgão paritário (50% representantes do poder público e 50% representantes eleitos pela sociedade civil). Suas atribuições são: elaboração do diagnóstico local da situação social da criança e adolescente e do plano de ação, com a efetiva aplicação dos recursos; registro das entidades e inscrição dos projetos; edição de resoluções normativas que atendam às necessidades de defesa e promoção dos direitos da criança e adolescente e gestão do Fundo dos Direitos da Criança e Adolescente.",
"O IDI foi elaborado pela Unicef em 2001 e leva em consideração indicadores como: percentual de crianças com mães com escolaridade precária; crianças com pais com escolaridade precária; coberturas de vacinação (sarampo e DTP), entre outros. Obs.: cerca de 1.300 municípios brasileiros (24% do total) possuem um IDI até 0,4, o que significa um índice de desenvolvimento infantil muito baixo.",
"O IES foi elaborado pela Unicamp em 2003 e leva em consideração indicadores como: porcentagem de chefes de família pobres no município; taxa de desemprego formal na população em idade ativa; desigualdade de renda; alfabetização de pessoas acima de 5 anos; número médio de anos de estudo do chefe de domicílio; porcentagem de jovens na população e número de homicídios.&#13;&#10;Obs.: 2.290 municípios (42% do total) possuem um IES até 0,4, o que significa um alto índice de exclusão social",
"Informe o valor do lucro líquido de sua empresa. Obs.: Não devem ser informados lucros, rendimentos ou ganhos de capital oriundos do exterior, uma vez que não são passíveis de dedução fiscal.",
"Informe o valor total dos rendimentos tributáveis no ano. Exemplos: receitas obtidas pelo títular ou dependentes, como: salário, 13º salário, aposentadoria, aluguéis, pensão alimentícia, lucro na venda de bens, ganhos obtidos com investimentos no mercado financeiro, prêmios obtidos em loterias, entre outros. Obs.: São isentos e não-tributáveis ganhos de caderneta de poupança e saque do Fundo de Garantia do Tempo de Serviço (FGTS).",
"Informe o valor recolhido de INSS pelo declarante e dependente (se houver) do ano do exercício fiscal (2004). As despesas serão integralmente dedutíveis.",
"Indique o número de dependentes. <b>O valor fixo para dedução é de R$ 1.272,00 anuais, por dependente.</b>",
"Informe os gastos com despesas médicas para tratamento próprio, de dependentes e alimentandos.  São consideradas despesas com médicos, dentistas, psicólogos, exames, hospitais, serviços de radiologia, próteses dentárias, entre outras.",
"Informe a despesa integral com pensão alimentícia. Esta dedução somente é válida para  pensões homologadas judicialmente. As despesas médicas e com instrução pagas pelo alimentante não são dedutíveis como pensão alimentícia judicial.",
"Informe a soma dos pagamentos com Previdência Privada. <b>O valor da dedução é limitado a 12% do total dos Rendimentos Tributáveis.</b> O valor excedente não poderá ser considerado como despesa dedutível.",
"Informe aqui os gastos com sua instrução. <b>O valor individual dedutível é limitado a R$1.998.00.</b>",
"Informe aqui os gastos com a instrução de seus dependentes e alimentandos (homologados judicialmente). <b>O valor individual dedutível é limitado a R$1.998.00.</b>",
"Segurados com 65 anos, completos em 2003, ou mais, podem deduzir até R$ 12.696. Segurados cuja idade de 65 anos for alcançada ao longo de 2004 poderão multiplicar o valor de R$ 1.058,00 pelo número de meses faltantes para completar o exercício de 2004. Exemplo: Segurados que completam 65 anos em agosto de 2004 podem multiplicar R$ 1.058,00 por 4 (meses), ou seja, valor informado deverá ser R$ 4.232,00.",
"Soma das despesas dedutíveis.",
"Este valor é resultado da subtração dos Rendimentos Tributáveis com o Total das despesas dedutíveis, e determina qual alíquota deve ser aplicada ao contribuinte, conforme abaixo:Base de cálculo para resultados até R$ 12.696,00 – Isento. Base de cálculo para resultados acima de R$ 12.696,00 até R$ 25.380,00 – Aplica-se alíquota de 15% e será deduzido o valor de R$ 1.904,40. Base de cálculo para resultados acima de R$ 25.380,00 – Aplica-se alíquota de 27,5% e será deduzido o valor de R$ 5.076,90",
"Este valor é resultado da aplicação da alíquota correspondente à Base de Cálculo.",
"Este resultado é equivalente a 6% do Imposto de Renda Devido, sendo o limite máximo dedutível das doações feitas aos <b>Fundos dos Direitos da Criança e do Adolescente</b>. O valor excedente será considerado como doação não dedutível. Obs.: O limite de 6% é cumulativo aos incentivos fiscais direcionados a projetos culturais e audiovisuais aprovados pelo Ministério da Cultura.",
"Este valor é resultado da subtração do IR devido com o valor do campo Doação aos Fundos dos Direitos da Criança e do Adolescente.",
"Informe o valor anual do seu Imposto de Renda Retido na Fonte.",
"Este valor é resultado da subtração do Imposto de Renda Retido na Fonte com o Resultado do IR devido após a dedução."
);

overdiv="0";

function popLayer(a){

if (navigator.family == "gecko") {pad="0"; bord="1 bordercolor=black";}
else {pad="1"; bord="0";}
desc = 	  "<table cellspacing=0 cellpadding="+pad+" border="+bord+"  bgcolor=#A6BEBE><tr><td>\n"
	+"<table cellspacing=0 cellpadding=3 border=0 width=100%><tr><td bgcolor=#FFF9D9><font size=2px face=arial>\n"
	+descarray[a]
	+"\n</td></tr></table>\n"
	+"</td></tr></table>";

if(navigator.family =="nn4") {
	document.object1.document.write(desc);
	document.object1.document.close();
	document.object1.left=x+1;
	document.object1.top=y+2;
	}
else if(navigator.family =="ie4"){
	object1.style.pixelWidth = 350;
	object1.innerHTML=desc;
	object1.style.pixelTop=document.body.scrollTop + document.body.parentElement.offsetHeight-350;
	object1.style.pixelLeft=document.body.scrollLeft + document.body.parentElement.offsetWidth-400;
	object1.style.pixelWidth = object1.firstChild.offsetWidth;
	object1.style.pixelHeight = object1.firstChild.offsetHeight;

	object1.style.pixelTop=document.body.scrollTop + AcertaPos(y, object1.offsetHeight, document.body.parentElement.offsetHeight);
	object1.style.pixelLeft=document.body.scrollLeft +AcertaPos(x, object1.offsetWidth, document.body.parentElement.offsetWidth);
}
else if(navigator.family =="gecko"){
	document.getElementById("object1").innerHTML=desc;
	document.getElementById("object1").style.left=x+1;
	document.getElementById("object1").style.top=y+2;//-5;
	
	}
	
}

function GetSelectedItem(obj, msg)
{
	var vForm = document.forms[0];
	var retorno = 0;
	
	for(i=0;i<vForm.elements.length;i++)
	{
		if (vForm.elements[i].type == 'checkbox') 
		{ 
			if(vForm.elements[i].checked)
				retorno += 1;
		} 
	}
	
	if(retorno == 0){
		alert(msg);
		return false;
	}else{
		return true;
	}		
}

function AcertaPos(coord, offset, total)
{
	if( (coord + offset + 10) > total)
		return coord - offset - 10;
	else
		return coord + 10;
}

function hideLayer(){
if (overdiv == "0") {
	if(navigator.family =="nn4") {eval(document.object1.top="-500");}
	else if(navigator.family =="ie4"){object1.innerHTML="";object1.style.pixelTop=-500;}
	else if(navigator.family =="gecko") {document.getElementById("object1").style.top="-500";}
	}
}

var isNav = (navigator.appName.indexOf("Netscape") !=-1);

function handlerMM(e){
x = (isNav) ? e.pageX : event.clientX; //+ document.body.scrollLeft;
y = (isNav) ? e.pageY : event.clientY;// + document.body.scrollTop;
}
if (isNav){document.captureEvents(Event.MOUSEMOVE);}
document.onmousemove = handlerMM;

function AbreJanela(pURL, pNome, pWidth, pHeight, pScroll)
{
	w = (screen.availwidth / 2) - (pWidth / 2);
	h = (screen.availheight / 2) - (pHeight /2);
	
	popUp = window.open(pURL, pNome,'left='+ w +', top='+ h +',toolbar=no, directories=no, location=no, status=yes, menubar=no, resizable=no, scrollbars='+ pScroll +', width='+ pWidth +', height='+ pHeight +''); 
	return false;
}

function ValidaCNPJ(_cnpj)
	{
		CNPJ = _cnpj;
		erro = new String;
		if (CNPJ.length < 18) erro += "E' necessarios preencher corretamente o numero do CNPJ! \n\n";
		if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
			if (erro.length == 0) erro += "E' necessarios preencher corretamente o numero do CNPJ! \n\n";
		}
		//substituir os caracteres que nao sao numeros
		if(document.layers && parseInt(navigator.appVersion) == 4){
			x = CNPJ.substring(0,2);
			x += CNPJ.substring(3,6);
			x += CNPJ.substring(7,10);
			x += CNPJ.substring(11,15);
			x += CNPJ.substring(16,18);
			CNPJ = x;	
		} else {
			CNPJ = CNPJ.replace(".","");
			CNPJ = CNPJ.replace(".","");
			CNPJ = CNPJ.replace("-","");
			CNPJ = CNPJ.replace("/","");
		}
		var nonNumbers = /\D/;
		if (nonNumbers.test(CNPJ)) erro += "A verificacao de CNPJ suporta apenas numeros! \n\n";	
		var a = [];
		var b = new Number;
		var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
		for (i=0; i<12; i++){
			a[i] = CNPJ.charAt(i);
			b += a[i] * c[i+1];
		}
		if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
		b = 0;
		for (y=0; y<13; y++) {
			b += (a[y] * c[y]); 
		}
		if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
		if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
			erro +="Digito verificador com problema!";
		}
		if (erro.length > 0){
			alert(erro);
			return false;
		} else {
			//alert("CNPJ valido!");
		}
		return true;
	}
	


	function Exibir(abre, fecha)
	{	
		fecha.style.display = 'none';
		abre.style.display = 'none';
		
		abre.style.display = '';
	}
	
function isDate(dateStr) {

  var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
  var matchArray = dateStr.match(datePat); // is format OK?
  var msgRet = ''

  if (matchArray == null) {
    alert('Data Inválida!');
    return false;
    
  }

  // parse date into variables
  day = matchArray[1];
  month = matchArray[3];
  year = matchArray[5];

  if (month < 1 || month > 12) { // check month range
    alert('Data Inválida (mês inválido)!');
    return false;
  }

  if (day < 1 || day > 31) {
    alert('Data Inválida (dia inválido)!');
    return false;
  }

  if ((month==4 || month==6 || month==9 || month==11) && day==31) {
    alert('Data Inválida (mes '+month+ ' vai até 30)!');
    return false;
  }

  if (month == 2) { // check for february 29th
    var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
    if (day > 29 || (day==29 && !isleap)) {
    alert('Data Inválida (fevereiro)!');
    return false
    }
  }
  return true;
}

function isDateRange(dti, dtf) {
	if(!isDate(dti) || !isDate(dtf)) {
		alert('Data Inicial ou final não é válida!');
		return false;
		}
	var di = dti.split('/');
	var df = dtf.split('/');
	if(di[0]<10){
		di[0]='0'+di[0];
		}
	if(di[1]<10) {
		di[1]='0'+di[1];
		}
	var De = new Date (di[2], Number(di[1]) - 1, di[0]);

	if(df[0]<10) {df[0]='0'+df[0];}
	if(df[1]<10) {df[1]='0'+df[1];}
	var Ate = new Date (df[2], Number(df[1]) - 1, df[0]);
	if(De>Ate) {
		alert('Data Final não pode ser menor que data inicial!');
		return false;
		}
	return true;
	}

function Dtos(data) { // tranforma a data em YYYYmmDD
	if(!isDate(data)) {
		return data; // DATA INVALIDA, DEVOLVE ELE MESMO
		}
	var d = data.split('/');
	if(d[0] < 10) {
		//d[0] = '0'+d[0];
		}
	if(d[1] < 10) {
		//d[1] = '0'+d[1];
		}
	var ymd = new String( d[2] + d[1] + d[0]);
	return ymd;
	}

function OpenCalendar(idname, postBack) {
	var URL='Calendar.aspx?formname=0&id=' + idname;
	URL += '&selected=' + document.forms[0].elements[idname].value + '&postBack=' + postBack;
	openWindowCenter(URL,'calendario','width=165, height=228');
	}
	
function isEmail(str) {  
  var supported = 0;
  if (window.RegExp) {
    var tempStr = "a";
    var tempReg = new RegExp(tempStr);
    if (tempReg.test(tempStr)) supported = 1;
  }
  if (!supported) 
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
  return (!r1.test(str) && r2.test(str));
}


function SelecionaTudo(){
	count = document.forms[0].elements.length;
		for (i=0; i < count; i++){
			if(document.forms[0].elements[i].checked == 1)
				{document.forms[0].elements[i].checked = 0;}
			else {document.forms[0].elements[i].checked = 1;}
	}
}

function SelecionaCheck(sVar){ 

	var vForm = document.forms[0];
	for(i=0;i<vForm.elements.length;i++)
	{
		if (vForm.elements[i].type == 'checkbox') 
		{ 
			vForm.elements[i].checked = sVar; 
		} 
	}
} 

function onEnter(keyCode,Evento) {
  if(!keyCode) {
   var keyCode = event.keyCode; // ? event.keyCode : event.which ? event.which : event.charCode;
   }
  if (keyCode == 13) {
   //area para disparar Evento que quiser, (botao, funcao, etc)();
   if(Evento != '') {
	eval(Evento);
	}
   return true;
   } 
  else {
   return false;
  }
 } 
 
 function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
		}
	else {
		window.onload = function() {
			oldonload();
			func();
			}
		}
	}

function addUnLoadEvent(func) {
	var oldonload = window.onunload;
	if (typeof window.onunload != 'function') {
		window.onunload = func;
		}
	else {
		window.onunload = function() {
			oldonload();
			func();
			}
		}
	}

function isNumeric(sText) {
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   }


function OpenWindowCenter(URL,winName,features) {
	openWindowCenter(URL,winName,features);
	}
function openWindowCenter(URL,winName,features) {
	var autoCloseTimeoutHandle, ontopIntervalHandle, w = 480, h = 340;  
	if(document.all || document.layers || document.getElementById) {
		w = screen.availWidth; h = screen.availHeight;
		//alert('w='+w + ' h='+h);
		}
	var param = features.split(',');
	var subpar;
	var popWidth='800'; popHeight='600';
	for(var i=0;i<param.length;i++) {
		subpar=param[i].split('=');
		if(subpar[0] == 'width') {
			popWidth=subpar[1];
			}
		if(subpar[0] == 'height') {
			popHeight=subpar[1];
			}
		}
	var leftPos = (w-popWidth)/2, topPos = (h-popHeight)/2;
	features += (features.length > 0 ? ',' : '') + 'top=' + topPos+',left='+leftPos;
	//alert('features='+features+' w='+w+' h='+h+' popWidth='+popWidth+' popHeight='+popHeight);
	popupWindow = window.open(URL,winName,features);
	if (popupWindow.opener == null) popupWindow.opener = self;    
	if (document.all || document.layers || document.getElementById) {
  		window.onbeforeunload = function() {popupWindow.close();}; 
  		}   
	}


 function ChecaCpf(pcpf)
 {
 	pcpf = pcpf.toString();
	pcpf = pcpf.replace( "/", "" );
	pcpf = pcpf.replace( "-", "" );
	pcpf = pcpf.replace( "_", "" );
	pcpf = pcpf.replace( ",", "" );
	pcpf = pcpf.replace( ".", "" );
	pcpf = pcpf.replace( " ", "" );
	pcpf = pcpf.replace( ";", "" );
	pcpf = pcpf.replace( "[", "" );
	pcpf = pcpf.replace( "{", "" );
	pcpf = pcpf.replace( "]", "" );
	pcpf = pcpf.replace( "}", "" );
	pcpf = pcpf.replace( ")", "" );
	pcpf = pcpf.replace( "(", "" );
	pcpf = pcpf.replace( ".", "" );
	pcpf = pcpf.replace( ".", "" );

 if (pcpf.length != 11) {sim=false}
 else {sim=true}

  if (sim )  // valida o primeiro digito
  {
  for (i=0;((i<=(pcpf.length-1))&& sim); i++)
  {
   val = pcpf.charAt(i)
   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)
  {
    soma = 0
    for (i=0;i<=8;i++)
    {
     val = eval(pcpf.charAt(i))
     soma = soma + (val*(i+1))
    }

    resto = soma % 11
    if (resto>9) dig = resto -10
    else  dig = resto
    if (dig != eval(pcpf.charAt(9))) { sim=false }
   else   // valida o segundo digito
    {

     soma = 0
    for (i=0;i<=7;i++)
     {
     val = eval(pcpf.charAt(i+1))
      soma = soma + (val*(i+1))
    }

     soma = soma + (dig * 9)
    resto = soma % 11
     if (resto>9) dig = resto -10
     else  dig = resto
   if (dig != eval(pcpf.charAt(10))) { sim = false }
    else sim = true
   }
   }
  }

  if (!sim) { alert("CPF Inválido!") }
  return sim;
 }
