/**
 * @author caio
 */
 

_emTransito = false;

_salvaEstado = 0;

_editorAtivo = new Array();


_instanciaEditorAtivo = new Array();

Constantes = {
	NUMERO_ESTRELA : 5
};

function Popup(Url, Titulo, Width, Height, Scroll, Status) {
	
	if(Width == "")
		Width = screen.availWidth;
	if(Height == "")
		Height = screen.availHeight;		
		


    window.open(Url, Titulo, 'width='+Width+', height='+Height+', scrollbars='+Scroll+', status=no, top='+((screen.availHeight/2)-(Height/2))+', left='+((screen.availWidth/2)-(Width/2)));
}

function popupCalendario(Url, Titulo, Width, Height, Scrollbar) 
{
	window.open(Url, Titulo, 'width='+Width+', height='+Height+', scrollbars='+Scrollbar+', status=no, resizable, top='+((screen.availHeight/2)-(Height/2))+', left='+((screen.availWidth/2)-(Width/2)));
}
function Paginar(p, id){
	parent.window.toolbar.document.location.href = "toolbar.php?aux=1&p="+p+"&id="+id;
	parent.window.grid.document.location.href = "grid.php?p="+p+"&id="+id;
}
function AbrePrincipal(name, id){
	linktoolbar = new String();
	linkgrid = new String();
	
	linktoolbar = "../"+name+"/toolbar.php?aux=1";
	linkgrid = "../"+name+"/grid.php?aux=1";

	if(id != ""){
		linktoolbar = linktoolbar+"&id="+id;
		linkgrid = linkgrid+"&id="+id;
	}
	
	parent.window.toolbar.document.location.href = linktoolbar;
	parent.window.grid.document.location.href = linkgrid;
}



FivecomUtil = {
	submitForm:
		function(url,metodo,dados, div) {
			var _url = url + "&" + dados;
			var _metodo = metodo;
			$.ajax({
					url: _url,
					contentType: 'application/x-www-form-urlencoded; charset: ISO-8859-1',
					type: _metodo,
					cache: false,
					success: function(html){
						alert("OK");
					}
				} 
			);
		}
}

function novaJanela(url, altura, largura) {
	// Propriedades da janela (centralizada na tela)
	var prop = "top=" + (parseInt(window.screen.height/2)-parseInt(altura/2)) +
		",left=" + (parseInt(window.screen.width/2)-parseInt(largura/2)) +
		",height=" + altura + ",width=" + largura + ",titlebar=no,resizable=no,toolbar=no,location=no,status=yes,menubar=no,scrollbars=1";
	
	var janela = window.open(url,"janela",prop,true);
}


RankEstelar = {
	
	acende: function(estrela,idContainer) {
				if (_salvaEstado == 1) {
					return false;
				}
				
				
				RankEstelar.apaga(idContainer,0);
				
				for(var i=1;i<=estrela;i++) {
					
					window.document.getElementById(idContainer+'_on_'+i).style.display='';
					window.document.getElementById(idContainer+'_off_'+i).style.display='none';
				}
	},
	
	apaga: function(idContainer,carregaEstrela) {
				for(var i=1;i<=Constantes.NUMERO_ESTRELA;i++) {
					if (carregaEstrela == 0) {
						window.document.getElementById(idContainer+'_on_'+i).style.display='none';
						window.document.getElementById(idContainer+'_off_'+i).style.display='';
					} else {
						if (i<=carregaEstrela) {
							window.document.getElementById(idContainer+'_on_'+i).style.display='';
							window.document.getElementById(idContainer+'_off_'+i).style.display='none';
						} else {
							window.document.getElementById(idContainer+'_on_'+i).style.display='none';
							window.document.getElementById(idContainer+'_off_'+i).style.display='';
						}
					}
				}
		   },
		   
	salvar: 
		function(estrela,prop,idContainer) {
			
			_container = idContainer;
			_estrela = estrela;
			
			
			var _url = RankEstelar.getUrl(prop,estrela);
			
			
			$.ajax({
					url: _url,
					contentType: 'application/x-www-form-urlencoded; charset: ISO-8859-1',
					type: "POST",
					cache: false,
					success: function(html){
						
						if (document.getElementById(_container+"_numero_voto") != null) {
							document.getElementById(_container+"_numero_voto").innerHTML = "<strong>"+html+"</strong>";
						} 
						
						RankEstelar.travaEstrela(_container,_estrela);
						
					}
				} 
			);
					 	
		},
	
	getUrl:
		function(prop,estrela) {
			var url = "?id=/apps/" + prop.url + "&" + prop.pars + "&estrela="+estrela;

			return url;
		},
		
	travaEstrela:
		function(idContainer,quantidade) {
			
			RankEstelar.apaga(idContainer,0);
		
			for(var i=1;i<=Constantes.NUMERO_ESTRELA;i++) {
				if (i<=quantidade) {
					window.document.getElementById(idContainer+'_on_'+i).style.display='';
					window.document.getElementById(idContainer+'_off_'+i).style.display='none';
					window.document.getElementById(idContainer+"_link_"+i).onmouseover = function() { return false }
					window.document.getElementById(idContainer+"_link_"+i).onmouseout = function() { return false }
					window.document.getElementById(idContainer+"_link_"+i).onmouseout = function() { return false }
					window.document.getElementById(idContainer+"_link_"+i).onclick = function() { return false }
					window.document.getElementById(idContainer+"_link_"+i).style.cursor = 'normal';
				} else {
					window.document.getElementById(idContainer+"_link_"+i).onmouseover = function() { return false }
					window.document.getElementById(idContainer+"_link_"+i).onmouseout = function() { return false }
					window.document.getElementById(idContainer+"_link_"+i).onmouseout = function() { return false }
					window.document.getElementById(idContainer+"_link_"+i).onclick = function() { return false }
					window.document.getElementById(idContainer+"_link_"+i).style.cursor = 'normal';
					

				}
				
			}
		}
	
};

/**
 * Chamada para lightbox imagem / Vídeo
 */

LightBox = {
	recebeObjetoImagem: 
		function(prop) {
			var classe = "abc";
			
			var imgZoom = document.createElement('img');
			
			imgZoom.id = 'img_' +  classe;
			imgZoom.className = classe;
			imgZoom.src = prop.url;
			imgZoom.alt = prop.descricao;	
			
			return imgZoom;
			
		},
	recebeObjetoVideo:
		function(prop) {
			var _width,_height;
			
			_width  = 425;
			_height = 355;
			
			var embedZoom = document.createElement('embed');
			
			embedZoom.setAttribute("id","fivecomlv");
			embedZoom.setAttribute("name","fivecomlv");
			if (prop.url.indexOf("http://") != -1) {
				embedZoom.setAttribute("src", prop.url);
			} else {
				embedZoom.setAttribute("src", "http://www.youtube.com/v/"+prop.url);
			}
			embedZoom.setAttribute("uimode", "none");
			embedZoom.setAttribute("width", _width);
			embedZoom.setAttribute("height", _height);
			
			return embedZoom;
			
		//document.body.appendChild(embedZoom);
		},
		
	getImagem:
		function(imagem) {

			openZoom(LightBox.recebeObjetoImagem(imagem),imagem.fonte,imagem.descricao);
		},
	
	getVideo:
		function(video) {
			
			openZoom(LightBox.recebeObjetoVideo(video), video.fonte, video.descricao);
		},
	
	getGaleriaImagem: 
		function(imagem) {
			
			openGaleria(LightBox.recebeObjetoImagem(imagem), imagem.fonte, imagem.descricao, imagem.tipoMidia,imagem.codigoTopico,imagem.acao);
			
		},
		
	getGaleriaVideo:
		function(video) {
			openGaleria(LightBox.recebeObjetoVideo(video), video.fonte, video.descricao, video.tipoMidia, video.codigoTopico, video.acao)
		}
};

Topre = {
	buscar: 
		function(form) {
			if (form.palavra_chave.value != "") {
				url = '?id=/apps/topre.busca.php&action=b';
				$.ajax({
					url: url,
					data: $("#form_topre_busca").serialize(),
					type: "POST",
					cache: false,
					success: function(html){
						$("#div_resultado").html(html);
					}
				} 
				
			);
			return false;	
				
		}
	},
	
	relacionarTopico:
	 	
		function(form) {
			var nomeArtigo = new Array();
			var codigoArtigo = new Array();
			cont = 0;
			for(i=0;i<form.elements.length;i++) {
				if (form.elements[i].name.indexOf('chk') != -1) {
					if (form.elements[i].checked) {
						codigoArtigo[cont]= form.elements[i].value;
						nomeArtigo[cont] = form.elements[i].title;
						cont++;
					}
				}
		    }
			
			for (i=0;i<codigoArtigo.length;i++) {
				var prop = ({ 
								tabela: 'tabela_artigo_relacionado',
								codigoInclui: codigoArtigo[i],
								dados: Array(nomeArtigo[i])
							}
						 );
				
				Tabela.insere(' ', prop);
				
			}
						
		  
    	}	
	 }


// Todas as funções estão em tabeladinamica.js

Tabela = {
	
	insere : 
		
		function(objNativo, prop){
			if (objNativo.value != '') {
				if (prop.alias == null) {
					alias = "tpsub";
				} else {
					alias = prop.alias;
				}
				
				if (!existeRegistro(prop.tabela,prop.codigoInclui)) {
					insereLinhaTipoTopico(prop.tabela, prop.codigoInclui, prop.dados, '',alias);
				}
				
			} else {
				alert("Por favor adicione um valor ao campo");
				objNativo.focus();
			}

			objNativo.value = '';
	},
	
	insereComEnter : 
		function(e, objNativo,prop) {
			
			var tcl;
			
			
			if (navigator.appName.indexOf("Internet Explorer") !=-1) {
				tcl = e.keyCode;
			} else {
				tcl = e.which;
			}
			

			if (tcl == 13) {
				Tabela.insere(objNativo, prop);
			}
	},
	
	inativarRegistro : 
		function(tabelaId,linhaId) {
			prop = { 
					tabela : tabelaId,
					id : linhaId
				}
			
			Tabela.exclui(prop);
			
		},
	
	exclui : 
		function(prop) { 
			if (confirm("Deseja realmente inativar esse tipo de tópico ?")) {
				excluiLinha(prop.tabela,prop.id); 
			}
	},
	
	altera : 
		function(prop) {
			var tabela = document.getElementById(prop.tabela);
			var newVal = window.prompt("Alterar nome de subtipo", tabela.rows[prop.linha].cells[0].innerHTML);
			
			if (newVal != null) {
				tabela.rows[prop.linha].cells[0].innerHTML = newVal;
				tabela.rows[prop.linha].title = newVal;
			}	

	}
	
};

Exclui = function(prop) {
			if (confirm("Deseja realmente excluir ?")) {
				location.href = prop.pagina + "&codigo=" + prop.codigo;
			}
		
};

exibirLocalidade = 
	function(ob) {
		if (ob.options[ob.options.selectedIndex].text.indexOf('Localidade') != -1) {
			document.getElementById('exibir_localidade').style.display = "block";
		} else {
			document.getElementById('exibir_localidade').style.display = "none";
		}
}
exibirIndice = 
	function(codigoTpTop) {

		var urlTableIndice = "?id=/apps/topco.tpsub.php&action=tpsub&cd_tptop="+codigoTpTop;
		if (codigoTpTop != "") {
			$("#topco_div_tpsub").load(urlTableIndice, {
				cache: false
			});
		} else {
			$("#topco_div_tpsub").html("");
		}
	}
	
/*
 * 
 * VALIDAÇÃO DE INFORMAÇÕES
 * 
 */
Validacao = {
	Topblb:
		function(acao,form) {
			for(i=0;i<form.elements.length;i++) {
				if (form.elements[i].checked) {
					form.relacionador.value += form.elements[i].value + ",";
				} 
			}
			
			if (form.relacionador.value == "") {
				alert("É necessário relacionar ao menos 1 blog");
				
			} else {
				form.relacionador.value = form.relacionador.value.substring(0,(form.relacionador.value.length-1));
				
				if (acao == "rel") {
					acaoSeguinte = "i";
				} else {
					acaoSeguinte = "d";
				}
				
				form.action = "?id=/apps/topblb.form.php&action="+acaoSeguinte;
				
				form.method = "post";
				
				form.submit();
			}
		},
	
		TpTop: 
		function(form) {
			
			if (form.ds_tptop_tit.value == "") {
				alert("Título inválido");
				form.ds_tptop_tit.focus();
			} else {
				
				form.submit();
				
			}
	},
	
	Mdtop:
		function(acao,form) {
			for(i=0;i<form.elements.length;i++) {
				if (form.elements[i].checked) {
					form.relacionador.value += form.elements[i].value + ",";
				} 
			}
			
			if (form.relacionador.value == "") {
				alert("Nenhum item foi marcado!");
				
			} else {
		
				form.relacionador.value = form.relacionador.value.substring(0,(form.relacionador.value.length-1));
				
				if (acao == "rel") {
					acaoSeguinte = "i";
				} else {
					acaoSeguinte = "d";
				}
				
				form.method = "post";
				
				if (form.id_mdint_tpmid.value == 1) {
					form.action = "?id=/apps/mdtop.video.relaciona.php&action="+acaoSeguinte;
				}
				
				if (form.id_mdint_tpmid.value == 2) {
					form.action = "?id=/apps/mdtop.foto.relaciona.php&action="+acaoSeguinte;
				}
				
				
				
				form.submit();
			
			}
		},
	
	Topre:
		function(acao,form) {
			for(i=0;i<form.elements.length;i++) {
				if (form.elements[i].checked) {
					form.relacionador.value += form.elements[i].value + ",";
				} 
			}
			
			if (form.relacionador.value == "") {
				alert("Nenhum item foi marcado!");
				
			} else {
		
				form.relacionador.value = form.relacionador.value.substring(0,(form.relacionador.value.length-1));
				
				if (acao == "rel") {
					acaoSeguinte = "i";
				} else {
					acaoSeguinte = "d";
				}
				
				form.action = "?id=/apps/topre.form.php&action="+acaoSeguinte;
				form.method = "post";
				form.submit();
				
			}
		},
	
	Topco:
		function(form) {
			
			var codigoProduto = "";

			var inputs = document.getElementsByTagName("input");
			for (var i = 0; i < inputs.length; i++) {
				if ((inputs[i].name.indexOf("cd_produ") != -1) && (form.elements[inputs[i].name].checked)) {
					codigoProduto += form.elements[inputs[i].name].value + ",";
				} 
			}
			form.cd_produ.value = codigoProduto.substr(0,codigoProduto.length-1);
			
			if (form.cd_tptop.value == "") {
				alert("Por favor selecione um tipo de tópico");
			} else if (form.ds_topco_tit.value == "") {
				alert("É necessário escrever o título do tópico");
				form.ds_topco_tit.focus();
			} else {
				form.submit();
			}
		},
	
	SubTpTopco:
		
		function(form) {
			form.submit();
	},
		
		
	MdIntVideo:
		function(form) {
			
			var codigoProduto = "", codigoAgencia = "";
			
			for (var campo=0;campo<form.elements.length;campo++) {
				if ((form.elements[campo].name.indexOf("cd_produ") != -1) && (form.elements[campo].checked)) {
					codigoProduto += form.elements[campo].value + ",";
				} else if ((form.elements[campo].name.indexOf("cd_agenc") != -1) && (form.elements[campo].checked)) {
					codigoAgencia += form.elements[campo].value + ","; 
				}
			}
		
			
			form.cd_produ.value = codigoProduto.substr(0,codigoProduto.length-1);
			form.cd_agenc.value = codigoAgencia.substr(0,codigoAgencia.length-1);
			
			
			if (form.ds_mdint_tit.value == "") {
				alert("Por favor escreva o título do vídeo");
				form.ds_mdint_tit.focus();
				return false;
			} else if (form.ds_mdint_legen.value == "") {
				alert("Por favor escreva a legenda do vídeo");
				form.ds_mdint_legen.focus();
				return false;
			}  else if (form.ds_mdint_file.value == "") {
				alert("Por favor escreva o endereço do vídeo");
				form.ds_mdint_file.focus();
				return false;
			} else {
				return true;
			}		
			
	   },
	   
	 MdIntFoto:
		function(form,acao) {
			
			var codigoProduto = "", codigoAgencia = "";
			
			for (var campo=0;campo<form.elements.length;campo++) {
				if ((form.elements[campo].name.indexOf("cd_produ") != -1) && (form.elements[campo].checked)) {
					codigoProduto += form.elements[campo].value + ",";
				} else if ((form.elements[campo].name.indexOf("cd_agenc") != -1) && (form.elements[campo].checked)) {
					codigoAgencia += form.elements[campo].value + ","; 
				}
			}
		
			
			form.cd_produ.value = codigoProduto.substr(0,codigoProduto.length-1);
			form.cd_agenc.value = codigoAgencia.substr(0,codigoAgencia.length-1);
			
			if (form.ds_mdint_tit.value == "") {
				alert("Por favor escreva o título da foto");
				form.ds_mdint_tit.focus();
				return false;
			} else if (form.ds_mdint_legen.value == "") {
				alert("Por favor escreva a legenda da foto");
				form.ds_mdint_legen.focus();
				return false;
		    } else if (form.arquivo_foto.value == "" && acao == "i") {
				alert("Por favor selecione uma foto");
				form.arquivo_foto.focus();
				return false;
			} else if ((!/(.jpg){1}|(.gif){1}/.exec(form.arquivo_foto.value.toLowerCase()) && form.arquivo_foto.value != "")) {
				alert("Só são permitidas arquivos com extensões .jpg ou .gif");
				form.arquivo_foto.focus();
				return false;
			} else {
				return true;
			}		
			
	   }

}




Editor = {
	
	get: 
		function(id) {
			
			document.getElementById(id).style.display = "block";
			document.getElementById("container_"+id).style.display = "none";
			//document.getElementById("indiceConteudo").style.display = "none";
			
			_cssCarregar = "htmlarea.css";

			iniciarEditor("txt_"+id, null,450,350);
		
		},
	
	close: 
		function(id) {
			document.getElementById(id).value = "";
	    	document.getElementById(id).style.display = 'none';
			document.getElementById("container_"+id).style.display = 'block';
		},
		
	salvar: 
		function(caixaTexto,prop) {
			
			var _url = "index.php?id=/apps/"+prop.pagina+"&action="+prop.acao;
			var _pars = "&topco="+prop.codigoTopico;
			
			if (prop.descricaoTopico) {
				_pars += "&descr=sim";
			} 
			if (prop.indice) {
				_pars += "&indice=sim&tpsub="+prop.codigoTipoSubTopico+"&subtp="+prop.codigoSubTopico;
			}
			
			if (prop.complemento) {
				_pars += "&compl=sim";
			}
			
			if (prop.infExclusiva) {
				
			}
			
			
			_url = _url + _pars;
			
			document.forms['form_topco'].onsubmit();
			document.forms['form_topco'].ds_topco.value = caixaTexto.value;
			document.forms['form_topco'].action = _url;
			document.forms['form_topco'].method = "POST";
			document.forms['form_topco'].submit();
			
			/*
			$.ajax({
					url: _url,
					contentType: 'application/x-www-form-urlencoded; charset: ISO-8859-1',
					data: $("#form_topco").serialize(),
					type: "POST",
					cache: false,
					success: function(html){
					}
				} 
			);
			*/
					 	
		},	
	

		
	url_encode: // url_encode version 1.0  
		function (str) {  
		    var hex_chars = "0123456789ABCDEF";  
		    var noEncode = /^([a-zA-Z0-9\_\-\.])$/;  
		    var n, strCode, hex1, hex2, strEncode = "";  
		
		    for(n = 0; n < str.length; n++) {  
		        if (noEncode.test(str.charAt(n))) {  
		            strEncode += str.charAt(n);  
		        } else {  
		            strCode = str.charCodeAt(n);  
		            hex1 = hex_chars.charAt(Math.floor(strCode / 16));  
		            hex2 = hex_chars.charAt(strCode % 16);  
		            strEncode += "%" + (hex1 + hex2);  
		        }  
		    }  
		    return strEncode;  
		} ,
	
	url_decode: // url_decode version 1.0  
		function (str) {  
		    var n, strCode, strDecode = "";  
		
		    for (n = 0; n < str.length; n++) {  
		        if (str.charAt(n) == "%") {  
		            strCode = str.charAt(n + 1) + str.charAt(n + 2);  
		            strDecode += String.fromCharCode(parseInt(strCode, 16));  
		            n += 2;  
		        } else {  
		            strDecode += str.charAt(n);  
		        }  
		    }  
		    return strDecode;  
		}  

};

function iniciarEditor(campo,toolBar,width,height) {

	 for(i=0;i<_editorAtivo.length;i++) {
		if (_editorAtivo[i] == campo) {
			return;  		
		}
	 }
	
	 
	 var config = new HTMLArea.Config(); // create a new configuration object
                                    // having all the default values
	config.width = width + "px"; 
	config.height = height + "px";
	
	if (toolBar != null) {
		config.toolbar = toolBar;
	}
	
	HTMLArea.replace(campo, config);
  
	//editor = new HTMLArea(campo);
	 
	//editor.registerPlugin(SpellChecker);
    //editor.generate();
  	_instanciaEditorAtivo[campo] = HTMLArea;
	
	 _editorAtivo[_editorAtivo.length] = campo;
	 
	  return true;
}

/* Marca/desmarca todos os checks com o nome no formato "[nome]_#"
 * Onde # é um número sequencial iniciado por 1
 */
var marcarTudo = 
 function( acao, term, form) {
	var inputs = document.getElementsByTagName("input");
	
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].name.indexOf(term) != -1) {
			if (acao.checked) {
				if(!form.elements[inputs[i].name].disabled)
				form.elements[inputs[i].name].checked = true;
			} else {
				form.elements[inputs[i].name].checked = false;
			}
		
		}
	}
 }
				

Compl = {
	salvar: 
		function(id,prop) {
			if (prop.tipo == "comst") {
				var _url = "?id=/apps/comst.form.php&action=i&tipo="+prop.tipo+"&comst="+prop.codigoCompl;
			}
			
			if (prop.tipo == "comtp") {
				var _url = "?id=/apps/comtp.form.php&action=e&tipo="+prop.tipo+"&comtp="+prop.codigoCompl;
			}
			
			$.ajax({
					url: _url,
					contentType: 'application/x-www-form-urlencoded; charset: ISO-8859-1',
					data: $("#form_compl").serialize(),
					type: "POST",
					cache: false,
					success: function(html){
						alert("O complemento foi integrado ao conteúdo");
						location.href="?id=/apps/topco.atualizacao.php&action=atu&pagina=";
					}
				} 
			);
			
			//excluiLinha('table_comst','tr_'+id);
	},
	apagar: 
		function(id,prop) {
			if (prop.tipo == "comst") {
				var _url = "?id=/apps/comst.form.php&action=d&tipo="+prop.tipo+"&comst="+prop.codigoCompl;
			}
			
			if (prop.tipo == "comtp") {
				var _url = "?id=/apps/comtp.form.php&action=d&tipo="+prop.tipo+"&comtp="+prop.codigoCompl;
			}

			$.ajax({
					url: _url,
					contentType: 'application/x-www-form-urlencoded; charset: ISO-8859-1',
					type: "POST",
					cache: false,
					success: function(html){
						alert("O complemento foi excluído com sucesso");
						
						location.href="?id=/apps/topco.atualizacao.php&action=atu&pagina=";
						
					}
				} 
			);
		}

}



mostraEstado = 
	function(pais,objEstado) {
			if (pais != "") {
				_url = "?id=/apps/topco.form.php&action=estdo&pais="+pais;
				$.ajax({
					url: _url,
					cache: false,
					success: function(valores){
						eval(valores);
						preencheComboBox(",",estados.nome,estados.codigo, objEstado, 'Escolha um estado','');
					}
				} 
				);
			}
			
}

mostraCidade = 
	function(estdo,objCidade) {
			
			if (estdo != "NULL") {
			
			
				_url = "?id=/apps/topco.form.php&action=ciade&estdo=" + estdo;
				$.ajax({
					url: _url,
					cache: false,
					success: function(valores){
						
						eval(valores);
												
						preencheComboBox(",", cidades.nome, cidades.codigo, objCidade, 'Escolha uma cidade','');
					}
				});
			}
}

preencheComboBox = 
   function(sep, text, value, obj, textoPadrao,valorPadrao) {
        var clear, obj, t, v, init = 0, x;
		clear = preencheComboBox.arguments[3] ? preencheComboBox.arguments[3] : true;
        obj = document.getElementById(obj).options, t = text.split(sep), v = value.split(sep);
        if(clear)
            while(obj.length > 0)
                obj[0] = null;
		
		for(var i = 0; i < t.length; i++) {
            if (i == 0 ){
				obj[0] = new Option(textoPadrao, valorPadrao);
			} 
			obj[i+1] = new Option(t[i], v[i]);
			
			
        }
}

toggle =
	function(idObj) {
		objToggle = document.getElementById(idObj);
		
		if (objToggle.style.display == "block") {
			objToggle.style.display = 'none';
		} else {
			objToggle.style.display = 'block';
		}
}

editarIndice = 
	function(codigoTopico) {
		window.open("?id=/apps/subtp.topco.subitem.php&action=est&cd_topco="+codigoTopico, "subtp", "height = 400, width = 400");
	}

verificaNomeTopico= function(tituloAtual, novoTitulo, cd_paisAtual, cd_pais, cd_estdoAtual, cd_estdo, cd_ciadeAtual, cd_ciade, ds_topco_pchavAtual, ds_topco_pchav) {
			//alert(cd_ciadeAtual+' = '+cd_ciade);
			if (
				(tituloAtual.toLowerCase()) == (novoTitulo.toLowerCase()) &&
				(cd_paisAtual == cd_pais) &&
				(cd_estdoAtual == cd_estdo) &&
				(cd_ciadeAtual == cd_ciade) &&
				(ds_topco_pchavAtual) == (ds_topco_pchav)
			
			){
				return false;
			}

			_nome = novoTitulo;
			
			if (_nome != "") {
				$.ajax({
							url: "index.php",
							data: "id=/apps/topco.duplicado.php&action=verificanome&ds_topco_tit="+_nome+"&cd_pais="+cd_pais+"&cd_estdo="+cd_estdo+"&cd_ciade="+cd_ciade+"&ds_topco_pchav="+ds_topco_pchav,
							contentType: 'application/x-www-form-urlencoded; charset: ISO-8859-1',
							type: "POST",
							cache: false,
							success: function(html){
										if (html != "") {
											$('#nome_duplicado').show();
											$('#nome_duplicado').html("<div style='width:100%; height:100px; background-color:#f1f1f1;'>&nbsp;</div>");
											$('#nome_duplicado').html(html);
										} else {
											$('#nome_duplicado').hide();
										}
							}
					   }
				);
			}
}
/*
$(document).ready(function(){ 
	$('#alert').jqm({
		overlay: 60,
		overlayClass: 'overlay',
		modal: true,
		trigger: false
	});
	$('#confirm').jqm({
		overlay: 60,
		overlayClass: 'overlay',
		modal: true,
		trigger: false
	});
	//alert("Blog do tmferreira!");
});
*/

mostraCampoExtra = 
	function(acaoRealizada) {

			if (document.getElementById("campo_extra_1") != null) {
				document.getElementById("campo_extra_1").style.display = 'none';
			}
			
			if (document.getElementById("campo_extra_2") != null) {
				document.getElementById("campo_extra_2").style.display = 'none';
			}
			
			if (document.getElementById("campo_extra_3") != null) {
				document.getElementById("campo_extra_3").style.display = 'none';
			}
			
			if (document.getElementById("campo_extra_4") != null) {
				document.getElementById("campo_extra_4").style.display = 'none';
			}
			
			if (document.getElementById("campo_extra_5") != null) {
				document.getElementById("campo_extra_5").style.display = 'none';
			}
			
			if (document.getElementById("campo_extra_6") != null) {
				document.getElementById("campo_extra_6").style.display = 'none';
			}
			
			if (document.getElementById("campo_extra_7") != null) {
				document.getElementById("campo_extra_7").style.display = 'none';
			}			
			
			if (acaoRealizada == 'entregue orçamento') {
				document.getElementById('campo_extra_1').style.display = 'inline';
			}
			
			
			if (acaoRealizada == 'template enviado') {
				document.getElementById('campo_extra_2').style.display = 'inline';
			}
			
			if (acaoRealizada == 'teste agendado') {
				document.getElementById('campo_extra_3').style.display = 'inline';
			}
			
			if (acaoRealizada == 'teste realizado') {
				document.getElementById('campo_extra_4').style.display = 'inline';
			}
			
			if (acaoRealizada == 'transferência de produto') {
				document.getElementById('campo_extra_5').style.display = 'inline';
			}
			
			if (acaoRealizada == 'transferência de agência') {
				document.getElementById('campo_extra_6').style.display = 'inline';
			}
			
			if (acaoRealizada == 'enviado orçamento') {
				document.getElementById('campo_extra_7').style.display = 'inline';
			}


	}
	
Prosp = {
	
	excluir :
		function(cdPssoa,listaAtual) {
			if (confirm("Deseja realmente excluir o prospect ?")) {
				form = document.forms['form_temp'];
				form.cd_pssoa.value = cdPssoa;
				form.action="?id=/apps/prosp.form.php&action=d&lista_atual="+listaAtual;
				form.method='post';
				form.submit();
			}
		},
	mostraTemplate : 
		function(tipo,obj) {
			_tipo = tipo;
			if (tipo != "") {
				_url = "?id=/apps/mktpl.form.php&action=ct&id_mktpl_tipo="+tipo;
				$.ajax({
					url: _url,
					cache: false,
					success: function(valores){
						eval(valores);
						if (_tipo == 1) {

							preencheComboBox(",",mktpl.nome,mktpl.codigo, obj, 'Escolha um template estático','');
						} else {
							
							preencheComboBox(",",mktpl.nome,mktpl.codigo, obj, 'Escolha um template dinâmico','');
						}
					}
				} 
				);
			}
			
	},
	
	carregarTemplate: function(cd_mktpl) {
			_codigoMktpl = cd_mktpl;
			var _conteudo;
			if (_codigoMktpl != "") {
				document.getElementById('visualizar_template').style.display = 'block';
				$.ajax( {
							url: "?id=/apps/mktpl.form.php&action=lt&cd_mktpl="+_codigoMktpl,
							contentType: 'application/x-www-form-urlencoded; charset: ISO-8859-1',
							type: "GET",
							cache: false,
							success: 
								function(html){
									//alert('ok');
									Prosp.editarTemplate('abrir',_codigoMktpl);
									Prosp.processarTemplate(0);
								}
					   }
				);
				
			} else {
				document.getElementById('visualizar_template').style.display = 'none';
			}
				
	},
	
	processarTemplate: function(comando) {
		if(comando == 1){
			document.getElementById('processa_on').style.display = "";
		}else{
			document.getElementById('processa_on').style.display = "none";
		}
		
	},
	
	editarTemplate: function(comando,template) {
		
		if (comando == "abrir") {
			document.getElementById('iframetemplate').src = "?id=/apps/mktpl.form.template.php&action=lt&cd_mktpl="+template;
			html = true;
		}
		
		if (comando == "fechar") {
			document.getElementById('editor_template').value = '';
			document.getElementById('editor_template').style.display = 'none';
			html = true;
		}
		
		if (comando == "getDados") {
			html = parent.iframetemplate.document.forms[0].ds_mktpl_html.value;
			
		}

	return html;
	
		
		
			
		
	},
	
	registraAtendimento: 
		function() {
				var formulario = document.forms['prospect'];
				
				if (formulario.cd_tpate.value == "") {
					alert("Por favor selecione um tipo de contato feito com o prospect");
				} else if(formulario.ds_hisps.value == "") {
					alert("Por favor preencha a descrição do atendimento");
				} else {
					formulario.target = "iframehisps";
					formulario.action = "?id=/apps/prosp.hisps.php&action=ihsps";
					formulario.submit();
					alert("Atendimento registrado");
					document.getElementById('iframehisps').style.display = 'block';
					
					if( document.getElementById('msg_hisps') )
					document.getElementById('msg_hisps').style.display = 'none';
					
					formulario.ds_hisps.value = "";
				}
		},
		
	registraAtendimentoPopup: 
		function() {
				var formulario = document.forms['prospectPopup'];
				
				if (formulario.cd_tpate.value == "") {
					alert("Por favor selecione um tipo de contato feito com o prospect");
				} else if(formulario.ds_hisps.value == "") {
					alert("Por favor preencha a descrição do atendimento");
				} else {
					//formulario.target = "iframehisps";
					formulario.action = "?id=/apps/prosp.hisps.php&action=ihsps&cadastro=true";
					formulario.submit();
					alert("Atendimento registrado");
					document.getElementById('iframehisps').style.display = 'block';
					
					if( document.getElementById('msg_hisps') )
					document.getElementById('msg_hisps').style.display = 'none';
					
					formulario.ds_hisps.value = "";
				}
		},	
	
	enviarTemplate: 
		function(email) {
			
			if (document.forms['prospect'].cd_mktpl.value != "") {
				
				if (confirm("Confirma o envio do template para o email " + email + "?")) {
					


							document.forms['prospect'].ds_mktpl_html.value = Prosp.editarTemplate('getDados');
							
							_html = document.forms['prospect'].ds_mktpl_html.value;
							
							_cdPssoa = document.forms['prospect'].cd_pssoa.value;
							_cdMktpl = document.forms['prospect'].cd_mktpl.value;
							_data = "?id=/apps/mktpl.form.enviatemplate.php&action=et&cd_pssoa="+_cdPssoa+"&cd_mktpl="+_cdMktpl;
							
							try{
							parent.iframetemplate.document.forms[0].onsubmit();
							parent.iframetemplate.document.forms[0].action = _data;
							parent.iframetemplate.document.forms[0].submit();
							}catch(e){
								try{
									//parent.iframetemplate.document.forms[0].onsubmit();
									parent.iframetemplate.document.forms[0].action = _data;
									parent.iframetemplate.document.forms[0].submit();
								}catch(ex){
									alert(ex);
								}
							}
							//document.getElementsById('iframetemplate').forms['frm'].action = _data;
							
							// document.getElementsById('iframetemplate').document.forms['frm'].submit();
							
							$.post('index.php?id=/apps/mktpl.form.enviatemplate.php',{ 
												  action: 'reg',
												  cd_mktpl: _codigoMktpl, 
												  cd_pssoa : _cdPssoa }, 
												  function(html){
														//alert("O template foi enviado ao prospect");
														$('#template_enviado').html(html);
												  }, "html"
								  );
			}
		
		} else {
			alert("Por favor selecione um template");
		}
				 
						
	},

	mudaImagem : 
		function(secao,icone,acao) {
		if (acao == "in") {
			if (secao == "in") {
				document.getElementById(icone).src = "../imagens/ics_inbox_active.png";
			}
		
			if (secao == "ht") {
				document.getElementById(icone).src = "../imagens/ics_hotlist_active.png";
			}
		
			if (secao == "st") {
				document.getElementById(icone).src = "../imagens/ics_standby_active.png";
			}
		
			if (secao == "tr") {
				document.getElementById(icone).src = "../imagens/ics_trash_active.png";
			}
		}
		
		if (acao == "out") {
			if (secao == "in") {
				document.getElementById(icone).src = "../imagens/ics_inbox.png";
			}
			
			if (secao == "ht") {
				document.getElementById(icone).src = "../imagens/ics_hotlist.png";
			}
		
			if (secao == "st") {
				document.getElementById(icone).src = "../imagens/ics_standby.png";
			}
		
			if (secao == "tr") {
				document.getElementById(icone).src = "../imagens/ics_trash.png";
			}
		}
		
	},
	
	mudaTipoBusca : function(buscaAtual,form) {
		
		form.nm_pssoa.value = "";
		form.nm_pssoa_meio.value = "";
		form.nm_pssoa_ultim.value = "";
		
		var listaContainer = new Array('busca_basica','busca_avancada');
		for(var i in listaContainer) {
			if (listaContainer[i] == buscaAtual) {
				document.getElementById(listaContainer[i]).style.display = 'block';
			} else {
				document.getElementById(listaContainer[i]).style.display = 'none';
			}
		}
		
		for(var i in listaContainer) {
			if (listaContainer[i] == 'busca_basica') {
				//document.forms['form_busca_basica'].reset();
				document.forms['form_busca_basica'].tipo_busca.value = buscaAtual;
			} 
			
			if (listaContainer[i] == 'busca_avancada') {
				//document.forms['form_busca_avancada'].reset();
				document.forms['form_busca_avancada'].tipo_busca.value = buscaAtual;
			}
		}
		
	},
	
	mostrarControlesAutorProspect : function(tipoBusca) {
		
			if (tipoBusca == 1) {
				objs = new Array('consultor_busca_basica','combo_consultor_busca_basica');
			}
			
			if (tipoBusca == 2) {
				objs = new Array('consultor_busca_avancada','combo_consultor_busca_avancada');
			}
			
			
			for (var i=0;i<objs.length;i++) {
				objC =  document.getElementById(objs[i]);
				if (objC.style.display == 'none') { 
					objC.style.display = 'block';
				} else {
					objC.style.display = 'none';
				}
				objC = null;
				
			}
	},
	
	mudaAba : function(container,obj) {
		var listaContainer = new Array('atendimento','dados_pessoais','templates','sms','orcamentos');
		for(var i in listaContainer) {
			if (listaContainer[i] == container) {
				document.getElementById(listaContainer[i]).style.display = 'block';
			} else {
				document.getElementById(listaContainer[i]).style.display = 'none';
			}
		}
		
	},
	excluirParaTrashBin:
		function(codigoPssoa, lista,form) {
			if (confirm("Deseja realmente enviar para Trash Bin ?")) {
				Prosp.executaMudancaEstadoProspect('tr',codigoPssoa);
				setTimeout(function() { 
								form.submit() },1000);
			}
	},
		
	executaMudancaEstadoProspect: 
		function(lista,codigoPssoa) {
			_status = lista;
			_codigoPssoa = codigoPssoa;
                        $.ajax({
							url: "?id=/apps/prosp.form.php&action=me&cd_pssoa="+_codigoPssoa+"&id_pssoa_statu="+_status,
							contentType: 'application/x-www-form-urlencoded; charset: ISO-8859-1',
							type: "GET",
							cache: false,
							success: function(html){
								if (document.getElementById('status_prospect') != null) {
									if (_status == "in") {
										document.getElementById('status_prospect').style.textColor = "FF0000";
										document.getElementById('status_prospect').innerHTML = "O prospect foi adicionado a <b>Inbox</b>";
									}
									
									if (_status == "ht") {
										document.getElementById('status_prospect').style.textColor = "FF0000";
										document.getElementById('status_prospect').innerHTML = "O prospect foi adicionado a <b>Hot List</b>";
									}
									
									if (_status == "st") {
										document.getElementById('status_prospect').style.textColor = "FF0000";
										document.getElementById('status_prospect').innerHTML = "O prospect foi adicionado a <b>Stand By</b>";
									}
									
									if (_status == "tr") {
										document.getElementById('status_prospect').style.textColor = "FF0000";
										document.getElementById('status_prospect').innerHTML = "O prospect foi adicionado a <b>Trash Bin</b>";
									}
								}
								
							}
					   }
				);
	},
	
	mudaEstadoProspect: 
		function(status,codigoPssoa) {
			
			var _status = status;
			var _codigoPssoa = codigoPssoa;
			
			
			if (status == "in") { // coloca o estado da pesso para in. Assim, o mesmo se encontrará em Inbox
				//status = "";
				mudarLista = confirm("O prospect será transferido para a Inbox. \n \n Você confirma ?");	
			}
				
			if (status == "ht") {
				mudarLista = confirm("O prospect será transferido para a Hot List. \n \n Você confirma ?");	
				
				
			}
			
			if (status == "st") {
				mudarLista = confirm("O prospect será transferido para Stand By. \n \n Você confirma ?");
				
			}
			
			if (status == "tr") {
				mudarLista = confirm("O prospect será transferido para Trash Bin.\n \n Você confirma ?");
				
			}
			
			
			if (mudarLista) {
				Prosp.executaMudancaEstadoProspect(_status,_codigoPssoa);
				
			} 
				//document.forms['prospect'].action = "?id=/apps/prosp.form.php&action=me";
				//document.forms['prospect'].cd_pssoa.value = codigoPssoa;
				//document.forms['prospect'].id_pssoa_statu.value = status;
				//document.forms['prospect'].method = "POST";
				
				//FivecomUtil.submitForm(document.forms['prospect'].action,document.forms['prospect'].method,'status_prospect');
				
	},
/*	mudarAgencia = 
		function(codigoAgencia,codigoPssoa) {
			var formulario = window.document.forms['prospect'];
			formulario.action = "?id=/apps/prosp.form.php&action="+acaoRealizar;
			formulario.submit();
			//alert("valor " + x + " codígo pessoa " + y);		
		
	},*/

	ValidaForm:
		function(acao) {
			msg = new String();
	
			var formulario = window.document.forms['prospect'];
			
			//ColorirForm(formulario, '');
			
			
			if (formulario['nm_pssoa']) {
				if(formulario['nm_pssoa'].value == ""){
					formulario['nm_pssoa'].focus();
					msg = msg + "Alerta: O campo \"Primeiro Nome\" deve ser preenchido\n";
				}
			}
			
			if (formulario['nm_pssoa_ultim']) {
				if(formulario['nm_pssoa_ultim'].value == ""){
					formulario['nm_pssoa_ultim'].focus();
					msg = msg + "Alerta: O campo \"Ultimo Nome\" deve ser preenchido\n";
				}
			}

			if (formulario['ds_pssoa_email']) {
				if(formulario['ds_pssoa_email'].value == ""){
					formulario['ds_pssoa_email'].focus();
					msg = msg + "Alerta: O campo \"Email\" deve ser preenchido\n";
				}	
			}
			
			if (formulario['cd_cconh']) {
				if(formulario['cd_cconh'].value == ""){
					formulario['cd_cconh'].focus();
					msg = msg + "Alerta: O campo \"Como Conheceu a IE?\" deve ser preenchido\n";
				}
			}
		
			if (formulario['cd_agenc']) {
				if(formulario['cd_agenc'].value == ""){
					formulario['cd_agenc'].focus();
					msg = msg + "Alerta: O campo \"Agência mais proxima?\" deve ser preenchido\n";
				}
			}
			if (acao == "c") {
				if (formulario['cd_produ']) {
					if(formulario['cd_produ'].value == ""){
						formulario['cd_produ'].focus();
						msg = msg + "Alerta: Escolha um produto procurado \n";
					}
				}
			}

			if (formulario['id_pssoa_sexo']) {
				if(formulario['id_pssoa_sexo'].value == ""){
					formulario['id_pssoa_sexo'].focus();	
					msg = msg + "Alerta: O campo \"Sexo\" deve ser preenchido\n";
				}	
			}
	
			if (formulario['ds_pssoa_ciade']) {
				if(formulario['ds_pssoa_ciade'].value == ""){
					formulario['ds_pssoa_ciade'].focus();
					msg = msg + "Alerta: O campo \"Cidade\" deve ser preenchido\n";
				}
			}
			
			

			if (formulario['ds_pssoa_estdo']) {
				if(formulario['ds_pssoa_estdo'].value == ""){
					formulario['ds_pssoa_estdo'].focus();
					msg = msg + "Alerta: O campo \"Estado\" deve ser preenchido\n";
				}
			}
		

			//if (formulario['id_tptel1']) {
			//	if(formulario['id_tptel1'].value == ""){
			//		formulario['id_tptel1'].focus();
			//		msg = msg + "Alerta: O campo \"Tipo de Telefone 1\" deve ser preenchido\n";
			//	}	
			//}
			
	
			if (formulario['ds_pssoa_tel1']) {
				if(formulario['ds_pssoa_tel1'].value == ""){
					formulario['ds_pssoa_tel1'].focus();
					msg = msg + "Alerta: O campo \"Telefone de Contato\" deve ser preenchido\n";
				}
			}
	

			/*if (formulario['id_pssoa_hora']) {
				if(formulario['id_pssoa_hora'].value == ""){
					formulario['id_pssoa_hora'].focus();
					msg = msg + "Alerta: O campo \"Melhor Horário\" deve ser preenchido\n";
				}
			}
			*/		
						
			/*
			if (formulario['ds_pssoa_cpf']) {
				if(formulario['ds_pssoa_cpf'].value != ""){
					if(!validaCPF(formulario['ds_pssoa_cpf'].value)){
					}
				}
			}
			*/
			

			return Prosp.ValidaMsg(msg,formulario,acao);
		},
		
		ValidaMsg:
			function(msg,formulario,acao) {
				var acaoRelizar;
				if (acao == "c") {
					acaoRealizar = "i";
				} else if (acao == "e") {
					acaoRealizar = "a";
				} else {
					acaoRealizar = acao;
				}
				
				if (msg != "") {
					alert(msg);	
					//return false;	
				} else {
					_data = "";
					
					//return true;
					
					formulario.action = "?id=/apps/prosp.form.php&action="+acaoRealizar;
						
					formulario.submit();
				
					
				}	
			}
};



function getAlert(msg) {
  $('#alert')
    .jqmShow()
    .find('div.jqmAlertContent')
    .html("<img src='alert.gif' /><span>" + msg + "</span>")
    .end()
    .find(':submit:visible')
    .click(function() {
    	$('#alert').jqmHide();
    });
}

function getConfirm(msg,callback) {
  $('#confirm')
    .jqmShow()
    .find('p.jqmConfirmMsg')
    .html("<img src='confirm.gif' /><span>" + msg + "</span>")
    .end()
    .find(':submit:visible')
    .click(function(){
        if(this.value == 'Sim')
          (typeof callback == 'string') ?
            window.location.href = callback :
            callback;
        $('#confirm').jqmHide();
    });
}


MaskInput = function(f, m){
    function mask(e){
        var patterns = {"1": /[A-Z]/i, "2": /[0-9]/, "4": /[\xC0-\xFF]/i, "8": /./ },
            rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8};
        function accept(c, rule){
            for(var i = 1, r = rules[rule] || 0; i <= r; i<<=1)
                if(r & i && patterns[i].test(c))
                    break;
                return i <= r || c == rule;
        }
        var k, mC, r, c = String.fromCharCode(k = e.key), l = f.value.length;
        (!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ?
            r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0]
            : (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ?
            r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();
    }
    for(var i in !/^(.)\^(.*)$/.test(m) && (f.maxLength = m.length), {keypress: 0, keyup: 1})
        addEvent(f, i, mask);
};

/*
**************************************
* Restrict Class v1.0                *
* Autor: Carlos R. L. Rodrigues      *
**************************************
*/

//========================================================
// REQUIRES http://www.jsfromhell.com/geral/event-listener
//========================================================

Restrict = function(form){
    this.form = form, this.field = {}, this.mask = {};
}
Restrict.field = Restrict.inst = Restrict.c = null;
Restrict.prototype.start = function(){
    var $, __ = document.forms[this.form], s, x, j, c, sp, o = this, l;
    var p = {".":/./, w:/\w/, W:/\W/, d:/\d/, D:/\D/, s:/\s/, a:/[\xc0-\xff]/, A:/[^\xc0-\xff]/};
    for(var _ in $ = this.field)
        if(/text|textarea|password/i.test(__[_].type)){
            x = $[_].split(""), c = j = 0, sp, s = [[],[]];
            for(var i = 0, l = x.length; i < l; i++)
                if(x[i] == "\\" || sp){
                    if(sp = !sp) continue;
                    s[j][c++] = p[x[i]] || x[i];
                }
                else if(x[i] == "^") c = (j = 1) - 1;
                else s[j][c++] = x[i];
            o.mask[__[_].name] && (__[_].maxLength = o.mask[__[_].name].length);
            __[_].pt = s, addEvent(__[_], "keydown", function(e){
                var r = Restrict.field = e.target;
                if(!o.mask[r.name]) return;
                r.l = r.value.length, Restrict.inst = o; Restrict.c = e.key;
                setTimeout(o.onchanged, r.e = 1);
            });
            addEvent(__[_], "keyup", function(e){
                (Restrict.field = e.target).e = 0;
            });
            addEvent(__[_], "keypress", function(e){
                o.restrict(e) || e.preventDefault();
                var r = Restrict.field = e.target;
                if(!o.mask[r.name]) return;
                if(!r.e){
                    r.l = r.value.length, Restrict.inst = o, Restrict.c = e.key || 0;
                    setTimeout(o.onchanged, 1);
                }
            });
        }
}
Restrict.prototype.restrict = function(e){
    var o, c = e.key, n = (o = e.target).name, r;
    var has = function(c, r){
        for(var i = r.length; i--;)
            if((r[i] instanceof RegExp && r[i].test(c)) || r[i] == c) return true;
        return false;
    }
    var inRange = function(c){
        return has(c, o.pt[0]) && !has(c, o.pt[1]);
    }
    return (c < 30 || inRange(String.fromCharCode(c))) ?
        (this.onKeyAccept && this.onKeyAccept(o, c), !0) :
        (this.onKeyRefuse && this.onKeyRefuse(o, c),  !1);
}
Restrict.prototype.onchanged = function(){
    var ob = Restrict, si, moz = false, o = ob.field, t, lt = (t = o.value).length, m = ob.inst.mask[o.name];
    if(o.l == o.value.length) return;
    if(si = o.selectionStart) moz = true;
    else if(o.createTextRange){
        var obj = document.selection.createRange(), r = o.createTextRange();
        if(!r.setEndPoint) return false;
        r.setEndPoint("EndToStart", obj); si = r.text.length;
    }
    else return false;
    for(var i in m = m.split(""))
        if(m[i] != "#")
            t = t.replace(m[i] == "\\" ? m[++i] : m[i], "");
    var j = 0, h = "", l = m.length, ini = si == 1, t = t.split("");
    for(i = 0; i < l; i++)
        if(m[i] != "#"){
            if(m[i] == "\\" && (h += m[++i])) continue;
            h += m[i], i + 1 == l && (t[j - 1] += h, h = "");
        }
        else{
            if(!t[j] && !(h = "")) break;
            (t[j] = h + t[j++]) && (h = "");
        }
    o.value = o.maxLength > -1 && o.maxLength < (t = t.join("")).length ? t.slice(0, o.maxLength) : t;
    if(ob.c && ob.c != 46 && ob.c != 8){
        if(si != lt){
            while(m[si] != "#" && m[si]) si++;
            ini && m[0] != "#" && si++;
        }
        else si = o.value.length;
    }
    !moz ? (obj.move("character", si), obj.focus()) : o.setSelectionRange(si, si);
}

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/geral/event-listener [v1.4]

addEvent = function(o, e, f, s){
    var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
    r[r.length] = [f, s || o], o[e] = function(e){
        try{
            (e = e || (window.event ? (arguments = [].slice.call(arguments)).unshift(e = event) || 1 && e : {})).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
            e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
            e.target || (e.target = e.srcElement || null);
            e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
        }catch(f){}
        for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.apply ? c = a.apply(o, arguments) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
        return e = null, !!d;
    }
};

removeEvent = function(o, e, f, s){
    for(var i = (e = o["_on" + e] || []).length; i;)
        if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
            return delete e[i];
    return false;
};



function Carregado(acao) {

	document.getElementById('carregando').style.display='none';
	document.getElementById('Pagina').style.display='block';
	parent.document.getElementById('enviaTemplateBaixo').style.display='block';
	parent.document.getElementById('enviaTemplateCima').style.display='block';
	
} 


function habilitaFotoPerfil() {
	if(document.getElementById('fotoPerfilEscolha').checked == ""){
		document.getElementById('fotoPerfil').disabled = "";
	}else{
		document.getElementById('fotoPerfil').disabled = "disabled";
	}
}

function fechaMsgBox(id){
	if(document.getElementById(id).style.display == "none")
		document.getElementById(id).style.display = "";
	else
		document.getElementById(id).style.display = "none";
	
}


function VerificaNovaSenha(){
	if(document.getElementById('senhaAntigaBean').value != document.getElementById('senhaAntiga').value){
		alert('Senha atual não confere!');
		return false;
	}
	
	if(document.getElementById('novaSenha').value != document.getElementById('confirmaNovaSenha').value){
		alert('Houve um erro ao confirmar sua nova senha. Tente novamente!');
		return false;
	}
}


function marca(id){
	if(document.getElementById(id).checked == ''){ 
		document.getElementById(id).checked = 'checked'; 
	} else { 
		document.getElementById(id).checked = ''; 
	}
}


/**
 * Função para trocar uma imagem
 *
 */
function trocar_imagem( imagem, endereco ){
	document.getElementById( imagem ).src = endereco;
}



/** FUNÇÃO FILTRAR POSSÍVEL EMAIL DO PROSPECT JÁ EXISTENTE NO CADASTRO - AJAX **/
function filtroEmail(email){
	var email_origem = email;
	var erro;
	
	var er = new RegExp( /^[a-z\xe0-\xe3\xe9-\xea\xed\xf3-\xf5\xfa\xc7A-Z\xc0-\xc3\xc9-\xca\xcd\xd3-\xd5\xda\xe70-9\.\-\_]+@[a-z\xe0-\xe3\xe9-\xea\xed\xf3-\xf5\xfa\xc7A-Z\xc0-\xc3\xc9-\xca\xcd\xd3-\xd5\xda\xe70-9\.\-\_]+\.[a-zA-Z0-9]{2,4}$/ );
	
	if( email_origem == '' ){
		erro = 1;
		msg = 'É preciso preencher o campo e-mail';
	}
	else if( typeof( email_origem ) == "string" ){
		if( !er.test( email_origem )){ 
			erro = 1;
			msg = 'O e-mail digitado não é válido';
		}
	}
	else if( typeof( email_origem ) == "object" ){
		if( !er.test( email_origem.value ) ){
			erro = 1;
			msg = 'O e-mail digitado não é válido';
		}
	}
	
	if(!erro){
		$('#filtro_resposta_1').html("Verificando...");
		$.post('index.php?id=/includes/verifica_email.php', 
			{ email : email }, 
			function(resposta){
				$('#filtro_resposta_1').html(resposta);
			}
		);
	}else{
		alert("ATENÇÃO!\n\n"+msg);
		return false;
	}
}
