// construindo o calendário
function popdate(obj,div,tam,ddd)
{
    if (ddd) 
    {
        day		= ""
        mmonth	= ""
        ano		= ""
        c		= 1
        char	= ""

		for (s=0;s<parseInt(ddd.length);s++)
        {
            char = ddd.substr(s,1)
            if (char == "/") 
            {
                c++; 
                s++; 
                char = ddd.substr(s,1);
            }
            if (c==1) day    += char
            if (c==2) mmonth += char
            if (c==3) ano    += char
        }
        ddd = mmonth + "/" + day + "/" + ano
    }
  
    if(!ddd) {today = new Date()} else {today = new Date(ddd)}
    date_Form = eval (obj)
    if (date_Form.value == "") { date_Form = new Date()} else {date_Form = new Date(date_Form.value)}
  
    ano		= today.getFullYear();
    mmonth	= today.getMonth ();
    day		= today.toString ().substr (8,2)
  
    umonth		= new Array ("Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro")
    days_Feb	= (!(ano % 4) ? 29 : 28)
    days		= new Array (31, days_Feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

    if ((mmonth < 0) || (mmonth > 11))  alert(mmonth)
    if ((mmonth - 1) == -1) {month_prior = 11; year_prior = ano - 1} else {month_prior = mmonth - 1; year_prior = ano}
    if ((mmonth + 1) == 12) {month_next  = 0;  year_next  = ano + 1} else {month_next  = mmonth + 1; year_next  = ano}
    txt		= "<table bgcolor='#efefff' style='border:solid #cdcdcd; border-width:2' cellspacing='0' cellpadding='3' border='0' width='"+tam+"' height='"+tam*1.1 +"'>"
    txt		+= "<tr bgcolor='#FFFFFF'><td colspan='7' align='center'><table border='0' cellpadding='0' width='100%' bgcolor='#FFFFFF'><tr>"
    txt		+= "<td width=20% align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+((mmonth+1).toString() +"/01/"+(ano-1).toString())+"') class='Cabecalho_Calendario' title='Ano Anterior'><<</a></td>"
    txt		+= "<td width=20% align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+( "01/" + (month_prior+1).toString() + "/" + year_prior.toString())+"') class='Cabecalho_Calendario' title='Mês Anterior'><</a></td>"
    txt		+= "<td width=20% align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+( "01/" + (month_next+1).toString()  + "/" + year_next.toString())+"') class='Cabecalho_Calendario' title='Próximo Mês'>></a></td>"
    txt		+= "<td width=20% align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+((mmonth+1).toString() +"/01/"+(ano+1).toString())+"') class='Cabecalho_Calendario' title='Próximo Ano'>>></a></td>"
    txt		+= "<td width=20% align=right><a href=javascript:force_close('"+div+"') class='Cabecalho_Calendario' title='Fechar Calendário'><b>X</b></a></td></tr></table></td></tr>"
    txt		+= "<tr><td colspan='7' align='right' bgcolor='#dcdcdc' class='mes'><a href=javascript:pop_year('"+obj+"','"+div+"','"+tam+"','" + (mmonth+1) + "') class='mes'>" + ano.toString() + "</a>"
    txt		+= " <a href=javascript:pop_month('"+obj+"','"+div+"','"+tam+"','" + ano + "') class='mes'>" + umonth[mmonth] + "</a> <div id='popd' style='position:absolute'></div></td></tr>"
    txt		+= "<tr bgcolor='#aaaaaa'><td width='14%' class='dia' align=center><b>Dom</b></td><td width='14%' class='dia' align=center><b>Seg</b></td><td width='14%' class='dia' align=center><b>Ter</b></td><td width='14%' class='dia' align=center><b>Qua</b></td><td width='14%' class='dia' align=center><b>Qui</b></td><td width='14%' class='dia' align=center><b>Sex<b></td><td width='14%' class='dia' align=center><b>Sab</b></td></tr>"
    today1		= new Date((mmonth+1).toString() +"/01/"+ano.toString());
    diainicio	= today1.getDay () + 1;
    week		= d = 1
    start		= false;

    for (n=1;n<= 42;n++) 
    {
        if (week == 1)  txt += "<tr bgcolor='#efefff' align=center>"
        if (week==diainicio) {start = true}
        if (d > days[mmonth]) {start=false}
        if (start) 
        {
            dat		= new Date((mmonth+1).toString() + "/" + d + "/" + ano.toString())
            day_dat	= dat.toString().substr(0,10)
            day_today	= date_Form.toString().substr(0,10)
            year_dat	= dat.getFullYear ()
            year_today	= date_Form.getFullYear ()
            colorcell	= ((day_dat == day_today) && (year_dat == year_today) ? " bgcolor='#FFCC00' " : "" )
			
			if(d < 10){
				d_string =	"0"+d.toString()
			}else{
				d_string =	d.toString()
			};
			
			if(mmonth+1 < 10){
				m_string =	"0"+(mmonth+1).toString()
			}else{
				m_string =	(mmonth+1).toString()
			};
			
            txt			+= "<td"+colorcell+" align=center><a href=javascript:block('"+  d_string + "/" + m_string + "/" + ano.toString() +"','"+ obj +"','" + div +"') class='data'>"+ d.toString() + "</a></td>"
            d ++ 
        } 
        else 
        { 
            txt += "<td class='data' align=center> </td>"
        }
        week ++
        if (week == 8) 
        { 
            week = 1; txt += "</tr>"} 
        }
        txt		+= "</table>"
        div2	= eval (div)
        div2.innerHTML	= txt
}
  
// função para exibir a janela com os meses
function pop_month(obj, div, tam, ano)
{
  txt  = "<table bgcolor='#aaaaaa' border='0' width=80>"
  for (n = 0; n < 12; n++) { txt += "<tr><td align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+("01/" + (n+1).toString() + "/" + ano.toString())+"')>" + umonth[n] +"</a></td></tr>" }
  txt += "</table>"
  popd.innerHTML = txt
}

// função para exibir a janela com os anos
function pop_year(obj, div, tam, umonth)
{
  txt  = "<table bgcolor='#aaaaaa' border='0' width=160>"
  l = 1
  for (n=1991; n<2012; n++)
  {  if (l == 1) txt += "<tr>"
     txt += "<td align=center><a href=javascript:popdate('"+obj+"','"+div+"','"+tam+"','"+(umonth.toString () +"/01/" + n) +"')>" + n + "</a></td>"
     l++
     if (l == 4) 
        {txt += "</tr>"; l = 1 } 
  }
  txt += "</tr></table>"
  popd.innerHTML = txt 
}

// função para fechar o calendário
function force_close(div) 
    { div2 = eval (div); div2.innerHTML = ''}
    
// função para fechar o calendário e setar a data no campo de data associado
function block(data, obj, div)
{ 
    force_close (div)
    obj2 = eval(obj)
    obj2.value = data 
}
// FIM DA CONSTRUÇÃO DO CALENDÁRIO.


function scrollOver(){
if (document.form.cbScroller.checked)
	{scroller.scrollAmount='0'}
else
	{scroller.scrollAmount='1'}
scroller.style.cursor='default'
}

function scrollOut()
{
if (document.form.cbScroller.checked)
	{scroller.scrollAmount='0'}
else
	{scroller.scrollAmount='3'}
}

function checkSBox(box)
{
SBox = eval(box);
SBox.checked = !SBox.checked;
scrollOut();
}


function valDoc(obj,tip){
	with(document.forms[0]){
		if(tip == 1){ //CPF
			if(obj.value != "" && validaCPF(obj.value)==false){
				alert("O CPF informado não é válido")
				obj.focus()
				return
			}
		}
		else if(tip == 2){ //CNPJ
			if(obj.value != "" && validaCNPJ(obj.value)==false){
				alert("O CNPJ informado não é válido")
				obj.focus()
				return
			}
		}
	}
}


function remAlfanumerico(str){
	//retorna somente os caracteres de 0 a 9
	for(i=0;i<str.length;i++){
		if(str.charCodeAt(i) < 48 || str.charCodeAt(i) > 57){
			str = str.substring(0,i) + str.substr(i+1);
			i--;
		}
	}
	return str;
}

function validaCPF(txtCPF){
	tCPF = remAlfanumerico(txtCPF);
	dv = tCPF.substr(tCPF.length-2);
	tCPF = tCPF.substr(0,tCPF.length-2);
	
	if(parseInt(tCPF) / parseInt(tCPF.substr(0,1)) == "1111111111"){
		return(0)
	} 
	else {
	
		for(j=0;j<dv.length;j++){
			ind = 2;
			aux = 0;
			for(i=tCPF.length-1;i>=0;i--){
				aux += ind * parseInt(tCPF.charAt(i));
				ind++	
			}
			aux = 11 - (aux%11);
			if(aux > 9) aux = 0;			
			if(aux == dv.charAt(j)){
				tCPF += dv.charAt(j);
			}
			else{
				return(0);
			}
		}
		if(tCPF.length == 11){	
			return(1);	
		}
		else{
			return(0);
		}
	}
}

function validaCNPJ(txtCNPJ){
	tCNPJ = remAlfanumerico(txtCNPJ);
	dv = tCNPJ.substr(tCNPJ.length-2);
	tCNPJ = tCNPJ.substr(0,tCNPJ.length-2);
	for(j=0;j<dv.length;j++){
		ind = 2;
		aux = 0;
		for(i=tCNPJ.length-1;i>=0;i--){
			aux += ind * parseInt(tCNPJ.charAt(i));
			if(ind < 9){
				ind++;
			}
			else{
				ind = 2;
			}
		}
		aux = 11 - (aux%11);
		if(aux > 9) aux = 0;			
		if(aux == dv.charAt(j)){
			tCNPJ += dv.charAt(j);
		}
		else{
			return(0);
		}
	}	
	if(tCNPJ.length == 14){	
		return(1);	
	}
	else{
		return(0);
	}
}


function FN(num,op){
	if(op == 1) {
		return String(num).replace(",",".")
	}
	else if(op == 0) {
		return String(num).replace(".",",")
	}			
}

function formataNumero(num,dec){
	var d
	var n
	
	if(num.indexOf(",") >= 0){
		n = num.substring(0,num.indexOf(","))
		d = num.substring(num.indexOf(",")+1)		
	} else {
		n = num
		d = "0"
	}
	if(d.length < dec){
		for (i=d.length; i < dec; i++){
			d = d + "0"
		}
	}else{
		d = d.substring(0,dec)
	}

	num = n + "," + d
	return num
}

function formatarHora(obj){
	hStr = obj.value
	if(event.type == "keypress"){
		BloqueiaLetras()
		if (hStr.length == 2){
			obj.value = hStr + ":"
		}
	}
	else if(event.type == "blur"){
		if(hStr.length == 5 && hStr.indexOf(":") == 2){
			if(hStr.substring(0,2) > 24){
				alert("Hora inválida.")
				obj.focus()
			}else if(hStr.substring(3,5) > 59){
				alert("Minuto inválido.")
				obj.focus()
			}
		}
		else if(hStr.length > 0){
			alert("Hora/minuto inválidos. Informe um valor no formato hh:mm")
			obj.focus()
		}
	}
}



function data(dt,op){
	if (dt == ""){

		dt = new Date()
		d = dt.getDate()
		m = dt.getMonth() + 1
		a = dt.getYear()
		dt = d + "/" + m + "/" + a
	}
	if (op == 0){
		switch (m){
			case 1	: mNome = "Janeiro"; break;
			case 2	: mNome = "Fevereiro"; break;
			case 3	: mNome = "Março"; break;
			case 4	: mNome = "Abril"; break;
			case 5	: mNome = "Maio"; break;
			case 6	: mNome = "Junho"; break;
			case 7	: mNome = "Julho"; break;
			case 8	: mNome = "Agosto"; break;
			case 9	: mNome = "Setembro"; break;
			case 10	: mNome = "Outubro"; break;
			case 11	: mNome = "Novembro"; break;
			case 12	: mNome = "Dezembro"; break;
		}
		result = d + " " + mNome + " de " + a 
	}
	
	return result
}

function Submeter(nForm,destino){
	with(document.forms[nForm]){		
		op.value = "";
		action = destino; 
		submit();
	}
}

function FormataData(dt){
	BloqueiaLetras()
	with(document.forms[0]){
		if(dt.value.substring(dt.value.length-1,dt.value.length) != "/"){
			if(dt.value.length == 2 || dt.value.length == 5){
				dt.value = dt.value + "/" 
			}
		}		
	}
}

function ValidaData(dt){
	with(document.forms[0]){
		if(dt.value.length == 10 || dt.value.length == 8){
			dd = dt.value.substring(0,2)
			mm = dt.value.substring(3,5)
			aa = dt.value.substring(6,10)
			if(mm > 12 || mm < 1 ||mm.length != 2){alert("Mês inválido!");return "erro";}
			if((mm*5)%2 == 0 && mm < 8 && mm != 2){ultimo_dd = 30}
			if((mm*5)%2 == 1 && mm < 8 && mm != 2){ultimo_dd = 31}
			if((mm*5)%2 == 0 && mm >= 8 && mm != 2){ultimo_dd = 31}
			if((mm*5)%2 == 1 && mm >= 8 && mm != 2){ultimo_dd = 30}	
			if(mm == 2 && aa%4 == 0){ultimo_dd = 29}
			if(mm == 2 && aa%4 > 0){ultimo_dd = 28}
			if(dd > ultimo_dd || dd < 1 || dd.length != 2){alert("Dia inválido!");return "erro";}
			if(aa.length != 4 && aa.length != 2){alert("Ano inválido!");return "erro";}
		}
		else{
			if (dt.value!="")	{
				alert("Data inválida!\nInforme a data no formato DD/MM/AAAA ou DD/MM/AA")
				dt.focus()
			}
		}
	}
}

function VerificaMaximo(obj,maxi,op){
//	obj	 = objeto cuja quantidade de carecteres será
//		   verificada;
//	maxi = quantidade máxima de caracteres;
//	op	 = 0 - não retorna nenhum valor;
//	op	 = 1 - retorna 1 quando a quantidade máxima de caracteres for atingida;
//	op	 = 2 - remove caracteres excedentes
//if(op == 2) obj.value = obj.value.substring(0,maxi)
	if(op == 2){
		obj.value = obj.value.substring(0,maxi)
	}
	if(obj.value.length == maxi){
		window.event.keyCode=0;
		if(op == 1) return(1);
//		
	}

}

function FormataValorObj(obj,qtdDec){
	chr = String.fromCharCode(window.event.keyCode)
	asc = window.event.keyCode

	if(event.type == "keypress"){

		window.event.keyCode=0
		if (asc>=48 && asc <=59){		
			while(obj.value.indexOf(",") > 0){
				obj.value = obj.value.replace(",","")		
			}
			while(obj.value.indexOf(".") > 0){
				obj.value = obj.value.replace(".","")		
			}
			obj.value = obj.value + chr 
		}

	}
	if( asc != 37 && asc != 40) {
		obj.value = FormataValor(obj.value,qtdDec)	
	}
}

function FormataValor(strVal,qtdDec){
	var p1 = ""
	var p2 = ""
	var aux = ""
	var j = 0

	if(qtdDec==null){
		qtdDec = 2
	}
	strVal = String(strVal)
	
	while(strVal.indexOf(".") > 0){
		strVal = strVal.replace(".","")		
	}
	
	while(strVal.indexOf(",") > 0){
		strVal = strVal.replace(",","")		
	}


	for(i=strVal.length;i<qtdDec+1;i++){
		strVal = "0" + strVal
	}

	if(strVal.length > qtdDec){
		p1 = String(parseFloat(strVal.substring(0,strVal.length-qtdDec)))
		p2 = strVal.substring(strVal.length-qtdDec)
		
		for(i=p2.length; i > 0 && p2.length > 2; i--){
			if(p2.substr(p2.length - 1, 1) == 0){
				p2 = p2.substring(0,p2.length-1)
			}
		}
		
		for(i=p1.length;i>0;i--){
			j++
			if(j>3){ 
				aux = "." + aux
				j=1
			}
			aux = p1.substr(i-1,1) + aux
		}

		if(aux != "") {
			strVal = aux + "," + p2

		}
		else strVal = p1 +","+ p2
	}


	return strVal

}

function BloqueiaTudo(exc){
	var tecla = String.fromCharCode(window.event.keyCode);
	status = exc.indexOf(tecla) < 0
	if (exc.indexOf(tecla)<0)
	{
		window.event.keyCode=0;
	}  		
}

function BloqueiaLetras_virgula(){
	var codTecla = window.event.keyCode;
	var tecla = String.fromCharCode(codTecla);
	if (tecla==","){
	}else{
		if (tecla == " " || !(tecla >= 0 && tecla <= 9)){
					window.event.keyCode=0;
		}  
	}
}


function BloqueiaLetras(){
/*
var e = window.event;
if (e.keyCode)			code = e.keyCode;
else if (e.which)		code = e.which; // Netscape 4.?
else if (e.charCode)	code = e.charCode; // Mozilla

alert(code);
*/

	var codTecla = window.event.keyCode;
	var tecla = String.fromCharCode(codTecla);

	if (tecla == " " || !(tecla >= 0 && tecla <= 9))
	{
		window.event.keyCode=0;
	}  
}

function BloqueiaNumeros(){
	var codTecla = window.event.keyCode;
	var tecla = String.fromCharCode(codTecla);
	if (tecla >= 0 && tecla <= 9)
	{
		window.event.keyCode = 0	
	}
}

function AbrirJanela(url,x,y,nome,param){
	x = ( x == "" ) ? x = '' : x = x ;
	y = ( y == "" ) ? y = '' : y = y ;

	nome = ( nome == "" ) ? nome = "novajanela" : nome = nome;
	nome = ( nome == undefined) ? nome = "" : nome;

	param = ( param == "" ) ? param = "left=50, top=50, width = "+x+", height="+y+", tollbar=no, status=yes, scrollbars=yes" : param = param;
	param = ( param == undefined) ? param = "" : param;

	nome = window.open(url,nome,param)
}

function ChkTodos(obj,frm,op){
//	1 - seleciona todos os itens de um objeto do tipo checkbox
//	0 - limpa todas seleçoes de itens de um objeto do tipo checkbox
//	[object] - limpa todas seleçoes de itens de um objeto do tipo checkbox
	if(typeof(op) == "object"){
		if(op.checked){
			op = 1
		}else{
			op = 0
		}
	}
	obj = (eval("document."+frm+"."+obj))
	if(op == 1)
		for(i=0;i<=obj.length-1;i++)
			obj[i].checked = true
	if(op == 0)
		for(i=0;i<=obj.length-1;i++)
			obj[i].checked = false
}

function MostraLayer(lay,op,sty){
//	lay - Nome do Layer (String)
//	op = 0 - Se oculto, mostra layer, senão oculta layer
//	op = 1 - Mostra layer
//	op = 2 - Oculta layer
//	sty = 0 - visibility
//	sty = 1 - display
	styDefault = 0
	if(sty == null)
		sty = styDefault
		
	lay = eval("window."+lay)
	
	if (op != 0){
		if(sty == 0)
		  (op == 1) ? param = "visible" : param = "hidden";
		if(sty == 1)
		  (op == 1) ? param = "" : param = "none";

	}
	else{
		if(sty == 0){
			param = lay.style.visibility;
			param = (param == "hidden") ? param = "visible" : param = "hidden";
		}
		if(sty == 1){
			param = lay.style.display;
			param = (param == "none") ? param = "" : param = "none";
		}
	}
	if(sty == 0){
		lay.style.visibility = param;
	}
	else
	if(sty == 1)
		lay.style.display = param;
}

function msg(msgTxt){
	if(msgTxt != null){
		alert(msgTxt)
	}
}
