// Menu em cascata
//var menuid = "menu";
//		
//function buildsubmenus(){
//	var ultags = document.getElementById(menuid).getElementsByTagName("ul");
//    
//	for (var t = 0; t < ultags.length; t++){
//    			    	
//		if (ultags[t].parentNode.parentNode.id == menuid) { 
//			ultags[t].style.top = ultags[t].parentNode.offsetHeight+"px";
//		} 		  
//    
//		ultags[t].parentNode.onmouseover = function(){
//    		this.getElementsByTagName("ul")[0].style.display="block";
//   		}
//    	ultags[t].parentNode.onmouseout = function(){
//    		this.getElementsByTagName("ul")[0].style.display="none";
//    	}
//    }
//    
//	for (var t = ultags.length-1; t > -1; t--) { 
//		ultags[t].style.visibility="visible";
//		ultags[t].style.display="none";
//	}
//}
//
//if (window.addEventListener)
//window.addEventListener("load", buildsubmenus, false);
//else if (window.attachEvent)
//window.attachEvent("onload", buildsubmenus);
// Fim do menu
if (document.getElementById("nav")) {
sfHover = function() {
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);
}
function abreGaleria(galeria, tipo) {
	window.open("galeria_"+ tipo +".php?galeria="+ galeria, "_self");
}

function montaSubMenu(rel) {
//	alert ( rel.offsetLeft );
	var sM = document.getElementById('subMenu');
	sM.style.left = rel.offsetLeft +"px";
	sM.style.bottom = (8 + rel.offsetTop) +"px";
	sM.style.display = "block";
}

function escondeSubMenu() {
	document.getElementById('subMenu').style.display = "none";	
}

function validaMural(form) {
	if (form.nome.value == "") {
		alert("Preencha o Nome/Título");
		return false;
		} else if (form.email.value == "" || !validaEmail(form.email.value)) {
			alert("Preencha o E-Mail corretamente");
			return false;
		} else if (form.recado.value == "") {
			alert("Preencha o recado");
			return false;
	} else {
		return true;
	}
}

function validaComentario(form) {
	if (form.nome.value == "") {
		alert("Preencha o Nome/Título");
		return false;
		} else if (form.email.value == "" || !validaEmail(form.email.value)) {
			alert("Preencha o E-Mail corretamente");
			return false;
		} else if (form.comentario.value == "") {
			alert("Preencha o comentário");
			return false;
	} else {
		return true;
	}
}

function validaEmail(email){
	var resultado = false;
	var emailStr = new String(email);
	var index = emailStr.indexOf("@");
	if (index > 0){
		var indice = emailStr.indexOf(".",index);
		if ((indice > index+1) && (emailStr.length > indice+1)){
			resultado = true;
		}
	}
	return resultado;
}

function abrePlayer(galeria) {
	window.open("http://audios.rotadosamba.com/galeria.php?galeria="+ galeria, "_blank", "width=466, height=240");
}

function excluiMsg(tabela, id) {
	if (confirm("Tem certeza que deseja excluir o registro?")) {
		window.open("extras/busca_reg.php?tabela="+ tabela +"&id="+ id, "ifr_atualiza");
	}
}
// coloca barras na data
function ajustarData(input, evento){
    if(!soNumero(evento)){
	    return false;
	} else { 
		if ((input.value.length == 2)||(input.value.length == 5)) {
		   input.value = input.value + "/" ;
		   }
	}
	return true;
}



function mostraImagem(a,l,f){
	pg = "fig_produto/" + f;
	l = eval(l) + 17;
	a = eval(a) + 4;
	if(a > 520) a = 520
	if(l > 650) l = 650
	nova_janela = window.open('','mostra_imagem','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,menubar=no,width=' +l+ ',height=' + a);
	nova_janela.document.writeln('<HTML><HEAD><TITLE></TITLE></HEAD><BODY style="margin=0px;text-align=center;"><IMG style="cursor=hand;" src="'+pg+'" onClick="window.close()" alt="Clique na imagem para fechar"></BODY></HTML>');
	nova_janela.document.close();
}


function validaFormulario()
{
  //var campoForm[] = document.frm_cadastro.field[];
  var aux;
  var cont=1;
  var pos;
  
  for (var i=0; i < document.frm_cadastro.elements.length; i=i+1)
  {
     //alert(document.frm_cadastro.elements.length);
	 //alert(document.frm_cadastro.elements[i].name);
	 //document.frm_cadastro.hd_analise_critica.value = "fff";
	 if (document.frm_cadastro.elements[i].rel == "*")
	 { 
	     
	     if (((document.frm_cadastro.elements[i].value == "")||(document.frm_cadastro.elements[i].value == 0)) && cont == 1)
		     {
			    pos = document.frm_cadastro.elements[i].name.length;
				aux = document.frm_cadastro.elements[i].name.substr(3,pos-3);
			    aux = "Preencha o campo " + aux;				
			    alert(aux);
				document.frm_cadastro.elements[i].focus();
				//return false;
			    cont += 1;
			 }	
			 
					
	 }
  }
  
	if (cont == 1)
		{
			document.frm_cadastro.submit();
			return true;
		} 

}
	



// Envia o formulário de busca
function enviaBusca(pagina){
	with(document.frm_busca){
//		if(!nome_campo.value == "" && !valor_campo.value == ""){
//			if(nome_campo.value.substr(0,3) == "st_" || nome_campo.value.substr(0,3) == "cf_"){
//				tipo_campo.value = "txt";
//			}else if(nome_campo.value.substr(0,3) == "dt_"){
//				tipo_campo.value = "dat";
//			}else{
//				tipo_campo.value = "num";
//			}
//			
//			campo = nome_campo.value;
//			valor = valor_campo.value;
//			
//			dados = 'pagina=' + pagina + '&nome_campo=' + campo + '&valor_campo=' + valor + '&tipo_campo=' + tipo_campo, 'conteudo';
//			//processa('mostra', dados);
//		}else{
//			dados = 'pagina=' + pagina, 'conteudo';
//			
//			//processa('mostra', dados);
//		}
		submit();
	}
}

// Mantem o campo de pesquisa preenchido em memória
function guardaCampo(nome,valor){
	with(document.frm_busca){
		nome_campo.value = nome;
		valor_campo.value = valor;
	}
}

//Envia o formulario de cadastro
function executa(modulo, altera){
	formu = document.forms[0];
	dados = "pagina=" + modulo;
	for(cont=0;cont<formu.elements.length;cont++)
    	dados += '&' + formu.elements[cont].name + '='+escape(formu.elements[cont].value)
    if(modulo != "trocasenha" && altera == '0')
 		processa('muda', dados, 'conteudo');
 	else if(altera == '1')
 		processa('muda', dados, 'resposta');
 	else
 		processa('admin', dados, 'resposta');
}

function getQuery()  { 
	var query='', n=0; 
	for (var j=0,elm; (elm=FORM.elements[j]); j++){ 
		var name = elm.getAttribute('name'); 
		if (!name || (name.length == 0)) continue; 
		var s = elm.value.clean(); 
		if (s.length == 0) continue; 
		if (elm.type != 'hidden') n++; 
		if (query.length > 0) query += '&'; 
		query += name + '=' + escape(s); 
	} 
	return (n > 0) ? query : null; 
} 

  // remove brancos redundantes 
String.prototype.clean = function () { 
	var src=this.toString().replace(/^\s+/,"").replace(/\s+$/,""); 
	var re=/(\S+)(\x20{2,})(\S+)/; 
	while(src.match(re))src=src.replace(re,"$1 $3"); 
	re=/(\S+)(\s+)(\r)(\s+)(\S+)/; 
	while(src.match(re))src=src.replace(re,"$1$3$5"); 
	return src; 
}

/* ------------------------------ */

//Confirma exclusão antes de exluir
function excluir(pId, pagina) {	
	confirmacao = window.confirm("Atenção! Você tem certeza que deseja excluir este registro?");
	if (confirmacao){
		dados = 'pagina=' + pagina + '&opcao=2&excluir=1&id='+ pId;
//		processa('muda', dados, 'conteudo');
		window.open("muda.php?" + dados, "_self");
	}
//	alert(dados);
}

function confirmaExclusaoIcone(nomeArquivo, temImg){
	if(temImg != ""){
		confirmacao = window.confirm("Atenção! Este registro já tem um " + nomeArquivo + " cadastrado. \nVocê tem certeza que deseja substituí-lo?");
		if(confirmacao){
			document.frm_upload_ic.submit();
			return true
		}
	}else{
		document.frm_upload_ic.submit();
		return true
	}
}

function excluirImg(figura, pasta, id, pg, nomePagina) {
	if(nomePagina != "undefined"){
		arquivo = pasta.substr(4,pasta.length);
	}else{
		arquivo = "imagem";
	}
	
	// essa linha não ta certa não
// 	confirmacao = window.confirm("Atenção! Você tem certeza que deseja retirar este " + arquivo + " deste registro?");
	confirmacao = window.confirm("Atenção! Você tem certeza que deseja retirar esta imagem deste registro?");
	
	if (confirmacao){
		dados = 'pasta=' + pasta + '&img='+ figura + "&id=" + id + "&pg=" + pg;
		if(nomePagina != "undefined") dados = dados + "&pagina=" + nomePagina;
		window.open("exclui_img.php?" + dados, "ifr_upload");
	}
}

function excluirArq(arquivo, pasta, id, pg, nomePagina){
	if(nomePagina != "undefined"){
		arquivo = pasta.substr(4,pasta.length);
	}else{
		arquivo = "imagem";
	}
	
	// essa linha não ta certa não
// 	confirmacao = window.confirm("Atenção! Você tem certeza que deseja retirar este " + arquivo + " deste registro?");
	confirmacao = window.confirm("Atenção! Você tem certeza que deseja retirar esta imagem deste registro?");
	
	if (confirmacao){
		dados = 'pasta=' + pasta + '&img='+ arquivo + "&id=" + id + "&pg=" + pg;
		if(nomePagina != "undefined") dados = dados + "&pagina=" + nomePagina;
		window.open("exclui_img.php?" + dados, "ifr_upload");
	}
}

function renomearArq(nome_velho, ext, id, pasta, nome_novo, ok){
	if(ok == 1){
		url = 'id='+ id + '&pasta=' + pasta + '&nome_velho='+nome_velho+'&nome_novo='+nome_novo+'&ext='+ext+'&ok=1';
	}else{
		url = 'id='+ id + '&pasta=' + pasta + '&nome_velho='+nome_velho+'&ext='+ext;
	}
// 	alert('Nome velho: '+ nome_velho + ' - Ext: ' + ext + ' - Nome novo: ' + nome_novo + ' - OK: ' + ok + '\nURL: ' + url);
	window.open('renomear_arquivo.php?'+url, 'ifr_upload');
}

function focusNovoNome(){
	document.frm_cadastro.st_novo_nome.focus();
	document.frm_cadastro.st_novo_nome.select();
}



//Permite digitar apenas números
function soNumero(evento){
//48 - 57
	var BACKSPACE=  8; 
	var TAB= 9;
    var DEL=  46; 
    var FRENTE=  39; 
    var TRAS=  37; 
    var tecla= (evento.keyCode ? evento.keyCode: evento.which ? evento.which : evento.charCode)
    
    if (( tecla == BACKSPACE )||(tecla == DEL)||(tecla == FRENTE)||(tecla == TRAS)||(tecla == TAB)){
         return true; 
	}
    if ( tecla == 13 )     return false; 

	if ((tecla >= 48 && tecla <= 57) || (tecla == 44)) {
		return true;
	}else{
		evento.returnValue = false; 
		return false;
	}
}

//Permite digitar apenas letras
function soTexto(evento){
//65 - 90 A-Z
//97 - 122 a-z
    var tecla= (evento.keyCode ? evento.keyCode: evento.which ? evento.which : evento.charCode)
    
	if ((tecla>=65 && tecla<=90) || (tecla>=97 && tecla<=122) || (tecla == 32 || tecla == 38)) {
		return true;
	}else{
		evento.returnValue = false; 
		return false;
	}
}
function ajustarCpf(input, evento){
	tecla = evento.keyCode;
    if(!soNumero(evento)){
	    return false;
	}else{
		if((tecla<48)||(tecla>57)){
			evento.returnValue =false;
			return false;
		}else{
			if ((input.value.length == 3)||(input.value.length == 7)) {
				input.value = input.value + "." ;
			}
			if (input.value.length == 11) {
				input.value = input.value + "-" ;
			}
			if(input.value.length == 15){
				input.value = input.value.replace('.','');
				input.value = input.value.replace('.','');
				input.value = input.value.replace('-','');
				input.value = input.value.substr(0, 2) + '.' + input.value.substr(2, 3) + '.' + input.value.substr(5, 3) + '/' + input.value.substr(8, 4);
				input.value = input.value + "-" ;
			}
		}
	}
	return true;
}

//Formata Telefone
function ajustarFone(input, evento){
    if(!soNumero(evento)){
	    return false;
	} else { 
		if (input.value.length == 1) {
		   input.value = "(" + input.value;
		}
		if (input.value.length == 3) {
		   input.value = input.value + ")";
		}
		if (input.value.length == 8) {
		   input.value = input.value + "-";
		}
	}
	return true;
}

//Formata CEP
function ajustarCep(input, evento){
    if(!soNumero(evento)){
	    return false;
	} else { 
		if (input.value.length == 5) {
		   input.value = input.value + "-";
		}
	}
	return true;
}

//Formata Placa Veículo
function ajustarPlaca(input, evento){
	var tecla= (evento.keyCode ? evento.keyCode: evento.which ? evento.which : evento.charCode);
	if (tecla == 45){
		return false
	}else{
		if (input.value.length == 3){
		   input.value = input.value + "-";
		}
	}
	caixaAlta(input);
	return true;
}

// Transforma tudo em caixa alta
function caixaAlta(input) { 
	input.value = input.value.toUpperCase(); 
} 

function escreveData() {
    hoje = new Date()
    dia = hoje.getDate()
    dias = hoje.getDay()
    mes = hoje.getMonth()
    ano = hoje.getYear()

    if (ano< 2000)    // Y2K Fix, Isaac Powell
       ano = ano + 1900;

    if (dia< 10)
       dia = "0" + dia

    function CriaArray (n) {
       this.length = n
    }

    NomeDia = new CriaArray(7)
    NomeDia[0] = "Domingo"
    NomeDia[1] = "Segunda-feira"
    NomeDia[2] = "Ter&ccedil;a-feira"
    NomeDia[3] = "Quarta-feira"
    NomeDia[4] = "Quinta-feira"
    NomeDia[5] = "Sexta-feira"
    NomeDia[6] = "S&aacute;bado"

    NomeMes = new CriaArray(12)
    NomeMes[0]  = "Janeiro"
    NomeMes[1]  = "Fevereiro"
    NomeMes[2]  = "Mar&ccedil;o"
    NomeMes[3]  = "Abril"
    NomeMes[4]  = "Maio"
    NomeMes[5]  = "Junho"
    NomeMes[6]  = "Julho"
    NomeMes[7]  = "Agosto"
    NomeMes[8]  = "Setembro"
    NomeMes[9]  = "Outubro"
    NomeMes[10] = "Novembro"
    NomeMes[11] = "Dezembro"
    
    document.write (NomeDia[dias] + ", " + dia + " de " + NomeMes[mes] + " de " + ano)
}

function mostraHint(txt, event, pop){
	x = event.x + 8;
	y = event.y + 20;
//	document.body.style.cursor='default';

//	alert(left + '  ' + top);
	var div = document.getElementById(pop)
	
	div.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity=80)"; // filtro para o IE 5.5+
//-moz-opacity:0.7; /* filtro alpha para Mozilla - valores de 0 (transparente) até 1.0 (opaco) */ 
// ou ainda // background:transparent url(alpha.gif) center repeat; // esse ultimo funciona em todos brauzers

	div.style.position = "absolute"
	div.style.top = y
	div.style.left = x
	div.style.width = 150
	div.style.border = "1px dashed #000"
	div.style.backgroundColor = "#ffff99"
	div.style.color = "#f00"
	div.style.textAlign = "center"
	div.style.padding = "7px"
	div.style.display = ""
	div.innerHTML = txt
}

function limpaHint(pop){
	var div = document.getElementById(pop)
	div.style.display = "none"
}

function mudaDinamica(pagina, campo, valor){
	if(campo.substr(0,3) == "st_"){
		tipo_campo = "txt";
	}else if(campo.substr(0,3) == "dt_"){
		tipo_campo = "dat";
	}else{
		tipo_campo = "num";
	}
	mudaPagina('a','pagina_mostra','quadroBusca', 'pagina=' + pagina + '&nome_campo=' + campo + '&valor_campo=' + valor + '&tipo_campo=' + tipo_campo);
}

function  Teste(){
var objeto = event.srcElement;
var tag = objeto.tagName;
var tag2 = objeto.id;
var parentElemt=window.event.srcElement.parentElement.tagName; //Retorna o objeto pai
alert("tag: "+tag); 
alert("tag2: " + tag2);
alert('parentElement: '+parentElemt);
}

function guardaDados(){
	if(document.frm_cadastro.ds_pasta.value != ""){
		document.frm_upload.pasta_galeria.value = document.frm_cadastro.ds_pasta.value;
	}
	document.frm_upload.submit();
}

//valida CPF
function validaCpf(cpf){ 
	var i;
	cpf = cpf.substr(0,3) + cpf.substr(4,3) + cpf.substr(8,3) + cpf.substr(12,2);
	var c = cpf.substr(0,9); 
	var dv = cpf.substr(9,2); 
	var d1 = 0; 
	for (i = 0; i < 9; i++) { 
		d1 += c.charAt(i)*(10-i); 
	} 
	if (d1 == 0){
		alert("CPF Invalido") 
		return false; 
	} 
	d1 = 11 - (d1 % 11); 
	if (d1 > 9) d1 = 0; 
	if (dv.charAt(0) != d1){ 
		alert("CPF Invalido") 
		return false;  
	}
	d1 *= 2; 
	for (i = 0; i < 9; i++){ 
		d1 += c.charAt(i)*(11-i); 
	} 
	d1 = 11 - (d1 % 11); 
	if (d1 > 9) d1 = 0; 
	if (dv.charAt(1) != d1){ 
		alert("CPF Invalido")
		return false; 
	} 
	return true; 
} 

						/* CNPJ */
function validaCnpj(cnpj) {
	CNPJ = cnpj;
	erro = new String;
	if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! \n\n"; 
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
		if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
	}
	//substituir os caracteres que não são números
	if(document.layers && parseInt(navigator.appVersion) == 4){
		x = CNPJ.substring(0,2);
		x += CNPJ. substring (3,6);
		x += CNPJ. substring (7,10);
		x += CNPJ. substring (11,15);
		x += CNPJ. substring (16,18);
		CNPJ = x; 
	} else {
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace ("-","");
		CNPJ = CNPJ. replace ("/","");
	}
	var nonNumbers = /\D/;
	if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n"; 
	var a = [];
	var b = new Number;
	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (i=0; i<12; i++){
		a[i] = CNPJ.charAt(i);
		b += a[i] * c[i+1];
	}
	if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
	b = 0;
	for (y=0; y<13; y++) {
		b += (a[y] * c[y]); 
	}
	if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
	if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
		erro +="CNPJ Inválido!";
	}
	if (erro.length > 0){
//		alert(erro);
		return false;
	}
	return true;
}
			/* CNPJ */

//Envia o formulario de cadastro
function cadastrarDados(){
	cpfOk  = false;
	cnpjOk = false;
	docsOk = true;
	emailOk = true;
	var temCampo = document.getElementsByName("st_documento");
//	var temEmail = document.getElementsByName("st_email");
	if(temCampo[0] != undefined){
		cnpj_cpf = document.frm_cadastro.st_documento.value;
		if(cnpj_cpf != ""){
			if((cnpj_cpf.substr(11, 4) >= '0001') && (cnpj_cpf.substr(11, 4) <= '9999')){
				if(validaCnpj(cnpj_cpf)){ 
					cnpjOk = true;
				}else{
					alert("CNPJ Inválido!");
					document.frm_cadastro.st_documento.focus();
					document.frm_cadastro.st_documento.select();
				}
			}else{
				cpfOk  = validaCpf(cnpj_cpf);
			}
			if(cpfOk || cnpjOk){
				docsOk = true;
			}else{
				docsOk = false;
			}
		}else{
			docsOk = true;
		}
	}
	if(docsOk == true && emailOk == true){
		document.frm_cadastro.submit();
	}
}

function visualizaInfo(){
	window.open('', 'janelaVisualiza', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,menubar=no,width=790,height=560');
	with(document.frm_informativo){
		opcao.value = '1';
		action = "ver-info.php";
		target = "janelaVisualiza";
		submit();
	}
}

function enviaInfo(){
	with(document.frm_informativo){
//		opcao.value = '2';
		action = "envia_info_remoto.php";
		target = "_blank";
		//target = "ifr_executa";
		submit();
	}
}

function salvaInfo(){
	with(document.frm_informativo){
		opcao.value = '3';
		target = "_self";
		submit();
	}
}

function escondeInfo(){
	divInfo = document.getElementById("visualiza_info");
	divInfo.style.display = 'none';
}

function insereFigNoticia(informativo, noticiaNum){
	num = eval(noticiaNum)
	nova_janela = window.open('','insere_fig_noticia','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,menubar=no,width=500,height=120');
	nova_janela.document.writeln('<HTML><HEAD><TITLE>GeniCMS - Sistema Gerenciador de Conteúdo</TITLE>');
	nova_janela.document.writeln('<LINK href="extras/estilo_cms.css" rel="stylesheet" type="text/css">');
	nova_janela.document.writeln('</HEAD><BODY style="background: #ffffff; text-align: center; margin-top: 5px;">');
	nova_janela.document.writeln('<FORM name="frm_upload_fignoticia_' + num + '" action="upload_imagem.php" method="POST" enctype="multipart/form-data">');
	
	nova_janela.document.writeln('<INPUT type="hidden" name="id" value="'+ informativo +'_' + noticiaNum + '">');
	nova_janela.document.writeln('<INPUT type="hidden" name="pasta" value="informativo">');
	nova_janela.document.writeln('<INPUT type="hidden" name="espec" value="if">');
	nova_janela.document.writeln('<P>Enviar Figura para a Notícia ' + num + ': </P><DIV class="campo">');
	nova_janela.document.writeln('<INPUT type="file" name="imagem" style="width: 308px" class="formularios">');
	nova_janela.document.writeln('<INPUT type="submit" value="Enviar Figura ' + num + '" class="formularios"></DIV></FORM>');
	
	nova_janela.document.writeln('<BR><A href="javascript:window.close()" title="Clique aqui para fechar" class="btFecha">Fechar</A>');
	nova_janela.document.writeln('</BODY></HTML>');
	
	nova_janela.document.close();
}

// function abreTitulo(c){
// 	campo = eval(c);
// 	campo.value += '&t>';
// 	campo.focus();
// }

// function fechaTitulo(c){
// 	campo = eval(c);
// 	campo.value += '<t&';
// 	campo.focus();
// }

function addCamposEspec(texto, nuCampos, campoEspec){
	arrCampos = new Array(nuCampos); // Cria um novo Array
	for(var i = 0; i < nuCampos; i++){ 
		posicao = texto.indexOf("|"); // Tem que haver um sobrando no final da string
		arrCampos[i] = texto.substring(0,posicao); // Acrescenta um por um no array
		texto = texto.substring(posicao+1,texto.length); // Exlui a parte separada e pega o restante da string
	}
// 	for(var i = 0; i < arrCampos.length; i++){
// 		alert(arrCampos[i] + ' => ' + arrCampos.length);
// 	}

	// Monta a tela e joga dentro da div
	var nuEspec = eval(document.frm_add_espec.nu_espec.value) + 1; // Acrescenta o ID
	// Joga o ID acrescentado no campo hidden do formularios add_espec e frm_cadastro
	document.frm_add_espec.nu_espec.value = nuEspec;
	eval(campoEspec).value = nuEspec; // Campo com o nome que veio do banco
	
	// Começa no 2 pq os dois primeiros campos da tabela são (id_tabela_pai e id_especificacao)
	textoCampos = '<table width="100%"><tr><td>Tam.: <input type="text" name="' + arrCampos[2] + '_' + nuEspec + '" value="" class="formularios" size="1" maxlength="2"></td>';
	textoCampos = textoCampos + '<td>Cor.: <input type="text" name="' + arrCampos[3] + '_' + nuEspec + '" value="" class="formularios" size="14"></td>';
	textoCampos = textoCampos + '<td>Qtd.: <input type="text" name="' + arrCampos[4] + '_' + nuEspec + '" value="" class="formularios" size="2"></td>';
	textoCampos = textoCampos + '<td><input type="button" value="" class="formularios" style="color: #ffffff; border: #ffffff; width: 105px" disabled></td></tr></table>';
// 	alert(textoCampos);
	
	// Implementar criação dos campos automatica puxando padrões para cada tabela
// 	alert(arrCampos[0] + '_' + nuEspec);
// 	for(var i = 1; i < arrCampos.length; i++){
// 		textoCampos += "&nbsp;&nbsp;Tam.: <input type="text" name="espec_tamanho_' + nuEspec + '" value="" class="formularios" style="width: 25px" maxlength="2">";
// 	}
	
	var especs = document.getElementById('caixa_especs');
	especs.innerHTML = especs.innerHTML + textoCampos;
}

function mostraQtde(paragr, checkbox){
	alert(paragr + ' - ' + checkbox);
	checkbox = eval(document.frm_cesta.checkbox);
	if(checkbox.checked){
		document.getElementById(paragr).style.display='';
	}else{
		document.getElementById(paragr).style.display='none';
	}
}

// Tres casas decimais
function formataFloat(fld, milSep, decSep, e, qtasCasas) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 13) 
		return true;
	key = String.fromCharCode(whichCode);  // Valor para o código da Chave
	if (strCheck.indexOf(key) == -1) 
		return false;  // Chave inválida
	len = fld.value.length;
	for(i = 0; i < len; i++)
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
	aux = '';
	for(; i < len; i++)
		if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	if(qtasCasas == 3){
		if (len == 1) fld.value = '0'+ decSep + '00' + aux;
		if (len == 2) fld.value = '0'+ decSep + '0' + aux;
		if (len == 3) fld.value = '0'+ decSep + aux;
	}else{
		if (len == 0) fld.value = '';
		if (len == 1) fld.value = '0'+ decSep + '0' + aux;
		if (len == 2) fld.value = '0'+ decSep + aux;
	}
	if (len > qtasCasas) {
		aux2 = '';
		for (j = 0, i = len - (qtasCasas + 1); i >= 0; i--) {
			if (j == 3) {
				aux2 += milSep;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		fld.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
			fld.value += aux2.charAt(i);
		fld.value += decSep + aux.substr(len - qtasCasas, len);
	}
	return false;
}

function validaTurma(){
	if(document.frm_cadastro.ls_turma.value == 0){
		alert('Por favor escolha a turma.');
		return false;
	}else{
		with(document.frm_upload){
			turma.value = document.frm_cadastro.ls_turma.value;
			submit();
		}
	}
}

function salvarMusicas(){
	if(document.frm_cadastro.tem_musicas.value == "1"){
		document.frm_musicas.submit();
	}else{
		document.frm_cadastro.submit();
	}
}

function validaMusicas(){
	alert(document.frm_musicas.st_caminho[0].value);
	return false;
}

function FormataReais(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 13) 
		return true;
	key = String.fromCharCode(whichCode);  // Valor para o código da Chave
	if (strCheck.indexOf(key) == -1) 
		return false;  // Chave inválida
	len = fld.value.length;
	for(i = 0; i < len; i++)
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
	aux = '';
	for(; i < len; i++)
		if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 2) {
		aux2 = '';
		for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += milSep;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		fld.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
			fld.value += aux2.charAt(i);
		fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}

function gravaAlteracao(tabela, campo, novoValor, id1, id2){
	window.open('altera-dado-lista.php?tabela='+tabela+'&campo='+campo+'&novovalor='+novoValor+'&id1='+id1+'&id2='+id2, 'ifr_upload');
}

function selecionarTodosRegistros(totRegs, tipo){
	for(var i = 1; i <= totRegs; i++){
		if(tipo == "des"){
			document.getElementById('selec_'+i).checked=false;
			document.getElementById('linkSelecionaTodas').href = "javascript: selecionarTodosRegistros("+totRegs+", 'sel');";
			document.getElementById('linkSelecionaTodas').innerHTML = "Selecionar Todos";
		}else if(tipo == "sel"){
			document.getElementById('selec_'+i).checked=true;
			document.getElementById('linkSelecionaTodas').href = "javascript: selecionarTodosRegistros("+totRegs+", 'des');";
			document.getElementById('linkSelecionaTodas').innerHTML = "Desmarcar Todos";
		}
	}
//	document.getElementById('linkSelecionaTodas').href = "javascript:selecionarTodosRegistros("+totRegs+")";
}

function imprimirRegistros(totRegs, tabela){
	var sels = "";
	if (totRegs > 50) { totRegs = 50; }

	for(var i = 1; i <= totRegs; i++){
//		alert(document.getElementById('selec_'+i).value);
//		alert(totRegs);
		if (document.getElementById('selec_'+i).checked == true) {
			if (i > 1) { sels += "&"; }
			sels += "ids[]="+document.getElementById('selec_'+i).value;
		}
	}
	
	if (sels != "") {
		window.open('impressao.php?tab='+tabela+'&'+sels, '_blank');
	} else {
		alert("Selecione o(s) registro(s) a ser(em) impresso(s).");
	}
}

function ativaDesa(id) {
	window.open("extras/busca_reg.php?proda[id]="+id, "ifr_atualiza");
}

function mudaPreco(id, preco) {
	if (!preco) {
		window.open("extras/busca_reg.php?prodvl[id]="+id, "ifr_atualiza");
	} else {
		var nvl = prompt("Digite o novo preço: (Utilize PONTO para separar casas decimais, ex: 28.50)", preco);
		if (nvl > 0) {
			window.open("busca_reg.php?prodvl[id]="+id+"&prodvl[nvl]="+nvl, "ifr_atualiza");
		} else {
			alert('É preciso que seja um número!');
		}
	}
}

function imprimirCarterinhas(totRegs) {
	var sels = "";
	if (totRegs > 50) { totRegs = 50; }

	for(var i = 1; i <= totRegs; i++){
//		alert(document.getElementById('selec_'+i).value);
		if (document.getElementById('selec_'+i).checked == true) {
			if (i > 1) { sels += "&"; }
			sels += "ids[]="+document.getElementById('selec_'+i).value;
		}
	}
	
	if (sels != "") {
//		window.open('http://lilika:8080/amiga/site/carterinha/participante.php?'+ sels, '_blank');
		window.open('http://amigafa.com.br/encontrao/carterinha/participante.php?'+ sels, '_blank');
	} else {
		alert("Selecione o(s) registro(s) a ser(em) impresso(s).");
	}
}

function mudaTransmissao(mudaPara, qual){
	var url = 'muda-status-transm.php?mudapara=' + mudaPara + '&banner=' + qual;
	window.open(url, 'ifr_atualiza');
}
 
function copyToClipboard(s)
{
	if( window.clipboardData && clipboardData.setData )
	{
		clipboardData.setData("Text", s);
	}
	else
	{
		// You have to sign the code to enable this or allow the action in about:config by changing user_pref("signed.applets.codebase_principal_support", true);
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

		var clip = Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);
	   if (!clip) return;
	   
	   // create a transferable
	   var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);
	   if (!trans) return;
	   
	   // specify the data we wish to handle. Plaintext in this case.
	   trans.addDataFlavor('text/unicode');
	   
	   // To get the data from the transferable we need two new objects
	   var str = new Object();
	   var len = new Object();
	   
	   var str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);
	   
	   var copytext=meintext;
	   
	   str.data=copytext;
	   
	   trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]);
	   
	   var clipid=Components.interfaces.nsIClipboard;
	   
	   if (!clip) return false;
	   
	   clip.setData(trans,null,clipid.kGlobalClipboard);	   
	}
}