/*|---------------------------------->>  <<----------------------------------|

Include para ser usado na estrutura padrão dos sites. deve chamado
no arquivo head.inc.php.

Sr. Programador, todas as funções em javascript que serão utilizadas no site
deverão serem declaradas apenas neste arquivo.

|---------------------------------->>  <<----------------------------------|*/
function fecha_menu(objeto)
{
	if(document.getElementById)
	{
		var master = document.getElementById(objeto);
		master.style.display = "none";
	}
}

function vaipaiusr(id)
{
	window.opener.location = 'acoes.php?per=1&id='+id;
	window.opener.focus();
	this.close();
}

function gera_etiquetas_lista() {
	alert(document['lista']['del_item[]'].length);
}

function vaipaimsg(dst,nm)
{
		var largura 	= 600;
		var altura 		= 420;

		var esquerda	= meio_largura(largura);
		var topo 		= meio_altura(altura);

		var janela = window.open('pop_mensagem_escrever.php?destino='+dst+'&nome='+nm, 'msgarq', 'scrollbars=yes, width='+largura+', height='+altura+', top='+topo+', status = yes, resizable=yes, left='+esquerda);
		this.close();
}

function vaipaiage(id)
{
	window.opener.location = 'agenda_mes.php?usuario='+id;
	window.opener.focus();
	this.close();
}

// Método inArray para javascript
function inArray(vetor,value)
{
    var i;
    for (i in vetor) {
        if (vetor[i] === value) {
            return true;
        }
    }
    return false;
}

// Método indexOf para javascript
function indexOf(vetor,value)
{
    var i;
    for (i in vetor) {
        if (vetor[i] === value) {
            return i;
        }
    }
    return false;
}

function img_pop(arquivo, largura, altura)
{
	var esquerda	= meio_largura(largura);
	var topo 		= meio_altura(altura);

	window.open(arquivo, 'pop_img', 'width='+largura+', height='+altura+', resizable=yes, top='+topo+', left='+esquerda);
}

function qtd_grupo(form, campo, check_id, marcador)
{
	var marcados = 0;
	var total_grupo = 0;

	for(var i=0; i<document[form][campo].length; i++)
	{
		if(document[form][campo][i].id == check_id)
		{
			total_grupo += 1;
			if(document[form][campo][i].checked)
				marcados += 1;
		}
	}

	if(marcados < total_grupo)
		document[form][marcador].checked = false;
	else if(marcados == total_grupo)
		document[form][marcador].checked = true;
}

function marca_grupo(form, campo, check_id, check_flag)
{
	for(var i=0; i<document[form][campo].length; i++)
	{
		if(document[form][campo][i].id == check_id)
		{
			document[form][campo][i].checked = check_flag;
		}
	}
}

function deleta_item(nome_form, reg_id)
{
	if(confirm('Tem certeza que deseja deletar este registro?'))
	{
		document[nome_form]['del_item[]'].value = reg_id;
		document[nome_form].submit();
	}
	else
		return false;
}

function abre_relatorio(relat_id)
{
	var largura 	= 780;
	var altura 		= 550;

	var esquerda	= meio_largura(largura);
	var topo 		= meio_altura(altura);
	window.open('relat_frame.php?relat_id='+relat_id, 'relatorios','width='+largura+', height='+altura+', resizable=yes, top='+topo+', left='+esquerda);
}

function troca_cor(objeto, cor)
{
	if(document.getElementById)
	{
		var linha = document.getElementById(objeto);
		linha.style.background = cor;
	}
}

function pop_link(endereco, pop_largura, pop_altura)
{
	var largura 	= pop_largura;
	var altura 		= pop_altura;

	var esquerda	= meio_largura(largura);
	var topo 		= meio_altura(altura);

	window.open(endereco, '', 'width='+largura+', height='+altura+', resizable=yes, scrollbars=yes, top='+topo+', left='+esquerda);
}

function abre_agenda(form, campo, data)
{
	if(!data.value)
	{
		alert('Antes, digite um dia.');
		data.focus();
		return false;
	}
	else
	{
		var largura 	= 400;
		var altura 		= 390;

		var esquerda	= meio_largura(largura);
		var topo 		= meio_altura(altura);

		window.open('pop_agenda.php?form='+form+'&campo='+campo+'&data='+data.value,'agenda','width='+largura+', height='+altura+', top='+topo+', left='+esquerda);
	}
}

function busca_cliente()
{
	var largura 	= 420;
	var altura 		= 220;

	var esquerda	= meio_largura(largura);
	var topo 		= meio_altura(altura);

	window.open('pop_busca_cliente.php', 'busca_cliente', 'width='+largura+', height='+altura+', top='+topo+', left='+esquerda);
}

function envia_pai(linha, chave, campo_chave, campo_id, parent)
{
	if(parent)
	{
		window.parent.opener.document.geral[campo_chave].value = chave;
		window.parent.opener.document.geral[campo_id].value = linha;
		window.parent.opener.focus();
		window.parent.close();
	}
	else
	{
		window.opener.document.geral[campo_chave].value = chave;
		window.opener.document.geral[campo_id].value = linha;
		window.opener.focus();
		this.close();
	}
}

function janela_pop(destino, janela, retorna)
{
	var largura 	= 793;
	var altura 		= 550;

	var esquerda	= meio_largura(largura);
	var topo 		= meio_altura(altura);

	// a variável janela não está sendo utilizada. para utilizar, trocar o _blank por ela.
	objJanela = window.open(destino+'&pop=1', '_blank', 'scrollbars=yes, width='+largura+', height='+altura+', top='+topo+', resizable=yes, left='+esquerda);

	if(retorna)
	    return objJanela;
}

function pop(destino, janela)
{
    janela_pop(destino, janela, false);
}

function pop2(destino, janela)
{
    pop3(destino, janela);
}

function pop3(destino, janela)
{
	var largura 	= 793;
	var altura 		= 420;

	var esquerda	= meio_largura(largura);
	var topo 		= meio_altura(altura);

	return window.open(destino, janela, 'scrollbars=yes, width='+largura+', height='+altura+', top='+topo+', resizable=yes, left='+esquerda);
}

function abre_janela_etiquetas(mypage) {

	selecionados = '';
	for(i=0; i<document.forms['lista']['del_item[]'].length; i++) {
		if(document.forms['lista']['del_item[]'][i].checked)
			selecionados += document.forms['lista']['del_item[]'][i].value + ',';
	}
	if(selecionados != '') {
		lista = document.getElementById("form_lista");
		lista.action.value = 'imprime_etiquetas';
		lista.mypage.value = mypage;
		lista.submit();
		//OpenNewWindow(mypage+'&selecionados='+selecionados, w, h, myname);
	} else {
		alert('Atenção: Selecione ao menos uma linha.');
		return false;
	}
}

//Função pra abrir janela no centro da página
function OpenNewWindow(mypage,w,h,myname){

var winl = (screen.width- w)/2;

var wint = ((screen.height- h)/2)-25;

settings='height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars=yes,toolbar=no,location=no,status=no,menubar=no,resizable=no,dependent=no,nirectories=no,status=no,fullscreen=0'

win=window.open(mypage,myname,settings)

if(parseInt(navigator.appVersion) >= 4){win.window.focus();}

}

function abre_cal_nova(form, campo, data, obj_botao)
{
    //inputField,format,buttonObj,displayTime,timeInput
    displayCalendar(document.forms[form][campo],'dd/mm/yyyy', obj_botao);
}

function abre_cal(form, campo, data)
{
    abre_cal_nova(form, campo, data, document.forms[form][campo]);
}

function limpa_campo(formulario, campo)
{
	document[formulario][campo].value = '';
}

function troca_todos(tf)
{
	if(tf.checked)
		var flag = true;
	else
		var flag = false;

	ToggleAll('lista', 'del_item[]', flag);

	if(document['lista']['recibo[]'])
		ToggleAll('lista', 'recibo[]', flag);

	document.lista['marca_todos[]'][0].checked = flag;
	document.lista['marca_todos[]'][1].checked = flag;
}

function ToggleAll(formname, field, checked_flag)
{
	var len = document[formname][field].length;
    for(i = 0; i< len; i++)
        document[formname][field][i].checked = checked_flag;
}

function check(formulario, campo)
{
//	alert(document[formulario][campo].name);
	if(document[formulario][campo].checked)
		document[formulario][campo].checked = false;
	else
		document[formulario][campo].checked = true;
}

function check_radio(formulario, campo, valor)
{
	for(var i = 0; i < document[formulario][campo].length; i++)
	{
		if(document[formulario][campo][i].value == valor)
		{
			if(document[formulario][campo][i].checked == true && document[formulario][campo][i].type == 'checkbox')
				document[formulario][campo][i].checked = false;
			else
				document[formulario][campo][i].checked = true;
		}
	}
}

function marca_duplo(check, linha)
{
	if(document.geral[check][linha].checked)
		document.geral[check][linha].checked = false;
	else
		document.geral[check][linha].checked = true;
}

function marca_duplos(tabela, flag, troca)
{
	var i = 0;

	if(troca && flag)
		var flag = false;
	else if(troca && !flag)
		var flag = true;

    try
    {
    	for(i=0; i<document.geral['duplos_'+tabela+'[]'].length; i++)
    	{
    		document.geral['duplos_'+tabela+'[]'][i].checked = flag;
    	}
    }
    catch(erro)
    {
    	for(i=0; i<document.geral[tabela+'[]'].length; i++)
    	{
    		document.geral[tabela+'[]'][i].checked = flag;
    	}
    }

    try
    {
        document.geral['todos_'+tabela].checked = flag;
    }
    catch(erro)
    {

    }
}

function imprime_relat()
{
	parent.relat_principal.focus();
	parent.relat_principal.print();
}

function imprime_meio()
{
	parent.pop_meio.focus();
	parent.pop_meio.print();
}

function abre_janela_impressao(mypage) {
	selecionados = '';
	for(i=0; i<document.forms['lista']['del_item[]'].length; i++) {
		if(document.forms['lista']['del_item[]'][i].checked)
			selecionados += document.forms['lista']['del_item[]'][i].value + ',';
	}
	if(selecionados != '') {
		lista = document.getElementById("form_lista");
		lista.action.value = 'imprime_lista_selecionada';
		lista.mypage.value = mypage;
		lista.submit();
			//abre_print(vars+'selecionados='+selecionados);
	} else {
		alert('Atenção: Selecione ao menos uma linha.');
		return false;
	}
}

function abre_print(vars)
{
	// Função para produtos passados por id no index (link no email)
	var largura 	= 700;
	var altura 		= 500;

	var esquerda	= meio_largura(largura);
	var topo 		= meio_altura(altura);

	window.open('pop_print.php?pagina='+vars,'pop_print','width='+largura+', height='+altura+', resizable=yes, top='+topo+', left='+esquerda);

}

function confirma_delete()
{
	if(confirm('Tem certeza que você deseja apagar este(s) registro(s)?'))
		return true;
	else
		return false;
}

function valida_dinamico(dados, alerta)
{
	for(var i=0; i<dados.length; i++)
	{
		if(dados[i].id == 'true' && !dados[i].value)
		{
			alert(alerta);
			dados[i].focus();
			return false;
		}
	}
	if(dados.name == 'orcamento_aberto' && dados.cli_senha.value != dados.cli_senha1.value)
	{
		alert('As senha estão diferentes, por favor confira');
		dados.cli_senha1.value = '';
		dados.cli_senha1.focus();
		return false;
	}

	return true;
}

// Nova valida_dinamico
campos_obrigatorios         = new Array();
campos_inteiros             = new Array();
campos_float                = new Array();
campos_html                 = new Array();
nomes_campos                = new Array();
minimo_caracteres_campos    = new Array();
abas_campos                 = new Array();
campos_upload               = new Array();

var er_int          = /[^0-9,.]/;
var er_float        = /[^0-9,.]/;

function valida_dinamico2(form)
{
    erro = "";
    elemento_foco = "";
    direcionar_aba = null;

    if(campos_html.length > 0)
        tinyMCE.triggerSave();

    for(n = 0;n < form.elements.length; n++)
	{
        elemento = form.elements[n];

        // Isso é pra o elemento não ficar sem id
        if(!elemento.id)
            form.elements[n].id = "_form_elemento_"+n;

        // Campos obrigatórios
        if(inArray(campos_obrigatorios,elemento.name) && (elemento.value == "" && !(inArray(campos_upload, elemento.name) && (form["valor[" + elemento.name.replace(/^campo_/, "") + "]"].value != "" || elemento.value != "") ))) // Verifica também os casos especiais de campos de upload
        {
            if(nomes_campos[elemento.name])
                nome_campo = nomes_campos[elemento.name];
            else
                nome_campo = elemento.name;

            if(erro != "")
                erro += "\n";

            nome_campo = nome_campo.replace(/<br>/," ");
            nome_campo = nome_campo.replace(/<BR>/," ");

            erro += "- "+nome_campo+": campo obrigatório.";

            if(direcionar_aba == null)
                direcionar_aba = abas_campos[elemento.name];

            if(elemento_foco == "")
                elemento_foco = elemento;
            continue;

        }

        // Campos inteiros
        if(elemento.value != "" && inArray(campos_inteiros,elemento.name) && er_int.test(elemento.value) == true)
        {
            if(nomes_campos[elemento.name])
                nome_campo = nomes_campos[elemento.name];
            else
                nome_campo = elemento.name;

            if(erro != "")
                erro += "\n";

            nome_campo = nome_campo.replace(/<br>/," ");
            nome_campo = nome_campo.replace(/<BR>/," ");

            erro += "- "+nome_campo+": valor inválido digitado. O valor do campo deve ser um número inteiro.";

            if(direcionar_aba == null)
                direcionar_aba = abas_campos[elemento.name];

            if(elemento_foco == "")
                elemento_foco = elemento;
            continue;

        }

        // Campos float
        if(elemento.value != "" && inArray(campos_float,elemento.name) && er_float.test(elemento.value) == true)
        {
            if(nomes_campos[elemento.name])
                nome_campo = nomes_campos[elemento.name];
            else
                nome_campo = elemento.name;

            if(erro != "")
                erro += "\n";

            nome_campo = nome_campo.replace(/<br>/," ");
            nome_campo = nome_campo.replace(/<BR>/," ");

            if(direcionar_aba == null)
                direcionar_aba = abas_campos[elemento.name];

            erro += "- "+nome_campo+": valor inválido digitado. O valor do campo deve ser numérico.";

            if(elemento_foco == "")
                elemento_foco = elemento;
            continue;

        }

        // Mínimo de caracteres
        if(minimo_caracteres_campos[elemento.name] && elemento.value.length < minimo_caracteres_campos[elemento.name])
        {
            if(nomes_campos[elemento.name])
                nome_campo = nomes_campos[elemento.name];
            else
                nome_campo = elemento.name;

            if(erro != "")
                erro += "\n";

            erro += "- "+nome_campo+": o campo deve conter no mínimo "+minimo_caracteres_campos[elemento.name]+" caracteres.";

            if(direcionar_aba == null)
                direcionar_aba = abas_campos[elemento.name];

            if(elemento_foco == "")
                elemento_foco = elemento;
            continue;

        }
	}

    if(erro == "")
    {
        return true;
    }
    else
    {
        alert(erro);
        try
        {
            if(tabPane1 && direcionar_aba != null)
                tabPane1.setSelectedIndex(direcionar_aba);
            elemento_foco.focus();
            elemento_foco.select();
        }
        catch(err)
        {

        }
        return false;
    }
}

///////////

function meio_largura(largura)
{ // Parâmetro: númerico, largura da janela pop-up
	var meia_janela = largura/2;
	tamanho_largura = screen.width/2;
	dist_lateral = (tamanho_largura) - meia_janela;
	return dist_lateral;
}

function meio_altura(altura)
{ // Parâmetro: númerico, Altura da janela pop-up
	var meia_janela = altura/2;
	tamanho_altura = screen.height/2;
	dist_topo = (tamanho_altura) - meia_janela;
	return dist_topo;
}

function pop_info()
{
	// Função para produtos passados por id no index (link no email)
	var largura 	= 450;
	var altura 		= 400;

	var esquerda	= meio_largura(largura);
	var topo 		= meio_altura(altura);

	window.open('http://www.maisempresas.com/pop_info.htm','pop_info','width='+largura+', height='+altura+', top='+topo+', left='+esquerda);
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function soNums(e,args)
	{
	// Função que permite apenas teclas numéricas e
	// todos os caracteres que estiverem na lista
	// de argumentos.
	// Deve ser chamada no evento onKeyPress desta forma
	//  onKeyPress ="return (soNums(event,'(/){,}.'));"
	// caso queira apenas permitir caracters

		if (document.all){var evt=event.keyCode;} // caso seja IE
		else{var evt = e.charCode;}	// do contrário deve ser Mozilla
		var chr= String.fromCharCode(evt);	// pegando a tecla digitada
		// Se o código for menor que 20 é porque deve ser caracteres de controle
		// ex.: <ENTER>, <TAB>, <BACKSPACE> portanto devemos permitir
		// as teclas numéricas vão de 48 a 57
		if (evt <20 || (evt >47 && evt<58) || (args.indexOf(chr)>-1 ) ){return true;}
		return false;
	}

function evita_letra(tecla)
{
     if (tecla.keyCode < 45 || tecla.keyCode > 57 || tecla.keyCode == 47 || tecla.keyCode == 45 || tecla.keyCode == 46)
          tecla.returnValue = false;
}
function FormataData(campo,formname,teclapres)
{ // Máscara para os campos de data
	var tecla = teclapres.keyCode;
	vr = document[formname][campo].value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	tam = vr.length + 1;

	if ( tecla != 9 && tecla != 8 )
	{
		if ( tam > 2 && tam < 5 )
			document[formname][campo].value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
		if ( tam >= 5 && tam <= 10 )
			document[formname][campo].value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 );
	}
}

function testa_data(dta, formname, campo)
{ // função complementar para testar a validade da data
	if(!isdate(dta))
	{
		alert('Digite uma data válida');
		document[formname][campo].value = '';
		document[formname][campo].focus();
		return false;
	}
}

//Verifica se uma data com mês e ano é válida
function isdate2(obj){
var mes, ano;
var retval = false;
ano=obj.substring(3,7);
//alert(obj);
if (obj != ""){
   if (obj.length != 7 || obj.substring(2,3)!="/") {
   		retval = false;
   }
   else {
      mes = obj.substring(0,2);
      if (nochars(mes) && parseInt(mes,10) > 0 && parseInt(mes,10) <= 12){
         mes = parseInt(mes,10);
         if (nochars(ano) && parseInt(ano,10) >= 0000) {
            if ((parseInt(ano,10) % 4) == 0) {
               bissexto = 1;
            }
            else {
               bissexto = 0;
            }
			retval = true;
         } else {
		 	retval = false;
		 }
      } else {
	  		retval = false;
	  }
   }
}
else {
     retval = true;
}
//alert(retval);
return retval;
}

function testa_hora(hora, formname, campo)
{ // função complementar para testar a validade da data
	if(!is_hora(hora))
	{
		alert('Digite uma hora válida');
		document[formname][campo].value = '';
		document[formname][campo].focus();
		return false;
	}
}

function is_hora(horas, formname, campo)
{
	var hora, minuto;
	var retval = false;
	hora = horas.substring(0,2);
	minuto = horas.substring(3,5)
	if(hora < 24 && minuto < 60)
		retval = true;

	return retval;
}

//Verifica se é uma data válida
function isdate(obj){
var mes, dia, ano;
var retval = false;
ano=obj.substring(6,10);
//alert(obj);
if (obj != ""){
   if (obj.length != 10 || obj.substring(2,3)!="/" || obj.substring(5,6)!="/") {
   }
   else {
      mes = obj.substring(3,5);
      if (nochars(mes) && parseInt(mes,10) > 0 && parseInt(mes,10) <= 12){
         mes = parseInt(mes,10);
         if (nochars(ano) && parseInt(ano,10) >= 0000) {
            if ((parseInt(ano,10) % 4) == 0) {
               bissexto = 1;
            }
            else {
               bissexto = 0;
            }
            dia = obj.substring(0,2);
            if (nochars(dia)){
               dia = parseInt(dia,10);
               if (((mes==1 || mes==3 || mes==5 || mes==7 || mes==8 || mes==10 || mes==12) && (dia >= 1 && dia <= 31)) ||
                  ((mes==4 || mes==6 || mes==9 || mes==11) && (dia >= 1 && dia <= 30)) ||
                  (mes==2 && dia >= 1 && dia <= (28 + bissexto))) {
                  retval=true;
               }
			   if(ano < 1900 || ano > 3000)
			   	retval=false;
            }
         }
      }
   }
}
else {
     retval = true;
}
//alert(retval);
return retval;
}

// Verifica se existem letras na variavel
function nochars(strval){
  var retval = true;
  for (var i = 0; i < strval.length; i++){
     if (strval.substring(i,i+1) < "0" || strval.substring(i,i+1) > "9"){
        retval=false;
        break;
     }
  }
  return retval;
}

function FormataHora(campo,formname,teclapres){
	var tecla = teclapres.keyCode;
	vr = document[formname][campo].value;
	vr = vr.replace( ":", "" );
	tam = vr.length + 1;

	if ( tecla != 9 && tecla != 8 ){
		if ( tam > 2 && tam < 5 ){
			document[formname][campo].value = vr.substr( 0, tam - 2  ) + ':' + vr.substr( tam - 2, tam );
		}
	}
}

function limpa_imagem(campo)
{
	if(confirm('Tem certeza que deseja apagar?'))
	{
		document.geral['valor['+campo+']'].value = '';
		document['apaga_foto['+campo+']'].style.visibility = 'hidden';
		document['apaga_foto['+campo+']'].width = '0';
		document['apaga_foto['+campo+']'].height = '0';

		document['foto['+campo+']'].style.visibility = 'hidden';
		document['foto['+campo+']'].width = '0';
		document['foto['+campo+']'].height = '0';

        // Ajuste para poder funcionar com a nova função de validação de formulários, após o usuário ter excluído a imagem/arquivo
        if(inArray(campos_obrigatorios,'valor['+campo+']'))
        {
            indice = indexOf(campos_obrigatorios,'valor['+campo+']');
            campos_obrigatorios[indice] = "campo_"+campo;
        }


		return;
	}
	else
		return;
}

function FormataLista(tecla)
{
	if (tecla.keyCode < 44 || tecla.keyCode > 57 || tecla.keyCode == 47 || tecla.keyCode == 45 || tecla.keyCode == 46)
     	tecla.returnValue = false;
}

function FormataValor(campo, formname) {
	var form = document[formname];
	form[campo].value = FiltraCampo(campo, formname);
	vr = form[campo].value;
	tam = vr.length;

	if ( tam <= 2 )
 		form[campo].value = vr ;
 	if ( (tam > 2) && (tam <= 5) )
 		form[campo].value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ;
 	if ( (tam >= 6) && (tam <= 8) )
 		form[campo].value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;
 	if ( (tam >= 9) && (tam <= 11) )
 		form[campo].value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;
 	if ( (tam >= 12) && (tam <= 14) )
 		form[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 - 2, tam ) ;
 	if ( (tam >= 15) && (tam <= 17) )
 		form[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 ) ;

}

function SaltaCampo(campo, formname, prox, tammax, event){
	var form = document[formname];
	var tecla = event.which;
	vr = form[campo].value;
	tam = vr.length;

 	if (tecla != 0 && tecla != 9 && tecla != 16 ){
		if (tam == tammax && prox && tammax){
			if (form[prox])
				form[prox].focus();
		}
	}

}

function SetHelp(txt) {
	document.getElementById('help').innerHTML = txt ;
}

function setHelp(current,e,text,posx,posy){
	SetHelp(text);
}

function FiltraCampo(campo, formname){
	var form = document[formname];
	var s = "";
	var cp = "";
	vr = form[campo].value;
	tam = vr.length;
	for (i = 0; i < tam ; i++) {
		if (vr.substring(i,i + 1) != "/" && vr.substring(i,i + 1) != "-" && vr.substring(i,i + 1) != "."  && vr.substring(i,i + 1) != "," ){
		 	s = s + vr.substring(i,i + 1);}
	}
	form[campo].value = s;
	return cp = form[campo].value
}
/*
function FiltraCampo(campo, formname){
	var form = document[formname];
	var s = "";
	var cp = "";
	vr = form[campo].value;
	tam = vr.length;
	for (i = 0; i < tam ; i++) {
		if (vr.substring(i,i + 1) != "/" && vr.substring(i,i + 1) != "-" && vr.substring(i,i + 1) != "."  && vr.substring(i,i + 1) != "," ){
		 	s = s + vr.substring(i,i + 1);}
	}
	form[campo].value = s;
	return cp = form[campo].value
}
*/
function Formata_num_virgula(tecla)
{
	if (tecla.keyCode < 44 || tecla.keyCode > 57 || tecla.keyCode == 47 || tecla.keyCode == 45 || tecla.keyCode == 46)
     	tecla.returnValue = false;
}

_editor_url = "htmlarea/";
var win_ie_ver = parseFloat(navigator.appVersion.split("MSIE")[1]);
if (navigator.userAgent.indexOf('Mac')        >= 0)
	win_ie_ver = 0;
if (navigator.userAgent.indexOf('Windows CE') >= 0)
	win_ie_ver = 0;
if (navigator.userAgent.indexOf('Opera')      >= 0)
	win_ie_ver = 0;
if (win_ie_ver >= 5.5)
{
  document.write('<scr' + 'ipt src="' +_editor_url+ 'editor.js"');
  document.write(' language="Javascript1.2"></scr' + 'ipt>');
}
else
	document.write('<scr'+'ipt>function editor_generate() { return false; }</scr'+'ipt>');

function troca_busca(per_id)
{
	window.opener.location = 'buscar.php?per='+per_id;
	window.opener.focus();
	this.close();
}

function faz_busca(per_id, cont_nome, cont_doc)
{
	var direciona ;

    if(per_id == "pessoa_fisica")
        arquivo = "listar_pf.php";
    else if(per_id == "pessoa_juridica")
        arquivo = "listar_pj.php";
    else
        arquivo = "listar.php";

    direciona = arquivo + '?per='+per_id+'&tembusca=true&chave_texto%5Badm_usuario.cont_nome%5D='+cont_nome+'&chave_texto%5Badm_usuario.cont_doc1%5D='+cont_doc;

	if(document.busca_rapida.popup.value)
	{
		window.opener.location = direciona;
		window.opener.focus();
		window.close();
	}
	else
		window.location = direciona;
}

function valida_busca_rapida(dados)
{
	if(!dados.cli_tipo.value)
    	dados.cli_tipo.value = dados.per.value;

    if(!dados.cli_tipo.value)
	{
		alert('Antes de buscar,\nselecione o tipo de pessoa.');
		dados.cli_tipo.focus();
		return false;
	}
	if(!dados.cont_nome.value && !dados.cont_doc.value)
	{
		alert('Digite uma palavra chave\npara o nome ou documento.');
		dados.cont_nome.focus();
		return false;
	}

	faz_busca(dados.cli_tipo.value, dados.cont_nome.value, dados.cont_doc.value);
	return false;
}

function verifica_marcado()
{
	var marca = false
	if(document.lista['del_item[]']){
		var len = document.lista['del_item[]'].length;
		if(len){
		    for(i = 0; i< len; i++){
		        if(document.lista['del_item[]'][i].checked == true) marca = true;
			}
		}else{
			if(document.lista['del_item[]'].checked == true) marca = true;
		}
	}
	return marca;
}

function verifica_marcado_pasta()
{
	var marca = false
	if(document.lista['del_pasta[]']){
		var len = document.lista['del_pasta[]'].length;
		if(len){
		    for(i = 0; i< len; i++){
		        if(document.lista['del_pasta[]'][i].checked == true) marca = true;
			}
		}else{
			if(document.lista['del_pasta[]'].checked == true) marca = true;
		}
	}
	return marca;
}

function abre_mover(usr,pasta,pm)
{
	if(!pm) pm = false;
	if((verifica_marcado()) || (pm)){
		var largura 	= 450;
		var altura 		= 500;

		var esquerda	= meio_largura(largura);
		var topo 		= meio_altura(altura);
		window.open('obj_mover.php?usr_id='+usr+'&pasta='+pasta, 'mover_arquivos','width='+largura+', height='+altura+', resizable=yes, top='+topo+', left='+esquerda);
	}else{
		alert('Você precisa selecionar pelo menos 1 arquivo para executar esta operação!')
	}
}

function apagar_arquivos(pm)
{
	if(!pm) pm = false;
	if((verifica_marcado()) || (verifica_marcado_pasta())  || (pm)){
		if(confirm('Tem certeza que você deseja apagar este(s) registro(s) DEFINITIVAMENTE? ')){
			document.lista['acao'].value = 'apagar';
			document.lista.submit();
		}
	}else{
		alert('Você precisa selecionar pelo menos 1 arquivo/pasta para executar esta operação!')
	}
}

function obj_propriedades(id,usr)
{
	var largura 	= 740;
	var altura 		= 380;

	var esquerda	= meio_largura(largura);
	var topo 		= meio_altura(altura);
	var janela = window.open('obj_propriedades.php?obj_id='+id+'&usr_id='+usr, 'propriedades_obj','width='+largura+', height='+altura+', scrollbars=1, resizable=no, top='+topo+', left='+esquerda);
	janela.onunload = function(){ window.location.reload()};
}

var marked_row = new Array;

function troca_cor(id, red, green, blue)
{
	var teste = document.getElementById(id);
	var currentColor = 'rgb('+red+','+green+','+blue+')';

	var rgbStr = currentColor.slice(currentColor.indexOf('(') + 1, currentColor.indexOf(')'));
    var rgbValues = rgbStr.split(",");
    currentColor = "#";
    var hexChars = "0123456789ABCDEF";
    for (var i = 0; i < 3; i++)
    {
    	var v = rgbValues[i].valueOf();
        currentColor += hexChars.charAt(v/16) + hexChars.charAt(v%16);
	}

	teste.style['background'] = currentColor;
}

function verifica_dono(usr)
{
	var ver = '';
	if(document.lista['del_item[]'].length){
		for(var i=0; i<document.lista['del_item[]'].length; i++)
		{
			if(document.lista['del_item[]'][i].checked == true){
				if((document.lista['dono[]'][i].value != usr) && (document.lista['uploader[]'][i].value != usr)){
					ver = 'none';
					document.lista['del_item[]'][i].checked = false
				}
			}
		}
	}else{
		if(document.lista['del_item[]'].checked == true){
			if((document.lista['dono[]'].value != usr) && (document.lista['uploader[]'].value != usr)){
				ver = 'none';
				document.lista['del_item[]'].checked = false
			}
		}
	}
	if(ver == 'none') alert('Atenção: Você não tem permissão para mover e/ou apagar este arquivo.');
//	document.getElementById('bt_mover').style.display = ver;
//	document.getElementById('bt_apagar').style.display = ver;
}

///////// importado do phpmyadmin ///////////////
function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor)
{
    var theCells = null;

    // 1. Pointer and mark feature are disabled or the browser can't get the
    //    row -> exits
    if ((thePointerColor == '' && theMarkColor == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }

    // 2. Gets the current row and exits if the browser can't get it
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }

    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"
    if (typeof(window.opera) == 'undefined'
        && typeof(theCells[0].getAttribute) != 'undefined') {
        currentColor = theCells[0].getAttribute('bgcolor');
        domDetect    = true;
    }
    // 3.2 ... with other browsers
    else {
        currentColor = theCells[0].style.backgroundColor;
        domDetect    = false;
    } // end 3

	// 3.3 ... Opera changes colors set via HTML to rgb(r,g,b) format so fix it
	if (currentColor.indexOf("rgb") >= 0)
	{
		var rgbStr = currentColor.slice(currentColor.indexOf('(') + 1,
                                     currentColor.indexOf(')'));
        var rgbValues = rgbStr.split(",");
        currentColor = "#";
        var hexChars = "0123456789ABCDEF";
        for (var i = 0; i < 3; i++)
        {
            var v = rgbValues[i].valueOf();
            currentColor += hexChars.charAt(v/16) + hexChars.charAt(v%16);
        }
    }

    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentColor == ''
        || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        if (theAction == 'over' && thePointerColor != '') {
            newColor              = thePointerColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
            // Garvin: deactivated onclick marking of the checkbox because it's also executed
            // when an action (like edit/delete) on a single item is performed. Then the checkbox
            // would get deactived, even though we need it activated. Maybe there is a way
            // to detect if the row was clicked, and not an item therein...
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = true;
        }
    }
    // 4.1.2 Current color is the pointer one
    else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()
             && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
        if (theAction == 'out') {
            newColor              = theDefaultColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = true;
        }
    }
    // 4.1.3 Current color is the marker one
    else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        if (theAction == 'click') {
            newColor              = (thePointerColor != '')
                                  ? thePointerColor
                                  : theDefaultColor;
            marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
                                  ? true
                                  : null;
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = false;
        }
    } // end 4

    // 5. Sets the new color...
    if (newColor) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].setAttribute('bgcolor', newColor, 0);
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].style.backgroundColor = newColor;
            }
        }
    } // end 5

    return true;
} // end of the 'setPointer()' function

// Falta terminar
function redimensionaAnimado(id,wfinal,hfinal,tempo)
{
    obj = document.getElementById(id);

    /*for(cont = 0; cont != )
    {

    }*/
}

function mostra(id)
{
    document.getElementById(id).style.display = "block";
}

function some(id)
{
    document.getElementById(id).style.display = "none";
}

function visivel(id)
{
    if(document.getElementById(id).style.display == "block")
        return true;
    else
        return false;
}

function aviso()
{
		var largura 	= 450;
		var altura 		= 203;

		var esquerda	= meio_largura(largura);
		var topo 		= meio_altura(altura);
		window.open('aviso.php', 'pop_aviso','width='+largura+', height='+altura+', resizable=no, status= yes, top='+topo+', left='+esquerda);
}

/*|---------------------------------->>  <<----------------------------------|

	 						   USUARIOS ON-LINE

|---------------------------------->>  <<----------------------------------|*/
function online()
{
		var largura 	= 360;
		var altura 		= 400;

		var esquerda	= meio_largura(largura);
		var topo 		= meio_altura(altura);
		window.open('online.php', 'pop_online','width='+largura+', height='+altura+', resizable=no, status= yes, top='+topo+', left='+esquerda);
}

/*|---------------------------------->>  <<----------------------------------|

					PREENCHE SELECT DE CONTATOS DO ATENDIMENTO

|---------------------------------->>  <<----------------------------------|*/

function preenche_contatos(dados){
	x = dados.split(',');
	//var contas = document.geral['valor[cont_id]'];
	var contas = document.getElementById("select_contatos");
	contas.options[0] = new Option('Não especificado ou desconhecido','')
	if(x.length > 1){
		for(a=0; a< x.length-1; a++){
			if(x[a]){
				info = x[a].split('|');
				contas.options[a+1] = new Option(info[1],info[0]);
			}
		}
		contas.disabled = '';
	}else{
		contas.options.length = 0;
		contas.options[0] = new Option('Não especificado ou desconhecido','')
	}
}
var req;

function carrega_contatos(valor,per,per_pai)
{
    req = null;
	document.getElementById("select_contatos").disabled = (valor)?'disabled':'';
	var contas = document.getElementById("select_contatos");
	contas.options.length = 0;
	contas.options[0] = new Option('Aguarde o carregamento...');
	contas.disabled = 'disabled';
	if(valor){
		url = 'atendimento_carrega_contatos.php?per='+per+'&id_pai='+valor+'&per_pai='+per_pai;
	    if (window.XMLHttpRequest) {
	        req = new XMLHttpRequest();
	        req.onreadystatechange = processReqChange;
	        req.open("GET", url, true);
	        req.send(null);
	    } else if (window.ActiveXObject) {
	        req = new ActiveXObject("Microsoft.XMLHTTP");
	        if (req) {
	            req.onreadystatechange = processReqChange;
	            req.open("GET", url, true);
	            req.send();
	        }
	    }
	}else{
		contas.options.length = 0;
		contas.options[0] = new Option('Não especificado ou desconhecido')
	}
}

function processReqChange()
{
    if (req.readyState == 4) {
        if (req.status == 200) {
            preenche_contatos(req.responseText);
        } else {
            alert("Houve um problema ao obter os dados:\n" + req.statusText);
        }
    }
}

/*|---------------------------------->>  <<----------------------------------|

  								R E M I N D E R

|---------------------------------->>  <<----------------------------------|*/
function carrega_reminder(doc){
	if (document.implementation && document.implementation.createDocument){
		xmlDoc = document.implementation.createDocument("", "", null);
		xmlDoc.onload = verifica_reminder;
	}else if (window.ActiveXObject){
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.onreadystatechange = function () {
			if (xmlDoc.readyState == 4){
//				if (xmlDoc.status == 200){
					verifica_reminder()
//				}
			}
		};
 	}else{
		alert('Atenção: para utilizar todos os recursos deste sistema, \n recomendamos que atualize seu navegador.');
		return;
	}
	xmlDoc.load(doc);
}

function abre_agenda_usr(form, campo, data,usr)
{
	if(!data.value)
	{
		alert('Antes, digite um dia.');
		data.focus();
		return false;
	}
	else
	{
		var largura 	= 400;
		var altura 		= 390;

		var esquerda	= meio_largura(largura);
		var topo 		= meio_altura(altura);

		window.open('pop_agenda.php?form='+form+'&campo='+campo+'&data='+data.value+'&usr_id='+usr,'agenda','width='+largura+', height='+altura+', top='+topo+', left='+esquerda);
	}
}

function abre_popup(end,altura,largura)
{
	var esquerda	= meio_largura(largura);
	var topo 		= meio_altura(altura);

	window.open(end,'galeria','width='+largura+', height='+altura+', top='+topo+', left='+esquerda);
	void(0);
}

/*|---------------------------------->>  <<----------------------------------|

  								M E N S A G E M

|---------------------------------->>  <<----------------------------------|*/
function anexar_arquivos()
{
    if(top.window.opener.id_div_anexos)
	    id_div_anexos = top.window.opener.id_div_anexos;
	else
	    id_div_anexos = 'anexos';

	if(document.lista['del_item[]']){
		var len = document.lista['del_item[]'].length;
		if(len){
		    for(i = 0; i< len; i++){
		        if(document.lista['del_item[]'][i].checked == true)
		            top.window.opener.document.getElementById(id_div_anexos).innerHTML +=  '<div class="mensagemtxt2" id="div'+document.lista['del_item[]'][i].value+'">'+document.lista['nome[]'][i].value+'<input name="arquivo[]" value="'+document.lista['del_item[]'][i].value+'" type="hidden" /><input name="arquivo_caminho[]" value="'+document.lista['nome[]'][i].value+'" type="hidden" />&nbsp;<a href="javascript:apaga_anexo(\''+document.lista['nome[]'][i].value+'\',\''+document.lista['del_item[]'][i].value+'\')" class="fontep">[Excluir]</a></div>';
			}
		}else{
			if(document.lista['del_item[]'].checked == true)
			    top.window.opener.document.getElementById(id_div_anexos).innerHTML +=  '<div class="mensagemtxt2" id="div'+document.lista['del_item[]'].value+'">'+document.lista['nome[]'].value+'<input name="arquivo[]" value="'+document.lista['del_item[]'].value+'" type="hidden" /><input name="arquivo_caminho[]" value="'+document.lista['nome[]'].value+'" type="hidden" />&nbsp;<a href="javascript:apaga_anexo(\''+document.lista['nome[]'].value+'\',\''+document.lista['del_item[]'].value+'\')" class="fontep">[Excluir]</a></div>';
		}
	}
	if(confirm('Inseridos com sucesso, deseja fechar esta janela?')){
		top.window.close();
	}
}

function apaga_anexo(lb,id){
    if(!id_div_anexos)
	    id_div_anexos = 'anexos';

	var tmp = document.getElementById(id_div_anexos).innerHTML;
	var inicio = tmp.toLowerCase().indexOf('<div class="mensagemtxt2" id="div'+id+'">');
	if(inicio == -1) inicio = tmp.toLowerCase().indexOf('<div class=mensagemtxt2 id=div'+id+'>');
	var sfinal = tmp.substring(0,inicio);
	var tmp_f = tmp.substring(inicio);
	sfinal += tmp_f.substring(tmp_f.toLowerCase().indexOf('</div>')+6)
	document.getElementById(id_div_anexos).innerHTML = sfinal;
}

function anexar_contatos()
{
	if(document.geral['select_usr[]']){
		var len = document.geral['select_usr[]'].length;
		if(len){
		    for(i = 0; i< len; i++){
		        if(document.geral['select_usr[]'][i].checked == true)
					window.opener.document.getElementById('destinatarios').innerHTML += '<div class="usuarios" id="div'+document.geral['select_usr[]'][i].value+'">'+document.geral['select_nome[]'][i].value+'<input name="contato[]" value="'+document.geral['select_usr[]'][i].value+'" type="hidden" />&nbsp;<a href="javascript:apaga_contato(\''+document.geral['select_nome[]'][i].value+'\',\''+document.geral['select_usr[]'][i].value+'\')" class="fontep">[Excluir]</a></div>';
			}
		}else{
			if(document.geral['select_usr[]'].checked == true) window.opener.document.getElementById('destinatarios').innerHTML +=  '<div class="usuarios" id="div'+document.geral['select_usr[]'].value+'">'+document.geral['select_nome[]'].value+'<input name="contato[]" value="'+document.geral['select_usr[]'].value+'" type="hidden" />&nbsp;<a href="javascript:apaga_contato(\''+document.geral['select_nome[]'].value+'\',\''+document.geral['select_usr[]'].value+'\')" class="fontep">[Excluir]</a></div>';
		}
	}
	window.close()
}

function apaga_contato(lb,id){
	var tmp = document.getElementById('destinatarios').innerHTML;
	var inicio = tmp.toLowerCase().indexOf('<div class="usuarios" id="div'+id+'">');
	if(inicio == -1) inicio = tmp.toLowerCase().indexOf('<div class=usuarios id=div'+id+'>');
	var sfinal = tmp.substring(0,inicio);
	var tmp_f = tmp.substring(inicio);
	sfinal += tmp_f.substring(tmp_f.toLowerCase().indexOf('</div>')+6)
	document.getElementById('destinatarios').innerHTML = sfinal;
}

function valida_mensagem(){
	//document.getElementById('noise').value = document.getElementById('noiseWidgIframe').contentWindow.document.getElementsByTagName("body")[0].innerHTML;
	var dest = document.getElementById('destinatarios').innerHTML;
	var estado = false;
	if((dest.length > 15) || (document.mensagem.destinos.value)){
		estado = true
	}else{
		alert('Selecione pelo menos 1(um) destinatário para a mensagem.')
		estado = false
	}
	if((!document.mensagem.assunto.value) && (estado)){
		alert('A mensagem deve possuir um assunto para ser enviada.')
		estado = false
	}
	if(estado)document.mensagem.submit()
	return false;
}

function msg_verifica_marcado()
{
	var marca = false
	if(document.lista['mensagem[]']){
		var len = document.lista['mensagem[]'].length;
		if(len){
		    for(i = 0; i< len; i++){
		        if(document.lista['mensagem[]'][i].checked == true) marca = true;
			}
		}else{
			if(document.lista['mensagem[]'].checked == true) marca = true;
		}
	}
	return marca;
}
function apagar_mensagens()
{
	if(msg_verifica_marcado()){
		if(confirm('Tem certeza que você deseja apagar esta(s) mensagem(ns)?')){
			document.lista['acao'].value = 'apagar';
			document.lista.submit();
		}
	}else{
		alert('Você precisa selecionar pelo menos 1 arquivo para executar esta operação!')
	}
}
function restaurar_mensagens()
{
	if(msg_verifica_marcado()){
		if(confirm('Tem certeza que você deseja restaurar esta(s) mensagem(ns)?')){
			document.lista['acao'].value = 'restaurar';
			document.lista.submit();
		}
	}else{
		alert('Você precisa selecionar pelo menos 1 arquivo para executar esta operação!')
	}
}

function msg_troca_todos(tf)
{
	if(tf.checked)
		var flag = true;
	else
		var flag = false;
	ToggleAll('lista', 'mensagem[]', flag);
}

function msg_abre_mover(pasta)
{
	if(msg_verifica_marcado()){
		var largura 	= 450;
		var altura 		= 380;

		var esquerda	= meio_largura(largura);
		var topo 		= meio_altura(altura);
		window.open('mensagem_mover.php?pasta='+pasta, 'mover_mensagens','width='+largura+', height='+altura+', resizable=yes, top='+topo+', left='+esquerda);
	}else{
		alert('Você precisa selecionar pelo menos 1 mensagem para executar esta operação!')
	}
}
function matar_mensagens()
{
	if(msg_verifica_marcado()){
		if(confirm('Tem certeza que você deseja APAGAR DEFINITIVAMENTE esta(s) mensagem(ns)?')){
			document.lista['acao'].value = 'acabar';
			document.lista.submit();
		}
	}else{
		alert('Você precisa selecionar pelo menos 1 arquivo para executar esta operação!')
	}
}
function lidas()
{
	if(msg_verifica_marcado()){
		document.lista['acao'].value = 'lida';
		document.lista.submit();
	}else{
		alert('Você precisa selecionar pelo menos 1 arquivo para executar esta operação!')
	}
}

function enviar_arquivos()
{
	if(verifica_marcado()){
		var largura 	= 600;
		var altura 		= 420;

		var esquerda	= meio_largura(largura);
		var topo 		= meio_altura(altura);

		var janela = window.open('pop_mensagem_escrever.php?assunto=Enviando Arquivos&mensa=Arquivos prontos para ser enviados.', 'msgarq', 'scrollbars=yes, width='+largura+', height='+altura+', top='+topo+', status = yes, resizable=yes, left='+esquerda);
	}else{
		alert('Você precisa selecionar pelo menos 1 arquivo para executar esta operação!')
	}
}
function carrega_no_ie(){
	//carrega
	if(window.opener){
		var len = window.opener.document.lista['del_item[]'].length;
		if(len){
			for(i = 0; i< len; i++){
				if(window.opener.document.lista['del_item[]'][i].checked == true)document.getElementById('anexos').innerHTML +=  '<div class="mensagemtxt2" id="div'+window.opener.document.lista['del_item[]'][i].value+'">'+window.opener.document.lista['nome[]'][i].value+'<input name="arquivo[]" value="'+window.opener.document.lista['del_item[]'][i].value+'" type="hidden" /><input name="arquivo_caminho[]" value="'+window.opener.document.lista['nome[]'][i].value+'" type="hidden" />&nbsp;<a href="javascript:apaga_anexo(\''+window.opener.document.lista['nome[]'][i].value+'\',\''+window.opener.document.lista['del_item[]'][i].value+'\')" class="fontep">[Excluir]</a></div>';
			}
		}else{
			if(window.opener.document.lista['del_item[]'].checked == true) document.getElementById('anexos').innerHTML +=  '<div class="mensagemtxt2" id="div'+window.opener.document.lista['del_item[]'].value+'">'+window.opener.document.lista['nome[]'].value+'<input name="arquivo[]" value="'+window.opener.document.lista['del_item[]'].value+'" type="hidden" /><input name="arquivo_caminho[]" value="'+window.opener.document.lista['nome[]'].value+'" type="hidden" />&nbsp;<a href="javascript:apaga_anexo(\''+window.opener.document.lista['nome[]'].value+'\',\''+window.opener.document.lista['del_item[]'].value+'\')" class="fontep">[Excluir]</a></div>';
		}
		// desmarca
		if(len){
			for(i = 0; i< len; i++){
				window.opener.document.lista['del_item[]'][i].checked = false;
			}
		}else{
			window.opener.document.lista['del_item[]'].checked = false;
		}
		window.opener.document.lista['marca_todos[]'][0].checked = false;
		window.opener.document.lista['marca_todos[]'][1].checked = false;
	}
}

/**
 * Mostra tela de "carregando"...
 */
function mostraLoading()
{
    if(document.getElementById('div_loading'))
    {
        if(document.all)
        {
            for(cont = 0; cont < document.geral.elements.length ; cont++)
            {
                if(document.geral.elements[cont].type == "select-one")
                    document.geral.elements[cont].style.visibility   = "hidden";
            }
        }

        document.getElementById('principal').style.zIndex = -20;
        document.getElementById('div_loading').style.display = "block";
        document.getElementById('div_loading').style.height = "1000";
        window.scrollTo(0,0);
    }

    return true;
}

/**
 * Limpa a tela de "carregando..."
 */
function limpaLoading(janela)
{
    janela.document.getElementById('div_loading').style.display = "none";
    janela.document.getElementById('div_loading').innerHTML = "";
}

/**
 * Oculta tela de "carregando" para o caso de erro
 */
function ocultaLoading(janela)
{
    if(janela.document.getElementById('div_loading'))
    {
        if(document.all)
        {
            for(cont = 0; cont < janela.document.geral.elements.length ; cont++)
            {
                if(janela.document.geral.elements[cont].type == "select-one")
                    janela.document.geral.elements[cont].style.visibility   = "visible";
            }
        }

        janela.document.getElementById('principal').style.zIndex = -20;
        janela.document.getElementById('div_loading').style.display = "none";
        window.scrollTo(0,0);
    }

    return true;
}

function mudaClasseCss(obj,classe)
{
    obj.className = classe;
}

function confirma_atualizacao_dv(form)
{
    if(form.cota_atualiza.value == "" || form.cota_atualiza.value == undefined)
    {
        alert('Digite um valor em megabytes para definir as cotas.');
        form.cota_atualiza.focus();
        return false;
    }
    else
    {
        return confirm("Isso irá atualizar todas as cotas selecionados pela busca para "+form.cota_atualiza.value+"Mb. Tem certeza?");
    }
}

function mostra_detalhes(id)
{
	var largura 	= 100;
	var altura 		= 100;

	var esquerda	= meio_largura(largura);
	var topo 		= meio_altura(altura);
	var janela = window.open('ext_propriedades.php?img='+id, 'visualizar','width='+largura+', height='+altura+', resizable=yes, top='+topo+', left='+esquerda);
}

function addEvent(obj, evType, fn){
    if (obj.addEventListener)
        obj.addEventListener(evType, fn, true)
    if (obj.attachEvent)
        obj.attachEvent("on"+evType, fn)
}

function obrigatorio(campo,label)
{
    nomes_campos[campo] = label;
    return campos_obrigatorios.push(campo);
}

function atualizaChaveEstrangeira(per_id, campo, id_campo, tamanho_max, classe, attrs)
{
    $(id_campo).innerHTML = "Atualizando...";
    //alert('per_id: ' + per_id + ", campo: " + campo + ", id_campo: " + id_campo);
    setTimeout('xajax_atualizaChaveEstrangeira(' + per_id + ',"' + campo + '","' + id_campo + '","' + tamanho_max + '","' + classe + '","' + escape(attrs) + '")',0); // O settimeou é pra resolver um bug do XMLHttpRequest do Firefox
}

function agenda_atualizacao(link_janela,funcao)
{
	var largura 	= 793;
	var altura 		= 500;

	var esquerda	= meio_largura(largura);
	var topo 		= meio_altura(altura);

	// a variável janela não está sendo utilizada. para utilizar, trocar o _blank por ela.
	janela = window.acoes.window.open(link_janela + '&pop=1', '_blank', 'scrollbars=yes, width='+largura+', height='+altura+', top='+topo+', resizable=yes, left='+esquerda);

    if(!document.all) // Para browsers
    {
        janela.onload = function ()
        {
            addEvent(janela, "unload", funcao);
        }
    }
    else // Para I.E.
        addEvent(janela, "unload", funcao);
}

function desabilitarMenu()
{
    return false;
}

function menuColunasListagem(id_menu,mostra,evento)
{
    if(!mostraMenuCamposListagem)
        return false;

    document.oncontextmenu = desabilitarMenu    ;

    if(mostra == true)
        mostra = "block";
    else
        mostra = "none";

    for(cont = 0 ; $("menu_listagem"+cont);cont++)
        $("menu_listagem"+cont).style.display = "none";

    if(navigator.appName == 'Netscape')
        diferenca = 280;
    else
        diferenca = 280;

    //$(id_menu).style.top        = "0px";//(screen.height + evento.clientY)+"px";
    $(id_menu).style.left       = ( evento.clientX-diferenca)+"px";
    $(id_menu).style.display    = mostra;

    setTimeout('document.oncontextmenu = false',1000);
}

function confirmaSelecaoColunasListagem(array_campos)
{
    marcados    = 0;
    campos      = "";

    campos_considerados = new Array();

    for(cont=0 ; cont < array_campos.length ; cont++)
    {
        if(inArray(campos_considerados,array_campos[cont].value))
            continue;
        else
            campos_considerados[cont] = array_campos[cont].value;

        if(array_campos[cont].checked == true)
        {
            marcados++;
            campos += array_campos[cont].value + ",";
        }
    }

    if(marcados == 0)
    {
        alert('É necessário escolher pelo menos um campo.');
        return false;
    }


    endereco = window.location.href.replace(/&_colunas_selecionadas=[^&]*&/,"&")+"&_colunas_selecionadas="+escape(campos);

    window.location.href = endereco;

    return true;
}

/**
 * Chama a função de validação de formulários e o submete
 */
function validacao_tela_form(form)
{
    if(valida_dinamico2(form)==true)
    {
        form.submit();
        mostraLoading();
    }
    return false;
}

/////////// Respostas de atendimentos

/**
 * Abre o formulário de resposta de atendimento
 */
function abre_resposta_attend(id)
{
    $("box_resposta_"+id).innerHTML = "<form name='form_resposta_"+id+"' id='form_resposta_"+id+"' enctype='multipart/form-data' action='recebe_arquivo_ajax.php'><input type='hidden' name='valor[atend_id]' value='"+id+"'>"+$('form_resposta_atendimento').innerHTML.replace(/%atend_id%/g,id)+"</form><div id='div_carregando_"+id+"' style='display:none;padding:10px;'>Enviando...</div>";
    $("btn_enviar_"+id).focus();

    $("texto_resposta_"+id).value = "\n\n" + $("texto_resposta_"+id).value
    $("texto_resposta_"+id).focus();

    // Coloca o cursor no início do campo
    $("texto_resposta_"+id).selectionStart = 0;
    $("texto_resposta_"+id).selectionEnd = 0;
}

function fecha_resposta_attend(id)
{
    $("box_resposta_"+id).innerHTML = "";
}
var atend_id_atual = "";
function pegaAnexoEnviaFormAtendimento(resposta)
{
    alert(resposta);
    //enviar_form_resposta_atend(eval("document.form_resposta_" + atend_id_atual));
}

function inicioEnvioFormAjaxAtendimento()
{

}

function enviar_form_resposta_atend(form)
{
    $(form.id).style.display = "none";
    $('div_carregando_'+form['valor[atend_id]'].value).style.display = "block";

    xajax_grava_resposta_atendimento(xajax.getFormValues(form.id));
}

function mostra_respostas_atend(id)
{
    $('atend_view_respostas_'+id).innerHTML += "<br>Carregando...<br>";
    xajax_carrega_respostas_atendimento(id);
}

function esconde_respostas_atend(id,num_respostas)
{
    $('atend_view_respostas_'+id).innerHTML = '<div class="atendimento_botoes" id="'+id+'">	<a href="javascript:mostra_respostas_atend('+id+')"><img src="images/ico_atendimento_lupa.gif" width="13" height="12" align="absmiddle" border="0"> ' + num_respostas + ' Resposta'+(num_respostas > 1 ? 's' : '')+'</a> <a href="javascript:abre_resposta_attend(\''+id+'\')"><img src="images/btn_atalhos_adicionar_resposta.gif" width="116" height="14" hspace="15" border="0" align="absmiddle"></a>  </div>';
}

//////////////////////////////////////////

function envia_gravar_listagem(form)
{
    if(form['_salvar_list_titulo'].value == '')
    {
        alert('É necessário digitar um título para a listagem');
        form['_salvar_list_titulo'].focus();

    }
    else
        xajax_salvaListagem(form['_salvar_list_uri'].value,form['_salvar_list_titulo'].value);
}

function busca_telefones()
{
	var largura 	= 600;
	var altura 		= 420;

	var esquerda	= meio_largura(largura);
	var topo 		= meio_altura(altura);

	window.open('pop_busca_telefones.php', 'busca_telefones', 'width='+largura+', height='+altura+', top='+topo+', left='+esquerda+',scrollbars=yes');
}

///////////////// Chave suggest

var requisicoes_suggest   = new Array();
function oculta_suggest(nome_campo)
{
    requisicoes_suggest.splice(0,requisicoes_suggest.length);
	$('chave_suggest_bloco_' + nome_campo).innerHTML        = "";
	$('chave_suggest_bloco_' + nome_campo).style.display    = "none";

    if($('chave_suggest_iframe_' + nome_campo))
        $('chave_suggest_iframe_' + nome_campo).style.display = "none";
}

function seleciona_pai_suggest(id_linha, nome_campo, titulo)
{
    $("chave_suggest_" + nome_campo + "_hidden").value  = id_linha;
    $("chave_suggest_titulo_" + nome_campo).value       = titulo;
    $("chave_suggest_" + nome_campo).value              = titulo;

    $("chave_suggest_" + nome_campo).select();

    if($("chave_suggest_" + nome_campo + "_hidden").onchange)
        $("chave_suggest_" + nome_campo + "_hidden").onchange();

    oculta_suggest(nome_campo);
}

var dados_chave_suggest   = new Array();
var titulos_chave_suggest = new Array();
var data_suggest = new Date();
function mostra_suggest(campo, requisicao)
{
    if(inArray(requisicoes_suggest, requisicao))
    {
        if(dados_chave_suggest.length > 0)
        {
            conteudo = "<ul>";

            for(i = 0 ; i < dados_chave_suggest.length ; i++)
            {
                conteudo += "<li><a href='#' onmousedown='seleciona_pai_suggest(" + dados_chave_suggest[i] + ",\"" + campo + "\",\"" + titulos_chave_suggest[i] + "\")'>" + titulos_chave_suggest[i] + "</a></li>";
            }

            conteudo += "</ul>";
        }
        else
            conteudo = "Nenhum resultado encontrado.";

        requisicoes_suggest.splice(indexOf(requisicoes_suggest.requisicao),1);

    	$('chave_suggest_bloco_' + campo).innerHTML        = conteudo;

    	if(document.all) // Se for Internet Explorer usa um iframe pra permitir o div passar por cima de <select>
    	{
    	    if(!$('chave_suggest_iframe_' + campo))
    	        $('chave_suggest_bloco_' + campo).insertAdjacentHTML("afterEnd",'<IFRAME id="chave_suggest_iframe_' + campo + '" style="DISPLAY: none; LEFT: 0px; POSITION: absolute; TOP: 0px" src="javascript:false;" frameBorder="0" scrolling="no"></IFRAME>');

    	    iframe                  = $('chave_suggest_iframe_' + campo);
            iframe.style.top        = $('chave_suggest_bloco_' + campo).style.top;
            iframe.style.left       = $('chave_suggest_bloco_' + campo).style.left;
            iframe.style.width      = $('chave_suggest_bloco_' + campo).style.width;
            iframe.style.height     = (dados_chave_suggest.length * 18) + 10;
            iframe.style.zIndex     = 19;
            iframe.style.display    = "inline";

    	}

    	$('chave_suggest_bloco_' + campo).style.display    = "block";
    }
}

function busca_suggest(per, campo, valor)
{
    //$('chave_suggest_bloco_'+campo).innerHTML = '';
    tempo = data_suggest.getTime();
    requisicoes_suggest.push(tempo);
    xajax_busca_chave_suggest(valor,campo,per,tempo);
}

function busca_suggest_clientes(per, campo, valor)
{
    //$('chave_suggest_bloco_'+campo).innerHTML = '';
    tempo = data_suggest.getTime();
    requisicoes_suggest.push(tempo);
    xajax_busca_chave_suggest_clientes(valor,campo,per,tempo);
}

///////////////////////////////////

/**
*
*  AJAX IFRAME METHOD (AIM)
*  http://www.webtoolkit.info/
*
*/
AIM = {

    frame : function(c) {

        var n = 'f' + Math.floor(Math.random() * 99999);
        var d = document.createElement('DIV');
        d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
        document.body.appendChild(d);

        var i = document.getElementById(n);
        if (c && typeof(c.onComplete) == 'function') {
            i.onComplete = c.onComplete;
        }

        return n;
    },

    form : function(f, name) {
        f.setAttribute('target', name);
    },

    submit : function(f, c) {
        AIM.form(f, AIM.frame(c));
        if (c && typeof(c.onStart) == 'function') {
            return c.onStart();
        } else {
            return true;
        }
    },

    loaded : function(id) {
        var i = document.getElementById(id);
        if (i.contentDocument) {
            var d = i.contentDocument;
        } else if (i.contentWindow) {
            var d = i.contentWindow.document;
        } else {
            var d = window.frames[id].document;
        }
        if (d.location.href == "about:blank") {
            return;
        }

        if (typeof(i.onComplete) == 'function') {
            i.onComplete(d.body.innerHTML);
        }
    }

}

///////////////////////////////////////////

function sortlist(lb)
{
    arrTexts    = new Array();
    arrValues   = new Array();

    for(i=0; i<lb.length; i++)
    {
        arrTexts[i]     = lb.options[i].text;
        arrValues[i]    = lb.options[i].value;
    }

    arrTexts.sort();

    for(i=0; i<lb.length; i++)
    {
        lb.options[i].text  = arrTexts[i];
        lb.options[i].value = arrValues[i];
    }
}

function visualizarImpressao()
{
	try
	{
		 var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
		 document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
		 WebBrowser1.ExecWB( 7, 1 );
		 WebBrowser1.outerHTML = "";
	}
	catch(e)
	{
		alert("Para visualizar a impressão você precisa habilitar o uso de controles ActiveX na página.");
		return;
	}
}

// Menu de acesso rapido
function menu_rapido()
{
    if($('menu_rapido_crm').style.display != "block")
    {
        $('menu_rapido_crm').style.display  = "block";
        $('menu_rapido_crm').innerHTML      = "<br><img src='images/loading.gif' border='0' align='absmiddle'> Carregando...";
        xajax_carregaMenuRapido();
    }
    else
    {
        $('menu_rapido_crm').style.display  = "none";
    }
}

//Devolve X, Y em relação a janela do documento
function getAbsolutePosition(element) {
	var r = { x: element.offsetLeft, y: element.offsetTop };
	if (element.offsetParent) {
		var tmp = getAbsolutePosition(element.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
}

function getElementsByClassName(strClass)
{
	var ret = new Array();
	var tag = arguments[1] || "*";
	var node = arguments[2] || document;
	var base = node.getElementsByTagName(tag);
	var tBase = base.length;
	for(var i = 0; i < tBase; i++)
	{
		var aClass = base[i].className.split(" ");
		var taClass = aClass.length;
		for(var j = 0; j < taClass; j++)
		{
			if(aClass[j] == strClass)
			{
				ret[ret.length] = base[i];
				break;
			}
		}
	}
	return ret;
}


// Menu de acesso rapido 2
function menu_rapido2(evento,contador,id,per,link_acoes,perm_editar,tipo_usu,imprimir,link_editar,link_imprimir)
{
//    if($('menu_lista').style.display != "block")
//    {
    	botao = 'botao_mais'+contador;
	   	posicao = getAbsolutePosition($(botao));
		//alert('Posição do botão: '+posicao.x+' - '+posicao.y);
		//divClose = getElementsByClassName("divMenuRapido");

		//for (i=0;i<divClose.length;i++)
		//{
		//	divClose[i].style.display = "none";
		//}
		
		if(navigator.appName == "Netscape")
		{
	    	posY = evento.pageY+'px';
	    	posX = evento.pageX+'px';
	    }
	    else
	    {
   	    	posY = (evento.clientY+document.documentElement.scrollTop);
	    	posX = (evento.clientX+document.documentElement.scrollLeft);
	    }
		//alert('Posição do evento: '+evento.pageX+' - '+evento.pageY);
		//alert('posição original: '+ $('menu_rapido_crm'+contador).style.left+' - '+$('menu_rapido_crm'+contador).style.top);
		$('menu_lista').style.background = "#fff";
		$('menu_lista').style.display  = "block";
		$('menu_lista').style.position  = "absolute";
    	$('menu_lista').style.left = (posicao.x-205)+'px';
    	$('menu_lista').style.top = posicao.y+'px';
        $('menu_lista').innerHTML      = "<br><img src='images/loading.gif' border='0' align='absmiddle'> Carregando...";
		//alert('posição final: '+ posX+' - '+posY);
        xajax_carregaMenuRapido2(contador,id,per,link_acoes,perm_editar,tipo_usu,imprimir,link_editar,link_imprimir);
//    }
//    else
//    {
//        $('menu_lista').style.display  = "none";
//    }
}

// Define o intervalo de chamada das ações ajax agendadas
//var _tela_login
//if(_tela_login != true)
//    setInterval('try{ xajax_executaAcoesAjax() }catch(e){}', 20000);

// Mensagem rápida de um usuário pra outro
//function msg_rapida_ajax(usr_id_to, cont_nome_usr_id_to)
//{
//    msg = prompt("Mensagem rápida para " + cont_nome_usr_id_to + ":", "");
//    if(msg)
//        xajax_agenda_msg_ajax(usr_id_to, msg);
//}

