
//funcao para tirar todos os espaços em branco para a funcao "obriga"funcionar corretamente
function limpa(string) {
     var temp = "";
     string = '' + string;
     splitstring = string.split(" ");
     for(i = 0; i < splitstring.length; i++){
         temp += splitstring[i];
          return temp;
     }
}

function recarregar(elemento,ele2) {
	location.href=elemento + ele2;
}

function MM_showHideLayers() { //v9.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) 
  with (document) if (getElementById && ((obj=getElementById(args[i]))!=null)) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

//-----------------------------------------------------------------------------------------------
 //funcao para obrigar o preenchimento de campos passar o formulario como parametro

 function obriga(form){
 	var elementos = document.getElementById(form).elements;
 	for (var i=0;i<elementos.length;i++){
 if (elementos[i].getAttribute("obrigatorio")=="sim"){
   if (elementos[i].value==""  || elementos[i].value=="-Selecione-" || elementos[i].value=="-Sem Cadastro-"){
    	elementos[i].style.background = "#f8e9e1";
   		elementos[i].style.border = "1px dashed #FF6A6A";
   		alert("O campo ("+elementos[i].getAttribute("camp")+") é obrigatório!");
   		elementos[i].focus();
   		return false;
   }else{
   		elementos[i].style.border = "1px solid #bdbfbe";
   		elementos[i].style.background = "#FFFFFF";
   }
  }
 }
 return true
}

//-------------------------------------------------------------------------------------------------

//funcao para desabilitar campos, nao tem parametros definidos, passar o valor (true ou false) e os campos
function acess(){
      val = "";
      if (arguments.length > 0){acesso = arguments[0];} else {return false;}
        for (var i=1; i<arguments.length; i++ ){
            document.getElementById(arguments[i]).value=" ";
            document.getElementById(arguments[i]).disabled=acesso;
			if(acesso==false && arguments[1]){document.getElementById(arguments[1]).focus();}
          }
    }

//--------------------------------------------------------------------------------------------------

//funcao para capturar eventos com o DOM
function addEvent(object, evType, func, useCapture){
    if(object.addEventListener){
        object.addEventListener(evType, func, useCapture);
    } else if(object.attachEvent){ object.attachEvent("on" + evType, func);}
}

//----------------------------------------------------------------------------------------------

//funcao que gera um relogio digital
function horas(){
	var now = new Date();
	var hours = now.getHours();
	var minutes = now.getMinutes();
	var seconds = now.getSeconds()
	if (hours <=9)hours="0"+hours;
	if (minutes<=9)minutes="0"+minutes;
	if (seconds<=9)seconds="0"+seconds;
	var cdate="<b><font color='gray' size='2'>"+hours+":"+minutes+":"+seconds+" "+"</font>"
	clock.innerHTML= cdate;
	setTimeout("horas()",1000);
}
//-----------------------------------------------------------------------------------------------

//função para validar numeros

function numero(control){
	var c = "01234567890";
	var x = control.value.toLowerCase();
 	control.value = x;
	var y  = "correto";
	for (i=0;i<x.length;i++){
	    str1 = x;
    	str2 = str1.charAt(i);
	    if (c.indexOf(str2)==-1){ y = "incorreto";}
    }
    if (y=="incorreto")
      {control.focus();control.value = "";
      }
   }

//----------------------------------------------------------------------------------------------

//funcao para validar letras

function letra(control){
 var c = " ABCDEFGHIJKLMNOPQRSTUVXWYZÇÁÉÍÓÚÃÕÊÔÂ";
 var x = control.value.toUpperCase();
 control.value = x;
 var y  = "correto";
 for (i=0;i<x.length;i++)  {
    str1 = x;
    str2 = str1.charAt(i);
    if (c.indexOf(str2)==-1) { y = "incorreto";}
 }
 if (y=="incorreto"){control.focus();control.value = ""; }
}

//----------------------------------------------------------------------------------------------

//funcao que abre o pop-up

function abrir(pagina,largura,altura) {

//pega a resolução do visitante
w = screen.width;
h = screen.height;

//divide a resolução por 2, obtendo o centro do monitor
meio_w = w/2;
meio_h = h/2;

//diminui o valor da metade da resolução pelo tamanho da janela, fazendo com q ela fique centralizada
altura2 = altura/2;
largura2 = largura/2;
meio1 = meio_h-altura2;
meio2 = meio_w-largura2;

//abre a nova janela, já com a sua devida posição
window.open(pagina,'','height=' + altura + ', width=' + largura + ', top='+meio1+', left='+meio2+'');
}

//----------------------------------------------------------------------------------------------

//funcao para formatar a data

function data(obj,ob2,comp){
	 numero(obj,'s');
	 if(obj.value.length == 2 || obj.value.length == 5){
		 obj.value = obj.value+"/";
	 }
	 //comopara se vai ou nao  verificar a data
	 if(comp == "s"){
		 if(obj.value.length == 10){
			  var ano1 = new Date();
			  ano1 = obj.value;
			//pega o ano
			 var data = new Date();
			 var dia = data.getDate();
			 var mes = data.getMonth() + 1;
			 var ano = data.getFullYear();
			 var str_dia = new String( dia );
			 dia = (str_dia.length == 1 ? '0' + dia : dia);
			 var str_mes = new String( mes );
			 mes = (str_mes.length == 1 ? '0' + mes : mes);
			 atual =  dia + '/' + mes + '/' + ano;
			 //compara se a data fornecida é maior do que a atual
		}
	 }
	var v = document.getElementById(ob2);
	//cria uma funcao para tratar o tamanho da string
	v.onblur = function(){
	if(obj.value.length != 10){
		alert("FAVOR DIGITAR A DATA COM 8 DIGITOS SEM BARRAS / !!")
		obj.value = "";
		obj.focus();
	}else{
	var data1 = atual;
	var data2 =  ano1;
	//separa ano mes e dia para fazer a comparação
	if ( parseInt( data2.split( "/" )[2].toString() + data2.split( "/" )[1].toString() + data2.split( "/" )[0].toString() ) > parseInt( data1.split( "/" )[2].toString() + data1.split( "/" )[1].toString() + data1.split( "/" )[0].toString() ) ){  dt = '0';}
	else{  dt ='1';}
	 if (dt == '0') {
	 alert('A DATA INFORMADO É MAIOR QUE A CORRENTE!')
	  obj.value = "";
	 }
	}
	}
}

//----------------------------------------------------------------------------------------------

//funcao para validar 2 datas num intervalo

function valdata(obj1,obj2)
{
var data1 = obj2.value;
var data2 =  obj1.value;
if (data1.length == 10 && data2.length == 10){
//separa ano mes e dia para fazer a comparação
if ( parseInt( data2.split( "/" )[2].toString() + data2.split( "/" )[1].toString() + data2.split( "/" )[0].toString() ) > parseInt( data1.split( "/" )[2].toString() + data1.split( "/" )[1].toString() + data1.split( "/" )[0].toString() ) )
{
  dt = '0';
}
else
{
  dt ='1';
}
 if (dt == '0')
 {
 alert('A PRIMEIRA DATA É MAIOR DO QUE A SEGUNDA!')
  obj2.value = "";
  obj2.focus();
 }
 }
}
// funcao para telefone

function fone(obj2)
{
 var tel = obj2.value;
 var telstring = tel.substring(0,13).length;
 if (telstring < '11')
 {
 if (telstring == '10')
 {
var ddd = tel.substring(0,2);
var area = tel.substring(2,6);
var numero = tel.substring(6,10);
obj2.value = ("("+ddd+")"+" "+area+"-"+numero);
}
else
{
alert("FAVOR DIGITAR O TELEFONE COM DDD MAIS O NUMERO COM 8 DIGITOS!")
obj2.focus();
obj2.value = "";
}
}
else
{
alert("FAVOR DIGITAR O TELEFONE COM 8 DIGITOS!")
obj2.focus();
 obj2.value = "";

}
}

//----------------------------------------------------------------------------------------------

//funcao que conta quantas letras o usuario digitou e mostra o que ele pode digitar

function faltam(nome,total,span){
var camp = document.getElementById(nome).value;	
var digitado= camp.length;   //pega o total de caracteres digitados
 if(digitado>total){
     alert('VOCÊ JÁ DIGITOU O TOTAL MÁXIMO DE LETRAS, TENTE ABREVIAR A INFORMAÇÃO!');
     val = camp.slice(0,total);
	document.getElementById(nome).value = "";
	 document.getElementById(nome).value = val;
	 //exibe os 20 primeiros caracteres
 }
 digitado= camp.length;
 var restante= total-digitado;
 if (restante >= 0 && restante <= total)
 {
 document.getElementById(span).innerHTML= restante.toString() + ' '+'Letras Restantes';//exibe o texto na div
 }
 else
 {
  document.getElementById(span).innerHTML= '';
 }
}

//----------------------------------------------------------------------------------------------

//cria o objeto do ajax
function criaXMLHttp() {
if (typeof XMLHttpRequest != "undefined")
return new XMLHttpRequest();
else if (window.ActiveXObject){
var versoes = ["MSXML2.XMLHttp.5.0",
"MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0",
"MSXML2.XMLHttp", "Microsoft.XMLHttp"
];
}
for (var i = 0; i < versoes.length; i++){
try{
return new ActiveXObject(versoes[i]);
}catch (e) {}
}
throw new Error("Seu browser nao suporta AJAX");
}

//----------------------------------------------------------------------------------------------

//fucao para exibir a data
function datas()
{
 hoje = new Date()
 dia = hoje.getDate();
 dias = hoje.getDay();
 mes = hoje.getMonth();
 ano = hoje.getFullYear();
  if (dia < 10)
     dia = "0" + dia;
     if (ano < 2000)
        ano = "19" + ano;
        function CriaArray (n) {
        this.length = n; }
        NomeDia = new CriaArray(7)
        NomeDia[0] = "Domingo";
        NomeDia[1] = "Segunda-feira";
        NomeDia[2] = "Terça-feira";
        NomeDia[3] = "Quarta-feira";
        NomeDia[4] = "Quinta-feira";
        NomeDia[5] = "Sexta-feira";
        NomeDia[6] = "Sábado";
       NomeMes = new CriaArray(12)
       NomeMes[0] = "Janeiro" ;
       NomeMes[1] = "Fevereiro";
       NomeMes[2] = "Março";
       NomeMes[3] = "Abril";
       NomeMes[4] = "Maio";
       NomeMes[5] = "Junho";
       NomeMes[6] = "Julho";
       NomeMes[7] = "Agosto";
       NomeMes[8] = "Setembro";
       NomeMes[9] = "Outubro";
       NomeMes[10] = "Novembro";
       NomeMes[11] = "Dezembro";
      document.write ("<font color='gray'  face='Arial' size='2'>" + NomeDia[dias] + ", " + dia + " de " + NomeMes[mes] + " de " + ano + " </font>");
}

//----------------------------------------------------------------------------------------------

// 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='#00FF99' style='border:solid #B1E3AE; border-width:1' cellspacing='0' cellpadding='3' border='0' width='"+tam+"' height='"+tam*1.1 +"'>"
    txt += "<tr bgcolor='#FFFFFF'><td colspan='7' align='center'><table style='border:solid #EDEEEF; border='0' bgcolor='#009966' cellpadding='0' width='100%'><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' onMouseOver=\"this.style.color='#FF0000'\" onMouseout=\"this.style.color='#000000'\"><<</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' onMouseOver=\"this.style.color='#FF0000'\" onMouseout=\"this.style.color='#000000'\"><</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' onMouseOver=\"this.style.color='#FF0000'\" onMouseout=\"this.style.color='#000000'\">></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' onMouseOver=\"this.style.color='#FF0000'\" onMouseout=\"this.style.color='#000000'\">>></a></td>"
    // alterar o caminho da imagem que fecha o calendario
    txt += "<td width=20% align=right><a href=javascript:force_close('"+div+"') class='Cabecalho_Calendario' title='Fechar Calendário'><b><img src='../img/xcinza.png' border='0' width='10px'></b></a></td></tr></table></td></tr>"
    txt += "<tr><td colspan='7' align='center' bgcolor='#EDEEEF' width='10%' class='mes'>" + ano.toString() +  " " + umonth[mmonth] + " <div id='popd' style='position:absolute'></div></td></tr>"
    txt += "<tr bgcolor='#339966'><td width='10%' class='dia' align=center><b>Dom</b></td><td width='10%' class='dia' align=center><b>Seg</b></td><td width='10%' class='dia' align=center><b>Ter</b></td><td width='10%' class='dia' align=center><b>Qua</b></td><td width='10%' class='dia' align=center><b>Qui</b></td><td width='10%' class='dia' align=center><b>Sex<b></td><td width='10%' 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++)
    {
    //COR DA TABELA DOS DIAS
        if (week == 1)  txt += "<tr bgcolor='#FFFFFF' 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();
            //COR DO DIA DE HOJE
            colorcell = ((day_dat == day_today) && (year_dat == year_today) ? " bgcolor='#999999'" : "" );
            txt += "<td"+colorcell+" align=center style='border:1px solid #EDEEEF' onMouseOver=\"this.bgColor='#FFCC99'\" onMouseout=\"this.bgColor='#FFFFFF'\"><a href=javascript:block('"+  d + "/" + (mmonth+1).toString() + "/" + 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 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);
    sep = data.split("/");
    d = sep[0];
    if (d.length == 1){d = "0"+d;}
    m = sep[1];
    if (m.length == 1){m = "0"+m;}
    a = sep[2];
    ndata = d+"/"+m+"/"+a;
    obj2.value = ndata;
}

//-------------fim do calendario --------------------------------------------------------

//funcao para formatação de moeda

function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13) return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}

//----------------------------------------------------------------------------------------------

//funcao para validar e-mail

function Mail(m)
{
  var obj = eval(m);
  var txt = obj.value;
  if ((txt.length != 0) && ((txt.indexOf("@") < 1) || (txt.indexOf('.') < 7)))
  {
    alert('Email incorreto');
	obj.focus();
  }
}

//----------------------------------------------------------------------------------------------

//formata de forma generica os campos
function mascara(e,src,mask) {
    if(window.event) { _TXT = e.keyCode; }
    else if(e.which) { _TXT = e.which; }
    if(_TXT > 47 && _TXT < 58) {
		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); }
    	return true; 
	} else { 
		if (_TXT != 8) { return false; }
 		else { return true; }
    }
}


//----------------------------------------------------------------------------------------------

//mascara para telefone
function Mascarafone(e,objeto){
	 if(window.event) { _TXT = e.keyCode; }
    else if(e.which) { _TXT = e.which; }
    if(_TXT > 47 && _TXT < 58) {
		   if(objeto.value.length == 0) objeto.value = '(' + objeto.value;
		   if(objeto.value.length == 3) objeto.value = objeto.value + ')';
		   if(objeto.value.length == 4) objeto.value = objeto.value + ' ';
		   if(objeto.value.length == 9) objeto.value = objeto.value + '-';
	}else { 
		if (_TXT != 8) { return false; }
 		else { return true; }
    }
}

//----------------------------------------------------------------------------------------------

//valida telefone
function ValidaTelefone(tel){
    exp = /\(\d{2}\)\ \d{4}\-\d{4}/
    if(!exp.test(tel.value))
        alert('Numero de Telefone Invalido!');
}

//----------------------------------------------------------------------------------------------

//valida CEP
function ValidaCep(cep){
    exp = /\d{2}\.\d{3}\-\d{3}/
    if(!exp.test(cep.value))
        alert('Numero de Cep Invalido!');
}

//----------------------------------------------------------------------------------------------

//valida o CPF digitado
function ValidarCPF(Objcpf){
    var cpf = Objcpf.value;
    if(cpf == '111.111.111-11' || cpf == '222.222.222-22' ||
    cpf == '333.333.333-33' || cpf == '444.444.444-44' ||
    cpf == '555.555.555-55' || cpf == '666.666.666-66' ||
    cpf == '777.777.777-77' || cpf == '888.888.888-88' ||
    cpf == '999.999.999-99'){alert("Numero de CPF inválido!!");}
    exp = /\.|\-/g
    cpf = cpf.toString().replace( exp, "" );
    var digitoDigitado = eval(cpf.charAt(9)+cpf.charAt(10));
    var soma1=0, soma2=0;
    var vlr =11;

    for(i=0;i<9;i++){
        soma1+=eval(cpf.charAt(i)*(vlr-1));
        soma2+=eval(cpf.charAt(i)*vlr);
        vlr--;
    }
    soma1 = (((soma1*10)%11)==10 ? 0:((soma1*10)%11));
    soma2=(((soma2+(2*soma1))*10)%11);

    var digitoGerado=(soma1*10)+soma2;
    if(digitoGerado!=digitoDigitado)
        alert('CPF Invalido!');



}

//----------------------------------------------------------------------------------------------

//valida o CNPJ digitado
function ValidarCNPJ(ObjCnpj){
    var cnpj = ObjCnpj.value;
    var valida = new Array(6,5,4,3,2,9,8,7,6,5,4,3,2);
    var dig1= new Number;
    var dig2= new Number;

    exp = /\.|\-|\//g
    cnpj = cnpj.toString().replace( exp, "" );
    var digito = new Number(eval(cnpj.charAt(12)+cnpj.charAt(13)));

    for(i = 0; i<valida.length; i++){
        dig1 += (i>0? (cnpj.charAt(i-1)*valida[i]):0);
        dig2 += cnpj.charAt(i)*valida[i];
    }
    dig1 = (((dig1%11)<2)? 0:(11-(dig1%11)));
    dig2 = (((dig2%11)<2)? 0:(11-(dig2%11)));

    if(((dig1*10)+dig2) != digito)
        alert('Numero de CNPJ Inválido!!');

}

function Limpar(valor,validos) {
	// retira caracteres invalidos da string
	var result = "";
	var aux;
	for (var i=0; i < valor.length; i++) {
		aux = validos.indexOf(valor.substring(i, i+1));
		if (aux>=0) { result += aux; }
	}
	return result;
}


function Formata(campo,tammax,teclapres,decimal) {
var tecla = teclapres.keyCode;
vr = Limpar(campo.value,"0123456789");
tam = vr.length;
dec=decimal
if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }
if (tecla == 8 ){ tam = tam - 1 ; }
if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
if ( tam <= dec ){ campo.value = vr ; }
if ( (tam > dec) && (tam <= 5) ){campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 6) && (tam <= 8) ){campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;}
if ( (tam >= 9) && (tam <= 11) ){
campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 12) && (tam <= 14) ){
campo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 15) && (tam <= 17) ){
campo.value = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;}
}

}

//funcao para formatação de moeda

function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13) return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}


//requisicoes ajax cria o objeto

function criaXMLHttp() {
if (typeof XMLHttpRequest != "undefined")
return new XMLHttpRequest();
else if (window.ActiveXObject){
var versoes = ["MSXML2.XMLHttp.5.0",
"MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0",
"MSXML2.XMLHttp", "Microsoft.XMLHttp"
];
}
for (var i = 0; i < versoes.length; i++){
try{
return new ActiveXObject(versoes[i]);
}catch (e) {}
}
throw new Error("Seu browser nao suporta AJAX");
}


//funcao para popular select com ajax
/*
function envia(valor,campo,ident,imagem){
var XMLHttp = criaXMLHttp();
campo.innerHTML = " ";
campo.innerHTML = "<h5><span><center><img src='"+imagem+"'>carregando...</center></span></h5>";
XMLHttp.open("GET", "busca.php?action=cidade&uf="+valor+"&identificador="+ident, true);
XMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //envia com menas chance de erros
XMLHttp.onreadystatechange = function () {
if (XMLHttp.readyState == 4)
if (XMLHttp.status == 200){
if (XMLHttp.responseText == 0){campo.innerHTML='problemas na conexão!!!tente outra vez!!!';}else{campo.innerHTML = XMLHttp.responseText;}
} else {
campo.innerHTML = "Um erro ocorreu" + XMLHttp.statusText;
}
}
XMLHttp.send(null);
}

function envia_pro(valor,campo,ident,imagem){
var XMLHttp = criaXMLHttp();
campo.innerHTML = " ";
campo.innerHTML = "<h5><span><center><img src='"+imagem+"'>carregando...</center></span></h5>";
XMLHttp.open("GET", "busca.php?action=proprietario&tipo_prop="+valor+"&identificador="+ident, true);
XMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //envia com menos chance de erros
XMLHttp.onreadystatechange = function () {
if (XMLHttp.readyState == 4)
if (XMLHttp.status == 200){
if (XMLHttp.responseText == 0){campo.innerHTML='problemas na conexão!!!tente outra vez!!!';}else{campo.innerHTML = XMLHttp.responseText;}
} else {
campo.innerHTML = "Um erro ocorreu" + XMLHttp.statusText;
}
}
XMLHttp.send(null);
}*/

function ajax(valor,campo,ident,imagem,linkp){
	var XMLHttp = criaXMLHttp();
	campo.innerHTML = " ";
	campo.innerHTML = "<h5><span><center><img src='"+imagem+"'>carregando...</center></span></h5>";
	XMLHttp.open("GET", "busca.php?"+linkp+"&valor="+valor+"&identificador="+ident, true);
	XMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //envia com menos chance de erros
	XMLHttp.onreadystatechange = function () {
		if (XMLHttp.readyState == 4) if (XMLHttp.status == 200){
			if (XMLHttp.responseText == 0){campo.innerHTML='problemas na conexão!!!tente outra vez!!!';}else{campo.innerHTML = XMLHttp.responseText;}
		} else { campo.innerHTML = "Um erro ocorreu" + XMLHttp.statusText;}
	}
	XMLHttp.send(null);
}
//funcao para popular select com ajax

function hide(object) {
	var alvo = document.getElementById(object);
	alvo.style.visibility = 'hidden';
}
function show(object) {
	var alvo = document.getElementById(object);
	alvo.style.visibility = 'visible';
}
	
function img(v1,v2) {
	var v1 = document.getElementById(v1);
	var v2 = document.getElementById(v2);
	if (v1.style.visibility == 'visible') { v1.style.visibility = 'hidden';
	} else { v1.style.visibility = 'visible'; }
	if (v2.style.visibility == 'visible') { v2.style.visibility = 'hidden';
	} else { v2.style.visibility = 'visible'; }
	document.getElementById(menu).innerHTML = '<img src="images/icone_mais.gif" border="0"/>';
}

function menu(object) {
	var alvo = document.getElementById(object);
	if (alvo.style.visibility == 'visible') { 
		alvo.style.visibility = 'hidden';
	} else { 
		alvo.style.visibility = 'visible';
	}
}


/* -------------------------------------------
-------- MENU EM ÁRVORE - WIN EXPLORER -------
---------------------------------------------*/
// Node objeto
function Node(id, pid, name, url, title, target, isopen, img){
	this.id			= id;
	this.pid		= pid;
	this.name		= name;
	this.url		= url;
	this.title	= title;
	this.target	= target;
	this.img		= img;

	this._io		= isopen || false;
	this._ls		= false;
	this._hc		= false;
	this._is		= false;
}


// Tree objetos
function dTree(objName){
// Variaveis
// ----------------------------------------------------------------------------
	this.arrNodes			= [];
	this.arrRecursed	= [];
	this.arrIcons			= [];
	this.rootNode			= -1;
	this.strOutput		= '';
	this.selectedNode	= null;

	this.instanceName = objName;
	this.imgFolder		= 'menu/img/';
	this.target				= null;
	this.hasLines			= true;
	this.clickSelect	= true;
	this.folderLinks	= true;
	this.useCookies		= true;
// Funçoes
// ----------------------------------------------------------------------------
	// adiciona um node novo à disposição do node
	this.add = function(id, pid, name, url, title, target, isopen, img)	{
		this.arrNodes[this.arrNodes.length] = new Node(id, pid, name, url, title, target, isopen, img);
	}
	// Outputs a árvore à página 
	this.draw = function(){
		if (document.getElementById){
			this.preloadIcons();
			if (this.useCookies) this.selectedNode = this.getSelected();
			this.addNode(this.rootNode);
			document.writeln(this.strOutput);
		}else{
			document.writeln('Browser not supported.');
		}
	}

	this.openAll = function(){
		this.oAll(true);
	}

	this.closeAll = function(){
		this.oAll(false);
	}
// Confidencial
// ----------------------------------------------------------------------------
	// Imagens dePrealoads que são usadas na árvore
	this.preloadIcons = function(){
		if (this.hasLines){
			this.arrIcons[0] = new Image();
			this.arrIcons[0].src = this.imgFolder + 'plus.gif';
			this.arrIcons[1] = new Image();
			this.arrIcons[1].src = this.imgFolder + 'plusbottom.gif';
			this.arrIcons[2] = new Image();
			this.arrIcons[2].src = this.imgFolder + 'minus.gif';
			this.arrIcons[3] = new Image();
			this.arrIcons[3].src = this.imgFolder + 'minusbottom.gif';
		}else{
			this.arrIcons[0] = new Image();
			this.arrIcons[0].src = this.imgFolder + 'nolines_plus.gif';
			this.arrIcons[1] = new Image();
			this.arrIcons[1].src = this.imgFolder + 'nolines_plus.gif';
			this.arrIcons[2] = new Image();
			this.arrIcons[2].src = this.imgFolder + 'nolines_minus.gif';
			this.arrIcons[3] = new Image();
			this.arrIcons[3].src = this.imgFolder + 'nolines_minus.gif';
		}
		this.arrIcons[4] = new Image();
		this.arrIcons[4].src = this.imgFolder + 'folder.gif';
		this.arrIcons[5] = new Image();
		this.arrIcons[5].src = this.imgFolder + 'folderopen.gif';
	}

	// Função Recursive de que cría a estrutura de árvore
	this.addNode = function(pNode){
		for (var n=0; n<this.arrNodes.length; n++){
			if (this.arrNodes[n].pid == pNode){
				var cn = this.arrNodes[n];
				cn._hc = this.hasChildren(cn);
				cn._ls = (this.hasLines) ? this.lastSibling(cn) : false;
				if (cn._hc && !cn._io && this.useCookies) cn._io = this.isOpen(cn.id);

				if (this.clickSelect && cn.id == this.selectedNode){
						cn._is = true;
						this.selectedNode = n;
				}

				if (!this.folderLinks && cn._hc) cn.url = null;


				// se o node atual não for a raiz 
				if (this.rootNode != cn.pid){
					// escreve para fora a linha & ícones vazios 
					for (r=0; r<this.arrRecursed.length; r++)
						this.strOutput += '<img src="' + this.imgFolder + ( (this.arrRecursed[r] == 1 && this.hasLines) ? 'line' : 'empty' ) + '.gif" alt="" border="0"/>';

					// Linha & ícones vazios 
					(cn._ls) ? this.arrRecursed.push(0) : this.arrRecursed.push(1);

					// escreve junta para fora ícones 
					if (cn._hc){
						this.strOutput += '<a href="javascript: ' + this.instanceName + '.o(' + n + ');">'
							+ '<img id="j' + this.instanceName + n + '" src="' + this.imgFolder;
						if (!this.hasLines) this.strOutput += 'nolines_';
						this.strOutput += ( (cn._io) ? ((cn._ls && this.hasLines) ? 'minusbottom' : 'minus') : ((cn._ls && this.hasLines) ? 'plusbottom' : 'plus' ) )
							+ '.gif" alt="" border="0"/></a>';
					}else
					this.strOutput += '<img src="' + this.imgFolder + ( (this.hasLines) ? ((cn._ls) ? 'joinbottom' : 'join' ) : 'empty') + '.gif" alt="" border="0">';
				}
				// Começo da ligação do node 
				if (cn.url){
					this.strOutput += '<a href="' + cn.url + '"';
					if (cn.title) this.strOutput += ' title="' + cn.title + '"';
					if (cn.target) this.strOutput += ' target="' + cn.target + '"';
					if (this.target && !cn.target) this.strOutput += ' target="' + this.target + '"';

					// se a ligação do hightlight for sobre 
					if (this.clickSelect){
						if (cn._hc){
							if (this.folderLinks)
								this.strOutput += ' onclick="javascript: ' + this.instanceName + '.s(' + n + ');"';
						}else{
							this.strOutput += ' onclick="javascript: ' + this.instanceName + '.s(' + n + ');"';
						}
					}
					this.strOutput += '>';
				}
				if ((!this.folderLinks || !cn.url) && cn._hc && cn.pid != this.rootNode){
					this.strOutput += '<a href="javascript: ' + this.instanceName + '.o(' + n + ');">';
				}
				// escreve para fora o dobrador & pagina ícones
				this.strOutput += '<img id="i' + this.instanceName + n + '" src="' + this.imgFolder;
				this.strOutput += (cn.img) ? cn.img : ((this.rootNode == cn.pid) ? 'base' : (cn._hc) ? ((cn._io) ? 'folderopen' : 'folder') : 'page') + '.gif';
				this.strOutput += '" alt="" border="0"/>';

				// escreve para fora a extensão 
				this.strOutput += '<span id="s' + this.instanceName + n + '" class="' + ((this.clickSelect) ? ((cn._is ? 'nodeSel' : 'node')) : 'node') + '">';
				// escreve para fora o nome do node
				this.strOutput += cn.name;
					this.strOutput += '</span>';
				// Fim de linck
				if (cn.url || (!this.folderLinks && cn._hc)) this.strOutput += '</a>';
				this.strOutput += '<br />\n';
				// ----
				if (cn._hc){
					this.strOutput += '<div id="d' + this.instanceName + n + '" style="display:'
					+ ((this.rootNode == cn.pid || cn._io) ? 'block' : 'none')
					+ ';">\n';
					this.addNode(cn.id);
					this.strOutput += '</div>\n';
				}
				this.arrRecursed.pop();
			}
		}
	}

	// verifica se um node tiver alguma children
	this.hasChildren = function(node){
		for (n=0; n<this.arrNodes.length; n++)
			if (this.arrNodes[n].pid == node.id) return true;
		return false;
	}
	// verifica se um node for o último sibling 
	this.lastSibling = function(node){
		var lastId;
		for (n=0; n< this.arrNodes.length; n++)
			if (this.arrNodes[n].pid == node.pid) lastId = this.arrNodes[n].id;
		if (lastId==node.id) return true;
		return false;
	}
	// verifica se uma identificação do node esta em um cookie 
	this.isOpen = function(id){
		openNodes = this.getCookie('co' + this.instanceName).split('.');
		for (n=0;n<openNodes.length;n++)
			if (openNodes[n] == id) return true;
		return false;
	}

	// Verificações se um node esta selecionado
	this.isSelected = function(id){
		selectedNode = this.getCookie('cs' + this.instanceName);
		if (selectedNode){
			if (id==selectedNode){
				this.selectedNode = id;
				return true
			}
		}
		return false;
	}
	// retorna o node selecionado 
	this.getSelected = function(){
		selectedNode = this.getCookie('cs' + this.instanceName);
		if (selectedNode)	return selectedNode;
		return null;
	}

	// destaca o node selecionado 
	this.s = function(id){
		cn = this.arrNodes[id];
		if (this.selectedNode != id){
			if (this.selectedNode){
				eOldSpan = document.getElementById("s" + this.instanceName + this.selectedNode);
				eOldSpan.className = "node";
			}
			eNewSpan = document.getElementById("s" + this.instanceName + id);
			eNewSpan.className = "nodeSel";
			this.selectedNode = id;
			if (this.useCookies) this.setCookie('cs' + this.instanceName, cn.id);
		}
	}

	// Toggle de aberto ou próximo 
	this.o = function(id){
		cn = this.arrNodes[id];
		(cn._io) ? this.nodeClose(id,cn._ls) : this.nodeOpen(id,cn._ls);
		cn._io = !cn._io;
		if (this.useCookies) this.updateCookie();
	}
	// aberto ou próximo todos os nodes
	this.oAll = function(open){
		for (n=0;n<this.arrNodes.length;n++){
			if (this.arrNodes[n]._hc && this.arrNodes[n].pid != this.rootNode){
				if (open){
					this.nodeOpen(n, this.arrNodes[n]._ls);
					this.arrNodes[n]._io = true;
				}else{
					this.nodeClose(n, this.arrNodes[n]._ls);
					this.arrNodes[n]._io = false;
				}
			}
		}
		if (this.useCookies) this.updateCookie();
	}

	// abre um node
	this.nodeOpen = function(id, bottom){
		eDiv	= document.getElementById('d' + this.instanceName + id);
		eJoin	= document.getElementById('j' + this.instanceName + id);
		eIcon	= document.getElementById('i' + this.instanceName + id);
		eJoin.src = (bottom) ?  this.arrIcons[3].src : this.arrIcons[2].src;
		if (!this.arrNodes[id].img) eIcon.src = this.arrIcons[5].src;
		eDiv.style.display = 'block';
	}

	// finaliza um node
	this.nodeClose = function(id, bottom){
		eDiv	= document.getElementById('d' + this.instanceName + id);
		eJoin	= document.getElementById('j' + this.instanceName + id);
		eIcon	= document.getElementById('i' + this.instanceName + id);
		eJoin.src = (bottom) ? this.arrIcons[1].src : this.arrIcons[0].src;
		if (!this.arrNodes[id].img) eIcon.src = this.arrIcons[4].src;
		eDiv.style.display = 'none';
	}

	// cancela um Cookie
	this.clearCookie = function(){
		var now = new Date();
		var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
		this.setCookie('co'+this.instanceName, 'cookieValue', yesterday);
		this.setCookie('cs'+this.instanceName, 'cookieValue', yesterday);
	}

	// Sets value in a cookie
	this.setCookie = function(cookieName, cookieValue, expires, path, domain, secure) {
		document.cookie =
			escape(cookieName) + '=' + escape(cookieValue)
			+ (expires ? '; expires=' + expires.toGMTString() : '')
			+ (path ? '; path=' + path : '')
			+ (domain ? '; domain=' + domain : '')
			+ (secure ? '; secure' : '');
	}

	// começa um valor de um cookie
	this.getCookie = function(cookieName) {
		var cookieValue = '';
		var posName = document.cookie.indexOf(escape(cookieName) + '=');
		if (posName != -1){
			var posValue = posName + (escape(cookieName) + '=').length;
			var endPos = document.cookie.indexOf(';', posValue);
			if (endPos != -1)
				cookieValue = unescape(document.cookie.substring(posValue, endPos));
			else
				cookieValue = unescape(document.cookie.substring(posValue));
		}
		return (cookieValue);
	}

	// retorna ids de nós abertos como uma string 
	this.updateCookie = function(){
		sReturn = '';
		for (n=0;n<this.arrNodes.length;n++){
			if (this.arrNodes[n]._io && this.arrNodes[n].pid != this.rootNode){
				if (sReturn) sReturn += '.';
				sReturn += this.arrNodes[n].id;
			}
		}
		this.setCookie('co' + this.instanceName, sReturn);
	}

// fim dos objetos do menu tree
}


// As funções usadas pelo objeto do dTree mas não são realmente uma parte dela 
// ------------------------------------------------------------------------------------------------


if (!Array.prototype.push) {
	Array.prototype.push = function array_push() {
		for(var i=0;i<arguments.length;i++)
			this[this.length]=arguments[i];
		return this.length;
	}
}
if (!Array.prototype.pop) {
	Array.prototype.pop = function array_pop() {
		lastElement = this[this.length-1];
		this.length = Math.max(this.length-1,0);
		return lastElement;
	}
}

