var mydate=new Date()
var year=mydate.getYear()
if (year < 1000)
year+=1900
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()
if (daym<10)
daym="0"+daym
var dayarray=new Array("Domingo","Segunda","Terca","Quarta","Quinta","Sexta","Sabado")
var montharray=new Array("Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro")

UR_Nu = new Date;

var hh = UR_Nu.getHours();
var mm = UR_Nu.getMinutes();
var ss = UR_Nu.getSeconds();


function relogio(){ 
if (ss >= 60){ 
ss = 00; 
mm = mm + 1; 
if (mm >= 60){ 
mm = 00; 
hh = hh + 1; 
if (hh >= 24){ 
hh = 00; 
}}} 
ss = ss + 1; 
if (hh <= 9){ 
xhh = "0" + hh; 
} else { 
xhh = hh; 
} 
if (mm <= 9){ 
xmm = "0" + mm; 
} else { 
xmm = mm; 
} 
if (ss <= 9){ 
xss = "0" + ss; 
} else { 
xss = ss; 
} 

document.all("span_relogio").innerHTML = dayarray[day]+", "+daym+" de "+montharray[month]+" de "+year+" | "+xhh + ":" + xmm + ":" + xss; 
lrelogio = setTimeout("relogio()", 1000); 
} 

function calcula_Dias(data1_DDMMYYYY,data2_DDMMYYYY){

	Var_Dia1=Dia(data1_DDMMYYYY);
	Var_Mes1=Mes(data1_DDMMYYYY);
	Var_Mes1=Math.floor(Var_Mes1)-1;
	Var_Ano1=Ano(data1_DDMMYYYY);
	var data1 = new Date(Var_Ano1,Var_Mes1,Var_Dia1);
	
	Var_Dia2=Dia(data2_DDMMYYYY);
	Var_Mes2=Mes(data2_DDMMYYYY);
	Var_Mes2=Math.floor(Var_Mes2)-1;
	Var_Ano2=Ano(data2_DDMMYYYY);
	var data2 = new Date(Var_Ano2,Var_Mes2,Var_Dia2);
	
	var diferenca = data1.getTime() - data2.getTime();
	var diferenca = Math.floor(diferenca / (1000 * 60 * 60 * 24));
	
	alert('Diferença em dias entre '+data1_DDMMYYYY+' e '+data2_DDMMYYYY+' = '+diferenca);
}


function mostra(item)
{
	if (item.style.display=='none')
	{
		item.style.display='';
	}
	else
	{
		item.style.display='none';
	}
}

function calaculadesconto(vlr1,vlr2) 
{
	vlr1a = new Number(vlr1);
	vlr2a = new Number(vlr2);
	var total = new Number(vlr1a - vlr2a).toFixed(2);

	document.getElementById('vlrpagar').innerHTML = total;
}


function calaculavlrpagar(vlr1,vlr2,vlr3) 
{
	vlr1a = new Number(vlr1);
	vlr2a = new Number(vlr2);
	vlr3a = new Number(vlr3);
	var total = new Number(vlr1a + vlr2a + vlr3a).toFixed(2);

	document.getElementById('vlrpagar').innerHTML = total;
}


function idn_del(url) 
{
	if(confirm('Você deseja excluir este registro?')) 
	{
		location.href = url;
	}
}

function esc_pendencia(vlr)
{
	if (vlr=='simnao1')
	{
		div_pen1.style.display='';
		div_pen2.style.display='';
		div_pen3.style.display='';
		div_pen4.style.display='';
		div_pen5.style.display='';
		div_pen6.style.display='none';
		div_pen7.style.display='';
		document.frm_cadastro.elements['SZid_situacao'].value = 'sitnr2'
	}
	else
	{
		div_pen1.style.display='none';
		div_pen2.style.display='none';
		div_pen3.style.display='none';
		div_pen4.style.display='none';
		div_pen5.style.display='none';
		div_pen6.style.display='';
		div_pen7.style.display='none';
		document.frm_cadastro.elements['SZid_situacao'].value = 'sitnr1'
	}

}

function mostrasimounao(elemento,vlr)
{

	if (vlr=='tsn1')
	{
		document.getElementById(elemento).style.display='';
	}
	else
	{
		document.getElementById(elemento).style.display='none';
	}
}


function pedevalor(vlr)
{

	if (vlr=='ttipoprogrota1')
	{
		lnsemana.style.display='';
		lnmes.style.display='none';
		lnmes1.style.display='none';
		lnmes2.style.display='none';
	}
	else
	{
		lnsemana.style.display='none';
		lnmes.style.display='';
		lnmes1.style.display='';
		lnmes2.style.display='';
	}
}



function mostrasit(vlr)
{

		document.frm_cadastro.elements['SNid_formareceb'].value = 'RTD1016';
		document.frm_cadastro.elements['SNidendop'].value = 'tendop1';
		document.frm_cadastro.elements['SIqtde_parcelas'].value = '0';
		document.frm_cadastro.elements['SNrota1'].value = 'tendop1';
		document.frm_cadastro.elements['SAvlr'].value = '0';
		document.frm_cadastro.elements['SNhorario'].value = 'tsn2';		
		document.frm_cadastro.elements['SHentre'].value = '0';
		document.frm_cadastro.elements['SHe'].value = '0';
		document.frm_cadastro.elements['SNid_novocontato'].value = 'RTD1095';
		document.frm_cadastro.elements['SDdata'].value = '0';
		document.frm_cadastro.elements['SHhorae'].value = '07:00:00';
		document.frm_cadastro.elements['SHhoraf'].value = '18:00:00';
		document.frm_cadastro.elements['SNid_semcontato'].value = 'RTD1099';
		document.frm_cadastro.elements['SNid_motnaodoou'].value = 'RTD1092';
		document.frm_cadastro.elements['SNid_motcancelamento'].value = 'RTD1088';


	if (vlr=='RTD1176')
	{
		document.frm_cadastro.elements['SNid_formareceb'].value = '';
		document.frm_cadastro.elements['SNidendop'].value = '';
		document.frm_cadastro.elements['SIqtde_parcelas'].value = '';
		document.frm_cadastro.elements['SNrota1'].value = '';
		document.frm_cadastro.elements['SAvlr'].value = '';
		document.frm_cadastro.elements['SNhorario'].value = '0';
		document.frm_cadastro.elements['SHentre'].value = '';
		document.frm_cadastro.elements['SHe'].value = '';

		linhameses.style.display='';
		lnrecebopend.style.display='';
		lnparcelasrota.style.display='';
		vlrhorario.style.display='';
		
					lnnovocontato.style.display='';
					lnmotnovocontato.style.display='none';
								lnmotcancelamento.style.display='none';
												lnmotnaodoou.style.display='none';
															lnmotsemcontato.style.display='none';
	}
	else
	{
		lnrecebopend.style.display='none';
		lnparcelasrota.style.display='none';
		vlrhorario.style.display='none';
		linhameses.style.display='none';
		
					if (vlr=='RTD1175')
					{
						document.frm_cadastro.elements['SNid_novocontato'].value = '';
						document.frm_cadastro.elements['SDdata'].value = '';
						document.frm_cadastro.elements['SHhorae'].value = '';
						document.frm_cadastro.elements['SHhoraf'].value = '';
						lnnovocontato.style.display='';
						lnmotnovocontato.style.display='';
								lnmotcancelamento.style.display='none';
												lnmotnaodoou.style.display='none';
															lnmotsemcontato.style.display='none';
					}
					else
					{
						lnnovocontato.style.display='none';
						lnmotnovocontato.style.display='none';						
						
								if (vlr=='RTD1180')
								{
									document.frm_cadastro.elements['SNid_motcancelamento'].value = '';
									lnmotcancelamento.style.display='';
					lnnovocontato.style.display='';
												lnmotnaodoou.style.display='none';
															lnmotsemcontato.style.display='none';
								}
								else
								{
									lnmotcancelamento.style.display='none';
									
											if (vlr=='RTD1179')
											{
					lnnovocontato.style.display='';
												document.frm_cadastro.elements['SNid_motnaodoou'].value = '';
												lnmotnaodoou.style.display='';
															lnmotsemcontato.style.display='none';
											}
											else
											{
												lnmotnaodoou.style.display='none';
												
														if (vlr=='RTD1177')
														{
															document.frm_cadastro.elements['SNid_semcontato'].value = '';
					lnnovocontato.style.display='';
															lnmotsemcontato.style.display='';
														}
														else
														{
															lnmotsemcontato.style.display='none';
															
																	if (vlr=='RTD1358')
																	{
																		lnnovocontato.style.display='';
																	}
														}
											}

								}
								
					}
					
	}
	

}


function CheckAll() 
{ 
count = document.frm_cadastro.elements.length; 
for (i=0; i < count; i++) 
{ 
if (document.frm_cadastro.elements[i].name != 'chgeral')
{
	if(document.frm_cadastro.elements[i].checked == 1)  
	{ 
		document.frm_cadastro.elements[i].checked = 0; 
	} 
		else 
	{ 
		document.frm_cadastro.elements[i].checked = 1; 
	} 
}
} 
} 


function confirmaExclusao() 
{
var total = 0
var count = document.frm_cadastro.elements.length; 
for (i=0; i < count; i++) 
{ 
	if (document.frm_cadastro.elements[i].name != 'chgeral')
	{
		if(document.frm_cadastro.elements[i].checked == 1)  
		{ 
			total = 1
		} 
	}
}



	if (total > 0)
	{
		if(confirm('Você tem certeza que deseja excluir?')) 
		{
			confirmaExclusao = 1
		} else {confirmaExclusao = 0}
	}
		else
	{
		alert('Nenhum registro foi selecionado')
	}
}



function contadigitos(nome,qtde,tipo) 
{
var count = document.frm_cadastro.elements[nome].value.length; 
if (count != 0)
{
	if (count < qtde)
	{
		alert(tipo+' inválido(a), deverá conter no mínimo '+qtde+' caracteres.');	
		document.frm_cadastro.elements[nome].focus();
	}
}
}



function formatar(src, mask) 
{
  var i = src.value.length;
  var saida = mask.substring(0,1);
  var texto = mask.substring(i)
if (texto.substring(0,1) != saida) 
  {
  src.value += texto.substring(0,1);
  }
}


function validacpf(valor,nome)
{
vl1 = valor.replace('.', '');
vl2 = vl1.replace('.', '');
vl3 = vl2.replace('-', '');
resultado = isCpfCnpj(vl3)

if (resultado==true || valor=="")
{

} else {
		alert(valor + " Não é um documento válido.");
		document.frm_cadastro.elements[nome].focus();
		document.frm_cadastro.elements[nome].style.background = "red";
}
}

// Validações

var reDigits = /^\d+$/;

function doDigits(pStr,nome)
{
	if (reDigits.test(pStr)) {
		document.frm_cadastro.elements[nome].style.background = "write";		
	} else if (pStr != null && pStr != "") {
		alert(pStr + " Não é um valor inteiro válido.");
		document.frm_cadastro.elements[nome].focus();
		document.frm_cadastro.elements[nome].style.background = "red";				
	}
}

var reDecimalPt = /^[+-]?((\d+|\d{1,3}(\.\d{3})+)(\,\d*)?|\,\d+)$/;
var reDecimalEn = /^[+-]?((\d+|\d{1,3}(\,\d{3})+)(\.\d*)?|\.\d+)$/;
var reDecimal = reDecimalPt;

function doDecimal(pStr, pLang, nome)
{
	charDec = ( pLang != "En"? ",": "." );
	eval("reDecimal = reDecimal" + pLang);
	if (reDecimal.test(pStr)) {
		document.frm_cadastro.elements[nome].style.background = "write";
	} else if (pStr != null && pStr != "") {
		/*alert(pStr + " Não é um valor decimal válido.");
		document.frm_cadastro.elements[nome].focus();
		document.frm_cadastro.elements[nome].style.background = "red";*/
	}
} // doDecimal


var reEmail1 = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail2 = /^[\w-]+(\.[\w-]+)*@(([\w-]{2,63}\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail3 = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail = reEmail3;

function doEmail(pStr, pFmt, nome)
{
	eval("reEmail = reEmail" + pFmt);
	if (reEmail.test(pStr)) {
//		document.frm_cadastro.elements[nome].style.background = "write";
	} else if (pStr != null && pStr != "") {
		alert(pStr + " Não é um endreço de e-mail válido.");
		document.frm_cadastro.elements[nome].focus();
		document.frm_cadastro.elements[nome].style.background = "red";
	}
} // doEmail


var NUM_DIGITOS_CPF  = 11;
var NUM_DIGITOS_CNPJ = 14;
var NUM_DGT_CNPJ_BASE = 8;

String.prototype.lpad = function(pSize, pCharPad)
{
	var str = this;
	var dif = pSize - str.length;
	var ch = String(pCharPad).charAt(0);
	for (; dif>0; dif--) str = ch + str;
	return (str);
} //String.lpad


String.prototype.trim = function()
{
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
} //String.trim

function unformatNumber(pNum)
{
	return String(pNum).replace(/\D/g, "").replace(/^0+/, "");
} //unformatNumber

function formatCpfCnpj(pCpfCnpj, pUseSepar, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	if (pUseSepar==null) pUseSepar = true;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var numero = unformatNumber(pCpfCnpj);

	numero = numero.lpad(maxDigitos, '0');
	if (!pUseSepar) return numero;

	if (pIsCnpj)
	{
		reCnpj = /(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/;
		numero = numero.replace(reCnpj, "$1.$2.$3/$4-$5");
	}
	else
	{
		reCpf  = /(\d{3})(\d{3})(\d{3})(\d{2})$/;
		numero = numero.replace(reCpf, "$1.$2.$3-$4");
	}
	return numero;
} //formatCpfCnpj


function dvCpfCnpj(pEfetivo, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	var i, j, k, soma, dv;
	var cicloPeso = pIsCnpj? NUM_DGT_CNPJ_BASE: NUM_DIGITOS_CPF;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var calculado = formatCpfCnpj(pEfetivo, false, pIsCnpj);
	calculado = calculado.substring(2, maxDigitos);
	var result = "";

	for (j = 1; j <= 2; j++)
	{
		k = 2;
		soma = 0;
		for (i = calculado.length-1; i >= 0; i--)
		{
			soma += (calculado.charAt(i) - '0') * k;
			k = (k-1) % cicloPeso + 2;
		}
		dv = 11 - soma % 11;
		if (dv > 9) dv = 0;
		calculado += dv;
		result += dv
	}

	return result;
} //dvCpfCnpj


function isCpf(pCpf)
{
	var numero = formatCpfCnpj(pCpf, false, false);
	var base = numero.substring(0, numero.length - 2);
	var digitos = dvCpfCnpj(base, false);
	var algUnico, i;

	// Valida dígitos verificadores
	if (numero != base + digitos) return false;

	algUnico = true;
	for (i=1; i<NUM_DIGITOS_CPF; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	return (!algUnico);
} //isCpf


function isCnpj(pCnpj)
{
	var numero = formatCpfCnpj(pCnpj, false, true);
	var base = numero.substring(0, NUM_DGT_CNPJ_BASE);
	var ordem = numero.substring(NUM_DGT_CNPJ_BASE, 12);
	var digitos = dvCpfCnpj(base + ordem, true);
	var algUnico;

	// Valida dígitos verificadores
	if (numero != base + ordem + digitos) return false;

	algUnico = numero.charAt(0) != '0';
	for (i=1; i<NUM_DGT_CNPJ_BASE; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	if (algUnico) return false;

	if (ordem == "0000") return false;
	return (base == "00000000"
		|| parseInt(ordem, 10) <= 300 || base.substring(0, 3) != "000");
} 


function isCpfCnpj(pCpfCnpj)
{
	var numero = pCpfCnpj.replace(/\D/g, "");
	if (numero.length > NUM_DIGITOS_CPF)
		return isCnpj(pCpfCnpj)
	else
		return isCpf(pCpfCnpj);
} //isCpfCnpj







<!--
function abre_janela(width, height, nome, scrollbar) {
var top; var left;
top = ( (screen.height/2) - (height/2) )
left = ( (screen.width/2) - (width/2) )
window.open('',nome,'width='+width+',height='+height+',scrollbars='+scrollbar+',toolbar=no,location=no,status=no,menubar=no,resizable=no,left='+left+',top='+top);
}
//-->

function enviardados(){

for (i=0;i< document.frm_cadastro.elements.length; i++){
string = document.frm_cadastro.elements[i].name.substring(0,1);
var exibeResultado = document.getElementById("erro"+document.frm_cadastro.elements[i].name);


 if ( string=="S") 
 {
		if(document.frm_cadastro.elements[i].value=="")
		{
			document.frm_cadastro.elements[i].focus();
			document.frm_cadastro.elements[i].style.background = "orange";
			alert("O campo obrigatório "+document.frm_cadastro.elements[i].name+" não foi preenchido!");
			return false;
		}	
				
 }
} 		
return true;
}

function entrarfoco(objeto){
	document.frm_cadastro.elements[objeto].style.background = "#ffff99";
}

function sairfoco(objeto){
	var obj
	document.frm_cadastro.elements[objeto].style.background = "gainsboro";
	string = document.frm_cadastro.elements[objeto].name.substring(0,1);
	if ( string=="S")
	{
		if(document.frm_cadastro.elements[objeto].value=="")
		{
			document.frm_cadastro.elements[objeto].style.background = "#ffff99";
		}
	}
}




function semaspas(num){
	if (document.all)
		var tecla = event.keyCode;
	else if(document.layers)
		var tecla = num.which;
		if (tecla != 39)
			return true;
		else
			{
				if (tecla != 8)
					event.keyCode = 0;
				else
					return true;
			}
}




function getObj(objID)
{
    if (document.getElementById) {return document.getElementById(objID);}
    else if (document.all) {return document.all[objID];}
    else if (document.layers) {return document.layers[objID];}
}

function checkClick(e) 
{
	e?evt=e:evt=event;
	CSE=evt.target?evt.target:evt.srcElement;

}

function isChild(s,d) {
	while(s) {
		if (s==d) 
			return true;
		s=s.parentNode;
	}
	return false;
}

function Left(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function Top(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}
	
document.write('<table id="fc" style="position:absolute;border-collapse:collapse;background:#FFFFFF;border:1px solid #ABABAB;display:none" cellpadding=2>');
document.write('<tr class=text10><td style="cursor:pointer" onclick="csubm()">Anterior</td><td colspan=5 id="mns" align="center" style="font:bold 13px Arial"></td><td align="right" style="cursor:pointer" onclick="caddm()">Próximo</td></tr>');
document.write('<tr><td align=center style="background:#ABABAB;font:12px Arial">D</td><td align=center style="background:#ABABAB;font:12px Arial">S</td><td align=center style="background:#ABABAB;font:12px Arial">T</td><td align=center style="background:#ABABAB;font:12px Arial">Q</td><td align=center style="background:#ABABAB;font:12px Arial">Q</td><td align=center style="background:#ABABAB;font:12px Arial">S</td><td align=center style="background:#ABABAB;font:12px Arial">S</td></tr>');
for(var kk=1;kk<=6;kk++) {
	document.write('<tr>');
	for(var tt=1;tt<=7;tt++) {
		num=7 * (kk-1) - (-tt);
		document.write('<td id="v' + num + '" style="width:18px;height:18px">&nbsp;</td>');
	}
	document.write('</tr>');
}
document.write('<tr><td colspan=7 align=center style="background:#ABABAB;font:12px Arial"><a style="cursor:pointer" onclick=getObj("fc").style.display="none";>Fechar</a></td></tr></table>');

document.all?document.attachEvent('onclick',checkClick):document.addEventListener('click',checkClick,false);


// Calendar script
var now = new Date;
var sccm=now.getMonth()-6;
var sccy=now.getFullYear()-2;
var ccm=now.getMonth();
var ccy=now.getFullYear();

var updobj;
function lcs(ielem) 
	{
		updobj=ielem;
		getObj('fc').style.left=Left(ielem);
		getObj('fc').style.top=Top(ielem)+ielem.offsetHeight;
		getObj('fc').style.display='';
		
		// First check date is valid
		curdt=ielem.value;
		curdtarr=curdt.split('/');
		isdt=true;
		for(var k=0;k < curdtarr.length;k++) {
			if (isNaN(curdtarr[k]))
				isdt=false;
	}
	
	if (isdt&(curdtarr.length==3)) {
		ccm=curdtarr[1]-1;
		ccy=curdtarr[2];
		prepcalendar(curdtarr[0],curdtarr[1]-1,curdtarr[2]);
	}
}

function evtTgt(e)
{
	var el;
	if(e.target)el=e.target;
	else if(e.srcElement)el=e.srcElement;
	if(el.nodeType==3)el=el.parentNode; // defeat Safari bug
	return el;
}
function EvtObj(e){if(!e)e=window.event;return e;}
function cs_over(e) {
	evtTgt(EvtObj(e)).style.background='#FFCC66';
}
function cs_out(e) {
	evtTgt(EvtObj(e)).style.background='#C4D3EA';
}
function cs_click(e) {
	updobj.value=calvalarr[evtTgt(EvtObj(e)).id.substring(1,evtTgt(EvtObj(e)).id.length)];
	getObj('fc').style.display='none';
	updobj.focus();
}


var mn=new Array('JAN','FEV','MAR','ABR','MAI','JUN','JUL','AGO','SET','OUT','NOV','DEZ');
var mnn=new Array('31','28','31','30','31','30','31','31','30','31','30','31');
var mnl=new Array('31','29','31','30','31','30','31','31','30','31','30','31');
var calvalarr=new Array(42);

function f_cps(obj) {
	obj.style.background='#C4D3EA';
	obj.style.font='10px Arial';
	obj.style.color='#333333';
	obj.style.textAlign='center';
	obj.style.textDecoration='none';
	obj.style.border='1px solid #6487AE';
	obj.style.cursor='pointer';
}

function f_cpps(obj) {
	obj.style.background='#C4D3EA';
	obj.style.font='10px Arial';
	obj.style.color='#ABABAB';
	obj.style.textAlign='center';
	obj.style.textDecoration='line-through';
	obj.style.border='1px solid #6487AE';
	obj.style.cursor='default';
}

function f_hds(obj) {
	obj.style.background='#FFF799';
	obj.style.font='bold 10px Arial';
	obj.style.color='#333333';
	obj.style.textAlign='center';
	obj.style.border='1px solid #6487AE';
	obj.style.cursor='pointer';
}

// day selected
function prepcalendar(hd,cm,cy) {
	now=new Date();
	sd=now.getDate();
	td=new Date();
	td.setDate(1);
	td.setFullYear(cy);
	td.setMonth(cm);
	cd=td.getDay();
	getObj('mns').innerHTML=mn[cm]+ ' ' + cy;
	marr=((cy%4)==0)?mnl:mnn;
	for(var d=1;d<=42;d++) {
		f_cps(getObj('v'+parseInt(d)));
		if ((d >= (cd -(-1))) && (d<=cd-(-marr[cm]))) {
			dip=((d-cd < sd)&&(cm==sccm)&&(cy==sccy));
			htd=((hd!='')&&(d-cd==hd));
			if (dip)
				f_cpps(getObj('v'+parseInt(d)));
			else if (htd)
				f_hds(getObj('v'+parseInt(d)));
			else
				f_cps(getObj('v'+parseInt(d)));

			getObj('v'+parseInt(d)).onmouseover=(dip)?null:cs_over;
			getObj('v'+parseInt(d)).onmouseout=(dip)?null:cs_out;
			getObj('v'+parseInt(d)).onclick=(dip)?null:cs_click;
			if ((d-cd) < 10){var dia = '0'+(d-cd);}else{dia = (d-cd);}
			if ((cm-(-1)) < 10){var mes = '0'+(cm-(-1));}else{mes = cm-(-1);}
			getObj('v'+parseInt(d)).innerHTML=d-cd;	
			calvalarr[d]=''+(dia)+'/'+(mes)+'/'+cy;
		}
		else {
			getObj('v'+d).innerHTML='&nbsp;';
			getObj('v'+parseInt(d)).onmouseover=null;
			getObj('v'+parseInt(d)).onmouseout=null;
			getObj('v'+parseInt(d)).style.cursor='default';
			}
	}
}

prepcalendar('',ccm,ccy);
//getObj('fc'+cc).style.visibility='hidden';

function caddm() {
	marr=((ccy%4)==0)?mnl:mnn;
	
	ccm+=1;
	if (ccm>=12) {
		ccm=0;
		ccy++;
	}
	cdayf();
	prepcalendar('',ccm,ccy);
}

function csubm() {
	marr=((ccy%4)==0)?mnl:mnn;
	
	ccm-=1;
	if (ccm<0) {
		ccm=11;
		ccy--;
	}
	cdayf();
	prepcalendar('',ccm,ccy);
}

function cdayf() {
if ((ccy>sccy)|((ccy==sccy)&&(ccm>=sccm)))
	return;
else {
	ccy=sccy;
	ccm=sccm;
	cfd=scfd;
	}
}







function janelamodal(pUrl, pWidth, pHeight) {
	if (window.showModalDialog) {
		return window.showModalDialog(pUrl, window,
		  "dialogWidth:" + pWidth + "px;dialogHeight:" + pHeight + "px");
	} else {
		try {
			netscape.security.PrivilegeManager.enablePrivilege(
			  "UniversalBrowserWrite");
			window.open(pUrl, "wndModal", "width=" + pWidth
			  + ",height=" + pHeight + ",resizable=no,modal=yes");
			return true;
		}
		catch (e) {
			alert("Script não confiável, não é possível abrir janela modal.");
			return false;
		}
	}
}




            function checkAllBoxes()
            {
                
                for (i=0; i<document.body.childNodes.length;i++)
                {
                    if (document.body.childNodes[i].type)
                    {
                        if (String(document.body.childNodes[i].type).toLowerCase()=='checkbox')
                        {
                            document.body.childNodes[i].checked= true;
                        }
                    }
                }
                
            }





//-----------------------------------------------------
//Funcao: MascaraMoeda
//Sinopse: Mascara de preenchimento de moeda
//Parametro:
//   objTextBox : Objeto (TextBox)
//   SeparadorMilesimo : Caracter separador de milésimos
//   SeparadorDecimal : Caracter separador de decimais
//   e : Evento
//Retorno: Booleano
//Autor: Gabriel Fróes - www.codigofonte.com.br
//-----------------------------------------------------
function decimal(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 sonumero(num){
	if (document.all)
		var tecla = event.keyCode;
	else if(document.layers)
		var tecla = num.which;
		if (tecla > 47 && tecla < 58)
			return true;
		else
			{
				if ((tecla != 8) && (tecla != 13))
					event.keyCode = 0;
				else
					return true;
			}
}


function openAjax() { 
var Ajax; 
try {Ajax = new XMLHttpRequest(); // XMLHttpRequest para browsers mais populares, 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 carregadadoscep(cep,divlocal) { 
if(document.getElementById) { // Para os browsers complacentes com o DOM W3C. 
var exibeResultado = document.getElementById(divlocal); // div que exibirá o resultado. 
var Ajax = openAjax(); // Inicia o Ajax. 
Ajax.open("POST", "../funcoes/montarajaxcep.php?cep="+cep, true); // fazendo a requisição 
Ajax.onreadystatechange = function() 
{ 
if(Ajax.readyState == 1) { // Quando estiver carregando, exibe: Carregando... 
exibeResultado.innerHTML = "<table><tr><td class=text10><div align=center><img src=../img/processo1.gif></div></td></tr></table>";

} 
if(Ajax.readyState == 4) { // Quando estiver tudo pronto. 
if(Ajax.status == 200) { 
var resultado = Ajax.responseText; // Coloca o retornado pelo Ajax nessa variável 
resultado = resultado.replace(/\+/g," "); // Resolve o problema dos acentos (saiba mais aqui: http://www.plugsites.net/leandro/?p=4) 
resultado = unescape(resultado); // Resolve o problema dos acentos 

	var str_re1 = new String(resultado);
	str_resultado = str_re1.split(';'); 

	document.frm_cadastro.SNuf.value = str_resultado[3];
	document.frm_cadastro.SNmunicipio.value = str_resultado[2];
	document.frm_cadastro.SNbairro.value = str_resultado[1];
	document.frm_cadastro.SNendereco.value = str_resultado[0];
	exibeResultado.innerHTML = ""; 
	document.frm_cadastro.SNnumero.focus();
} else { 
exibeResultado.innerHTML = "Erro: ."; 
} 
} 
} 
Ajax.send(null);
} 
} 

function abre_janela(url, width, height, nome, scrollbar) {
var top; var left;
top = ( (screen.height/2) - (height/2) )
left = ( (screen.width/2) - (width/2) )
window.open(url,nome,'width='+width+',height='+height+',scrollbars='+scrollbar+',toolbar=no,location=no,status=no,menubar=no,resizable=no,left='+left+',top='+top);
}


function trazdados(arquivo,vlr,pcmp1,pcmp2,pcmp3,pcmp4,pcmp5,div)
{
	getObj = new AjaxObject("GET",arquivo+'?vlr='+vlr+'&pcmp1='+pcmp1+'&pcmp2='+pcmp2+'&pcmp3='+pcmp3+'&pcmp4='+pcmp4+'&pcmp5='+pcmp5);
	getObj.setCallBackFunction(callbackresponder_subcon); 
	getObj.setLoadingFunction(loadingresponder_subcon); 
	getObj.load(); 
	
	function callbackresponder_subcon(retorno)
	{
		document.getElementById(div).innerHTML = retorno;
		extraiScript(retorno);
	}
	
	function loadingresponder_subcon(retorno)
	{
		document.getElementById(div).innerHTML = "<table><tr><td class=text10><div align=center><img src=img/processo1.gif></div></td></tr></table>";
	}	
	delete getObj;
}
	
	
function montagrid(arquivo,div)
{
	getObj = new AjaxObject("GET",arquivo);
	getObj.setCallBackFunction(callbackresponder_subcon); 
	getObj.setLoadingFunction(loadingresponder_subcon); 
	getObj.load(); 
	
	function callbackresponder_subcon(retorno)
	{
		document.getElementById(div).innerHTML = retorno;
	}
	
	function loadingresponder_subcon(retorno)
	{
		document.getElementById(div).innerHTML = "<table><tr><td class=text10><div align=center><img src=img/processo2.gif></div></td></tr></table>";
	}	
	delete getObj;
}


function excreg(tabela,idn)
{
	if (idn != "ERRO01")
	{
		if (confirm('Tem certeza que deseja excluir este registro?'))
		{
			montagrid('rel/rel_exc.php?tab=' + tabela + '&idn=' + idn,'divexc1');
		}else{
			montagrid('rel/rel_exc.php?tab=' + tabela + '&idn=ead0001nd','divexc1');
		}
	}else{
			alert('Nenhum registro foi selecionado');
	}
}



function getValue(radio) 
{
var total = radio.length;
	if (total > 0)
	{
	  for (i=0; i < radio.length; i++) 
		  if (radio[i].checked == true) return radio[i].value;
	  	  return "ERRO01";
	}else{
		  return radio.value;
	}
}


function chedit(url,urldecod,idn)
{
	if (idn != "ERRO01")
	{
			window.open(url+'&u=' + urldecod + '&idn=' + idn,'alteracao','toolbar=yes,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,top=0,width=750,height=600');
	}else{
			alert('Nenhum registro foi selecionado');
	}
}




function cheditlocation(url,idn)
{
	if (idn != "ERRO01")
	{
			window.location=(url + '&idn=' + idn);
	}else{
			alert('Nenhum registro foi selecionado');
	}
}

function confsenha()
{
	var senha1 = document.frm_cadastro.elements['S*senha'].value;
	var senha2 = document.frm_cadastro.elements['S*senhav'].value;

	if (senha1.length < 6)
	{
		document.frm_cadastro.elements['S*senha'].value = '';
		document.frm_cadastro.elements['S*senhav'].value = '';
		alert('O número mínimo de caracteres não foi atingido');
		document.frm_cadastro.elements['S*senha'].focus();
	}

	if (senha1 != senha2)
	{
		document.frm_cadastro.elements['S*senha'].value = '';
		document.frm_cadastro.elements['S*senhav'].value = '';
		alert('As senhas não conferem');
		document.frm_cadastro.elements['S*senha'].focus();
	}
}

function extraiScript(texto){ 
        // inicializa o inicio >< 
        var ini = 0; 
        // loop enquanto achar um script 
        while (ini!=-1){ 
                // procura uma tag de script 
                ini = texto.indexOf('<script', ini); 
                // se encontrar 
                if (ini >=0){ 
                        // define o inicio para depois do fechamento dessa tag 
                        ini = texto.indexOf('>', ini) + 1; 
                        // procura o final do script 
                        var fim = texto.indexOf('</script>', ini); 
                        // extrai apenas o script 
                        codigo = texto.substring(ini,fim); 
                        // executa o script 
                        eval(codigo); 
                } 
        } 
}




function carregachat(arquivo,div,colab,t)
{
	getObj = new AjaxObject("GET",arquivo+'?colab='+colab);
	getObj.setCallBackFunction(callbackresponder_subcon); 
	getObj.setLoadingFunction(loadingresponder_subcon); 
	getObj.load(); 
	
	function callbackresponder_subcon(retorno)
	{
		var totalc = retorno.length;

		if (retorno.substring((totalc-1),totalc) == '1') {
			document.getElementById(div).innerHTML = retorno;
			window.focus();
		}else{
			document.getElementById(div).innerHTML = retorno.substring(0,(totalc-1));
		}
	}
	
	function loadingresponder_subcon(retorno)
	{
		document.getElementById(div).innerHTML = "<table><tr><td class=text10><div align=center><img src=../img/process1.gif></div></td></tr></table>";
	}	
	delete getObj;
		if (t == 0){
			window.setTimeout("carregachat('../chatvisit/blocoajax.php','divchat','"+colab+"','0');",8000);
		}else{
			window.setTimeout("carregachat('../chat/blocoajax.php','divchat','"+colab+"','1');",8000);
		}
}




function verificachat(arquivo,div,colab)
{
	getObj = new AjaxObject("GET",arquivo+'?colab='+colab);
	getObj.setCallBackFunction(callbackresponder_subcon); 
	getObj.setLoadingFunction(loadingresponder_subcon); 
	getObj.load(); 
	var mais="";
	if (div == "divchatat"){mais = "../";}else{mais = "";}			
	
	function callbackresponder_subcon(retorno)
	{
		if (retorno != "...")
		{

			if (popup!=null && !popup.closed){
			}else{
				popup = window.open(mais+'chatvisit/chat.php?atd='+retorno, 'Chat', 'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=no,resizable=yes,copyhistory=no,top=0,left=0,width=600,height=800');popup.focus();
			}
			
		}
		document.getElementById(div).innerHTML = "<a href='#' onclick=window.open('"+mais+"chatvisit/chat.php?atd="+retorno+"','Chat','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=no,resizable=yes,copyhistory=no,top=0,left=0,width=600,height=800');><img src="+mais+"../img/chat.png border=0></a>";
	}
	
	function loadingresponder_subcon(retorno)
	{
		document.getElementById(div).innerHTML = "<table><tr><td class=text10><div align=center><img src="+mais+"../img/process1.gif></div></td></tr></table>";
	}	
	
	delete getObj;
	
	if (colab != "")
	{
		window.setTimeout("verificachat('"+mais+"chat/verificachat.php','"+div+"','"+colab+"');",3000);
	}
}






function montalista(tipoc,campoid,camponovo,tabela,arquivo,div,vlr)
{
	getObj = new AjaxObject("GET",arquivo+'?cpid='+campoid+'&cpnovo='+camponovo+'&tab='+tabela+'&vlr='+vlr+'&tpc='+tipoc);
	getObj.setCallBackFunction(callbackresponder_subcon); 
	getObj.setLoadingFunction(loadingresponder_subcon); 
	getObj.load(); 
	
	function callbackresponder_subcon(retorno)
	{
		document.getElementById(div).innerHTML = retorno;
	}
	
	function loadingresponder_subcon(retorno)
	{
		document.getElementById(div).innerHTML = "<table><tr><td class=text10><div align=center><img src=img/loader.gif><br>Processando...</div></td></tr></table>";
	}	
	delete getObj;
}


function verifexist(cmp,vlr,tabela,arquivo,div)
{
	getObj = new AjaxObject("GET",arquivo+'?cmp='+cmp+'&idn='+vlr+'&tab='+tabela);
	getObj.setCallBackFunction(callbackresponder_subcon); 
	getObj.setLoadingFunction(loadingresponder_subcon); 
	getObj.load(); 
	
	function callbackresponder_subcon(retorno)
	{
		document.getElementById(div).innerHTML = retorno;
	}
	
	function loadingresponder_subcon(retorno)
	{
		document.getElementById(div).innerHTML = "<table><tr><td class=text10><div align=center><img src=img/loader.gif><br>Processando...</div></td></tr></table>";
	}	
	delete getObj;
}


function roundnumber(rnum) 
{
   return Math.round(rnum*Math.pow(10,2))/Math.pow(10,2);
}

function copiarvlr(vlr)
{
	document.frm_cadastro.elements['SAvlr_saldo'].value = vlr;
	document.frm_cadastro.elements['SNcomentarios'].focus();
}



function calculaprecotab(boleto,cheque,entrega)
{
	var perc_imposto = ((parseFloat(document.frm_cadastro.elements['SAperc_impostos'].value) * 1) + (parseFloat(document.frm_cadastro.elements['SAperc_custostransporte'].value) * 1) + (parseFloat(document.frm_cadastro.elements['SAperc_venda'].value) * 1) + (parseFloat(document.frm_cadastro.elements['SAperc_lucro'].value) * 1) + (parseFloat(document.frm_cadastro.elements['SAperc_entrega'].value) * 1));
	var custo = (parseFloat(document.frm_cadastro.elements['SAvlr_compra'].value) * 1);
	var tab1 = (((custo * 1) / (100 - (perc_imposto*1))) * 100);
	
	document.frm_cadastro.elements['SAtab_preco1'].value = roundnumber(tab1 - (tab1*entrega/100));
	document.frm_cadastro.elements['SAtab_preco2'].value = roundnumber(tab1);
	document.frm_cadastro.elements['SAtab_preco3'].value = roundnumber((tab1*1)+(boleto*1));
	document.frm_cadastro.elements['SAtab_preco4'].value = roundnumber((tab1*cheque/100) + tab1);
}





function pesqprod(idprod,tabpreco,cmpreco)
{
	getObj = new AjaxObject("GET",'../rel/rel_pesqprod.php?idprod='+idprod+'&tabpreco'+tabpreco);
	getObj.setCallBackFunction(callbackresponder_subcon); 
	getObj.setLoadingFunction(loadingresponder_subcon); 
	getObj.load(); 
	
	function callbackresponder_subcon(retorno)
	{
		var str_re1 = new String(retorno);
		str_resultado = str_re1.split(';');
		document.getElementById('divproddesc').innerHTML = "<strong>" + str_resultado[0] + "</strong>";
		document.getElementById('divtab1').innerHTML = "<strong>" + str_resultado[1] + "</strong>";
		document.getElementById('divprecocli').innerHTML = "<strong>" + str_resultado[6] + "</strong>";
		
		if (tabpreco == 'tsn1')
		{
		document.getElementById('divtab2').innerHTML = "<strong>" + str_resultado[2] + "</strong>";
		document.getElementById('divtab3').innerHTML = "<strong>" + str_resultado[3] + "</strong>";
		document.getElementById('divtab4').innerHTML = "<strong>" + str_resultado[4] + "</strong>";
		}
		if (cmpreco != '') 
		{
			document.frm_cadastro.elements[cmpreco].value = str_resultado[1].replace(',','.');
		}
		document.getElementById('divqtde').innerHTML = "<strong>" + str_resultado[5] + "</strong>";
	}
	
	function loadingresponder_subcon(retorno)
	{
		document.getElementById('divproddesc').innerHTML = "<table><tr><td class=text10><div align=center><img src=img/loader.gif><br>Processando...</div></td></tr></table>";
	}	
	delete getObj;
}


function pesqcliente(idcliente)
{
	getObj = new AjaxObject("GET",'../rel/rel_pesqcliente.php?idcliente='+idcliente);
	getObj.setCallBackFunction(callbackresponder_subcon); 
	getObj.setLoadingFunction(loadingresponder_subcon); 
	getObj.load(); 
	
	function callbackresponder_subcon(retorno)
	{
		var str_re1 = new String(retorno);
		str_resultado = str_re1.split(';'); 
		document.getElementById('divnomecli').innerHTML = "<strong>" + str_resultado[0] + "</strong>";
		document.getElementById('divcnpjcli').innerHTML = "<strong>" + str_resultado[1] + "</strong>";
		document.getElementById('divmunicipiocli').innerHTML = "<strong>" + str_resultado[2] + "</strong>";
	}
	
	function loadingresponder_subcon(retorno)
	{
		document.getElementById('divnomecli').innerHTML = "<table><tr><td class=text10><div align=center><img src=img/loader.gif><br>Processando...</div></td></tr></table>";
	}	
	delete getObj;
}


function pesqfornecedor(idfornecedor)
{
	getObj = new AjaxObject("GET",'../rel/rel_pesqfornecedor.php?idfornecedor='+idfornecedor);
	getObj.setCallBackFunction(callbackresponder_subcon); 
	getObj.setLoadingFunction(loadingresponder_subcon); 
	getObj.load(); 
	
	function callbackresponder_subcon(retorno)
	{
		var str_re1 = new String(retorno);
		str_resultado = str_re1.split(';'); 
		document.getElementById('divdescricao').innerHTML = "<strong>" + str_resultado[0] + "</strong>";
		document.getElementById('divcnpj').innerHTML = "<strong>" + str_resultado[1] + "</strong>";
		document.getElementById('divmunicipio').innerHTML = "<strong>" + str_resultado[2] + "</strong>";
	}
	
	function loadingresponder_subcon(retorno)
	{
		document.getElementById('divdescricao').innerHTML = "<table><tr><td class=text10><div align=center><img src=img/loader.gif><br>Processando...</div></td></tr></table>";
	}	
	delete getObj;
}


function handleEnter (field, event) {
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if (keyCode == 13) {
var i;
for (i = 0; i < field.form.elements.length; i++)
if (field == field.form.elements[i])
break;
i = (i + 1) % field.form.elements.length;
field.form.elements[i].focus();
return false;
}
else
return true;
}



function bloqf5() 
{
//Bloquear tecla F5
if (document.all)
{ 
document.onkeydown = function ()
{
var key_f5 = 116; 
if (key_f5==event.keyCode)
{
event.keyCode=0;
alert ("Função desabilitada, se necessário feche a aplicação e abra novamente!");
return false;
}
}
} 
}

