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_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function verticalOnly(item) {
	item.toolManDragGroup.verticalOnly()
}

function saveOrder(item) {
	var group = item.toolManDragGroup
	var list = group.element.parentNode
	var id = list.getAttribute("id")
	if (id == null) return

	group.register('dragend', function() {
		ToolMan.cookies().set("list-" + id, 
				junkdrawer.serializeList(list), 365)
	})
}

var dom = document.getElementById;
var iex = document.all;
var ns4 = document.layers;
	
function getElement(name,nest){
	nest = nest ? 'document.'+nest+'.' : '';
	var el = dom ? document.getElementById(name) : iex ? document.all[name] : ns4 ? eval(nest+'document.'+name) : false;
	return el;
}

function expande(elemento) { //função de expansão de elementos div
	diva=getElement(elemento);

	diva.style.display=diva.style.display=='' ? 'none' : '';
}

function cookie_menu(m) { //função que expande e grava cookies dos menus
	expande('menu'+m);

	document.cookie='menu'+m+"="+(diva.style.display!='' ? 'false' : 'true');	
}

elant="";
elatual="";
arrastou=false;
aberto=false;
cor="#DFF6FF";

function show_data(elemento) {
	continua=true;

	if(editando) abre_inclusao(0);
	if(alterado && !editando && id_edicao=="") continua=window.confirm("As alterações realizadas serão perdidas.\n Deseja continuar?");

	if(continua) {
//		alert("continua="+continua+" clicou="+clicou+" !arrastou="+(!arrastou));
		if(clicou && !arrastou) {
			elatual=elemento;

			if(elant!="" && elant!=elemento) {
				expande(elant);
				el=getElement(elant);
				el.innerHTML="";
				elant="";
			} 

			if(elant==elemento) {
				if(ba=getElement("master_fotos")) if(ba.style.display=="") expande("master_fotos");
				el=getElement(elant);
				el.innerHTML="";
				elant="";
				cor="#DFF6FF";
				alterado=false;
				aberto=false;
				quant_itens_sni_ed=0;
				sni_ed=0;
			} else {
				aberto=true;
				cor="#DFF6FF";
				x_exibe_dados_alteracao(elemento, exibe_dados_alteracao);
				elant=elemento;
			}

			if(ordenavel) troca_bullets();

			expande(elemento);

			clicou=false;
		} arrastou=false;
	}
}

function troca_bullets() {
	items=document.getElementById("listagem").getElementsByTagName("li");
	for(x=0; x<items.length; x++) {
		items[x].style.backgroundPosition="12px 8px";
		items[x].style.backgroundImage="url('imgs/det_"+(!aberto ? "seta" : "bullet")+"_rosa.gif')";
	}	
}


function check(campob) {
	campoa=getElement(campob);
	campoa.value=1-campoa.value;	
	img=getElement("check"+campob);

	img.src="imgs/ckeckbox"+(campoa.value==1 ? "_checked" : "")+(id_foto_aberta=="" ? "" : "_2")+".gif";
}

function exibe_dados_alteracao(v) {
//	document.write(v);
	vt=v;
	if(secao_atual==1) {
		v=vt.split("||||");
		vt=v[0];

		qcampos=v[1]


	}
	el=getElement(elatual);
	el.innerHTML=vt;
//	if(ordenavel) {
		count=0;

		pos=v.indexOf("detalhe_ed\[");
		while(pos!=-1) {
		   count++;
		   pos=v.indexOf("detalhe_ed",pos+1);
		}

//		alert(count);
		quant_itens_sni_ed=count;
		sni_ed=count;
//	}

	fecha_aguarde();
}

function registra_click() {
	clicou=true;
	arrastou=false;
}

function retorna_aberto() {
	return aberto;
}


function num(e) {
    if(navigator.userAgent.toUpperCase().indexOf("MSIE")+1) cod=e.keyCode;
    else cod=e.which;
    if(!(cod > 46 && cod < 58) && !(cod==8) && !(cod==0)) return false;
}

//se tivermos uma sessão relacionada, o formulário nos informará
function valida() {
	if(quantidade_de_itens) 
		if(document.form_insercao.txt_buscando_registro.value!="") {
			return show_data(elatual);
		}

	function insere_str(str1) {
		if(string.indexOf(str1)<0) return str1;
		else return "";
	}

	//começamos acreditando que o campo é valido
	valido=true;
	//e por isso esvaziamos a string de resposta
    string="";

	//igualamos os dados vindos do html a outras variáveis
	//isso se dá ao fato que necessitaremos concatenar os campos obrigatórios de 
	//sessões relacionadas, e não queremos estragar as variáveis originais com isso
	c=campos;
	t=tipo;
	o=obriga;

	//se possuímos sessões relacionadas, concatenamos os valores
	if(sessaorelacionada) {
		//ind possuei o números de registro abertos da dessão relacionada
		limite=(aberto  ? sni_ed : sni);

		for(i=(aberto ? 1 : 0); i<=limite; i++) {
			mod=getElement("detalhe"+(aberto ? "_ed" : "")+"["+i+"]");
			if(mod.innerHTML!="") {
				for(a=0; a<camposr.length; a++) {
					//adicionamos os dados do campo às variáveis utilizadas pelo código de validação
					c=c.concat(camposr[a]+"["+i+"]");
					o=o.concat(obrigar[a]);
					t=t.concat(tipor[a]);

				}
			}
		}
	}

	//para cada elemento, fazemos a verificação
	for(i=0; i<c.length ; i++) {
		campou=c[i];

		if(aberto) campou="ed_"+campou;

		campo=document.form_insercao.elements[campou];
		if(t[i]=="text" && campo.value!=":valor_ok:") updateTextArea("textarea_"+campo.name);

		titulo_c=getElement("tit_"+campou);
		tit_campo=titulo_c.innerHTML.replace(":","").replace("<strong>","").replace("</strong>","");

		if(t[i]=="email") {
			if(o[i] && campo.value=="") {
				string+="\n- Campo '"+tit_campo+"' é obrigatório";
				valido=false
				muda_cor(campou,1);			
			} else if (campo.value!="" && !campo.value.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi)) {
				string+="\n- O e-mail digitado no campo '"+tit_campo+"' é inválido";
				valido=false
				muda_cor(campou,1);						
			}
		}


		if(o[i]=="1") {
			//se data...
			if(t[i]=="date") {
				data1=true;
				//picamos a data
				dia=campo.value.substring(0,2);
				mes=campo.value.substring(3,5);
				ano=campo.value.substring(6,10);

				//se um dos três valores está vazio, inválido
				if(dia=="" || mes=="" || ano=="")  {
					string+="\n- Campo '"+tit_campo+"' é obrigatório";
					data1=false;
				} else {
					data1=validadata(campo.value);
					//se a validação retorna data inválida, inválido também!
					if(!data1) string+="\n- A "+tit_campo+" é inválida";
				}
				
				//destaque no campo
				if(!data1) muda_cor(campou,1);
		
				//se valido é true, valido fica igual a data1, que possui true se o campo passsou e false se foi detectado problema
				if(valido) { valido=data1; }
			} else if(t[i]=="text" || t[i]=="textsimple" || t[i]=="select") { //texto ou select? tratamos da mesma maneira! :D
				//campo vazio? inválido!
				if(campo.value=="") {
					string+=insere_str("\n- Campo '"+tit_campo+"' é obrigatório");
					//inválido
					valido=false
					//destaque no campo
					muda_cor(campou,1);
				}
			} else if(t[i]=="option") { //texto ou select? tratamos da mesma maneira! :D
				//campo vazio? inválido!
				if(campo.value!=":valor_ok:") {
					valor=retorna_valor_radio(campou);

					if(valor=="") {
						string+=insere_str("\n- Campo '"+tit_campo+"' é obrigatório");
						//inválido
						valido=false
						//destaque no campo
						muda_cor(campou,1);
					}
				}
			} else if(t[i]=="picture") { //texto ou select? tratamos da mesma maneira! :D
				//campo vazio? inválido!

				if(campo.value=="0") {
					string+=insere_str("\n- Campo '"+tit_campo+"' é obrigatório");
					//inválido
					valido=false
					//destaque no campo
					muda_cor(campou,1);
				}
			} else if(t[i]=="selectm") { //select múltiplo? tratado como select, mas dividimos só pra intuitividade da mensagem
				if(campo.value=="") {
					string+="\n- Selecione pelo menos uma opção para o campo '"+tit_campo+"'";
					valido=false
					muda_cor(campou,1);
				}
			} else if(t[i]=="radio") { //caso radio, precisamos de um loop
				v="";
				//se o campo for preenchido, então passamos direto. caso contrário, não há nada "checkado"
				if(retorna_valor_radio(campou)=="") {
					string+="\n- Campo '"+tit_campo+"' é obrigatório";
					muda_cor(campou,1);
					valido=false;
				}
			} else if(t[i]=="password") { //password exige validação do campo de confirmação
				//os campos de password só são obrigatórios na operação de cadastro, nunca na alteração do registro
				if(campo.value!=":valor_ok:") {
					if(campo.value=="") {
						string+="\n- Campo '"+tit_campo+"' e a confirmação são obrigatórios";
						muda_cor(campou,1);
						valido=false;
					} 
					//se o campo de confirmação é diferente...
					if(campo.value!=document.form_insercao.elements[campou+"_conf"].value) {
						string+="\n- '"+tit_campo+"' e a confirmação não são iguais";
						muda_cor(campou,1);
						valido=false;
					}
				}
			}
		}
	}
	//exibimos e erro e retornamos caso valido seja false e o retornamos
	//o grande lance desse loop é que em nenhum momento precisamos fazer operação "AND" com o valor que válido contêm
	//como só checamos as exceções consideradas como erro, qualquer uma delas seta valido como false.
	//se passarmos direto pelo loop, sem nenhum erro, valido continua com true, setado no início da função! :D
    if(!valido) alert("Erros encontrados: "+string);
    return valido;
}

//javascrtip de formatação de data no campo
function FormataData(Campo,teclapres) {
    if(navigator.userAgent.toUpperCase().indexOf("MSIE")+1) tecla=teclapres.keyCode;
    else tecla=teclapres.which;

    campo=eval("document.form_insercao.elements['"+Campo+"']");
    vr = campo.value;
    vr = vr.replace( "/", "" );
    vr = vr.replace( "/", "" );
    vr = vr.replace( "/", "" );
    tam = vr.length + 1;
	//previsção de que somente números sejam entrados
    if((tecla > 46 && tecla < 58) || (tecla > 95 && tecla < 106)) {
        if( tam > 2 && tam < 5 ) campo.value = vr.substr( 0, tam - 2 ) + '/' + vr.substr( tam - 2, tam );
        if( tam >= 5 && tam <= 10 ) campo.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 ); }
}

//javascript de chamada do calendário
function calendario(Campo) {
	var cal1 = new calendar1(eval("document.form_insercao.elements['"+Campo+"']"));
    cal1.year_scroll = true;
	cal1.time_comp = false;
	cal1.popup();
}

//validação de dado
function validadata(data) {
	//picamos a data do campo
    dia=data.substring(0,2);
    mes=data.substring(3,5);
    ano=data.substring(6,11);

	//validação primária. por ser avançado, o gpix não acredita que registros antes de 1900 serão fornecidas. e numa visão otimista, não acreditamos
	//q esse código resista até o ano 3000! :D
    if(dia>31 || mes>13 || mes<1 || dia<1 || ano<1900 || ano>3000) return false;
	//validação dos meses que não possuem 31 dias
    if(dia==31 && (mes==4 || mes==6 || mes==9 || mes==11)) return false;
	//validação do mês de fevereiro
    if((dia>29 && mes==2) || (dia==29 && mes==2 && (ano%4))) return false;

    return true;
}

valido_user=true;
function envia_insercao_user() {
	x_confirma_usuario(document.form_insercao.usuario.value,valida_existencia_usuario);
	return false;
}

function valida_existencia_usuario(v) {
	fecha_aguarde();	
	valido_user=parseInt(v);
	envia_insercao();
}

function envia_insercao() {
	if(aberto) {
		if(document.form_insercao.txt_buscando_registro.value!="") {
			if(alterado) continua=window.confirm("As alterações realizadas serão perdidas. Deseja continuar?");		
			else continua=true;
			return continua;
		} else {
			envia_edicao(elatual.replace("registro",""));
			return false;
		}
	} else {
		if(editando) {
			valido=valida();
			valores="";

			if(valido) {
				if(secao_atual==2 && !valido_user) {
					titulo_c=getElement("tit_usuario");
					tit_campo=titulo_c.innerHTML.replace(":","");

					alert("\n- Já existe um usuário cadastrado com o login escolhido!");
					muda_cor("usuario",1);
					valido_user=false;
					return false;
				} 
				srelacionada="";

				for(i=0; i<campos.length; i++) {
					campo=document.form_insercao.elements[campos[i]];
					if(tipo[i]=="select") valores+=(valores=="" ? "" : "|||||")+campo.options[campo.selectedIndex].value;
					else if(tipo[i]=="option") valores+=(valores=="" ? "" : "|||||")+retorna_valor_radio(campos[i]);
					else if(tipo[i]=="selectm") {
						valori="";
						for(u=0; u<campo.length; u++) {
							if(campo.options[u].selected) valori+=(valori=="" ? "" : ";")+campo.options[u].value;
						}

						valores=valores+=(valores=="" ? "" : "|||||")+valori;
					} else valores+=(valores=="" ? "" : "|||||")+campo.value;
				}

				if(sessaorelacionada) {
					for(i=0; i<=sni; i++) {
						mod=getElement("detalhe["+i+"]");
						if(mod.innerHTML!="") {
							for(a=0; a<camposr.length; a++) {
								campo=document.form_insercao.elements[camposr[a]+"["+i+"]"];
								if(tipor[a]=="select") srelacionada+=(srelacionada=="" ? "" : (a==0 ? "::registro::" : "|||||"))+campo.options[campo.selectedIndex].value;
								else if(campo.type) srelacionada+=(srelacionada=="" ? "" : (a==0 ? "::registro::" : "|||||"))+campo.options[campo.selectedIndex].value;
								else srelacionada+=(srelacionada=="" ? "" : (a==0 ? "::registro::" : "|||||"))+campo.value;
							}
						}
					}
				}
//				alert(valores);
				x_insere_dados(valores,srelacionada,confirma_insercao);
			}
			return false;
		} else return true;
	}
}

function envia_configuracao() {
	valido=valida();
	valores="";

	if(document.form_insercao.elements["senha_ant"].value!="" || document.form_insercao.elements["senha"].value!="" || document.form_insercao.elements["senha_conf"].value!="") {
		if(document.form_insercao.elements["senha_ant"].value!="") {
			if(document.form_insercao.elements["senha"].value!=document.form_insercao.elements["senha_conf"].value) {
				document.form_insercao.elements["senha_ant"].value="";				
				document.form_insercao.elements["senha"].value="";
				document.form_insercao.elements["senha_conf"].value="";

				exibe_mensagem("- A senha e a confirmação não são iguais");
				muda_cor("senha",1);
				valido=false;
			} else if(document.form_insercao.elements["senha"].value=="") {
				document.form_insercao.elements["senha_ant"].value="";

				exibe_mensagem("- Preencha as novas senhas para que possa haver a alteração");
				muda_cor("senha",1);
				valido=false;			
			}
		} else if(document.form_insercao.elements["senha_ant"].value=="" && (document.form_insercao.elements["senha"].value!="" || document.form_insercao.elements["senha_conf"].value!="")) {
				document.form_insercao.elements["senha"].value="";
				document.form_insercao.elements["senha_conf"].value="";

				exibe_mensagem("- Preencha a senha atual para que possa haver a alteração.");
				muda_cor("senha_ant",1);
				valido=false;	
		}
	}

	if(valido) {
		for(i=0; i<campos.length; i++) {

			if(tipo[i]=="radio") valores+=(valores=="" ? "" : "|||||")+retorna_valor_radio(campos[i]);
			else {
				campo=document.form_insercao.elements[campos[i]];
				if(campo.value!="") valores+=(valores=="" ? "" : "|||||")+campo.value;
			}
		}

		x_configuracao(valores,confirma_configuracoes);
	}

	return false;
}

function confirma_configuracoes(v) {
	if(v==1) {
		exibe_mensagem("Configurações gravadas com sucesso!");
		document.form_insercao.elements["senha"].value="";
		document.form_insercao.elements["senha_conf"].value="";
		document.form_insercao.elements["senha_ant"].value="";
	} else {
		exibe_mensagem(v);
	}
}

function confirma_insercao(v) {
	if(v==1) {
		exibe_mensagem("Registro inserido com sucesso!");
		x_remonta_lista(remonta_lista);	
		abre_inclusao(1);
		limpa_campos();
	} else alerta("Acorreu um erro na inserção de dados! Tente novamente.");
	return false;
}

function limpa_campos() {
	c=campos;
	t=tipo;

	if(sessaorelacionada) {
		//ind possuei o números de registro abertos da dessão relacionada
		for(i=0; i<=sni; i++) {
			mod=getElement("detalhe["+i+"]");
			if(mod.innerHTML!="") {
				for(a=0; a<camposr.length; a++) {
					//adicionamos os dados do campo às variáveis utilizadas pelo código de validação
					c=c.concat(camposr[a]+"["+i+"]");
					t=t.concat(tipor[a]);
				}
			}
		}
	}

	for(i=0; i<c.length ; i++) {
			campo=document.form_insercao.elements[c[i]];
//			alert(campo.type);
			if(campo.type=="textarea") clearTextArea("textarea_"+campo.name);
			else if(t[i]=="text" || t[i]=="textsimple" || t[i]=="date" || t[i]=="email" || t[i]=="number") campo.value="";
			else if(t[i]=="select") campo.selectedIndex=0;
			else if(t[i]=="radio") {
				campos_img=document.getElementsByTagName("input");
				for(ic=0; ic<campos_img.length; ic++) {
					if(!campos_img[ic].id.indexOf(c[i]+"_")) quantidader++;
				}

				for(ic=1; ic<=quantidader; ic++) {
					img=getElement(c[i]+"_b_"+ic);
					img.src="imgs/ckeckbox.gif";
					campoi=getElement(c[i]+"_"+ic);
					campoi.value=0;
				}			
			}
			else if(t[i]=="checkbox") {
				campo.value=0;	
				img=getElement("check"+c[i]);

				img.src="imgs/ckeckbox.gif";
			}
			else if(t[i]=="password") {
				campo.value="";
				campo=document.form_insercao.elements[c[i]+"_conf"];
				campo.value="";
			}
			else if(t[i]=="selectm") ;			
			else if(t[i].indexOf("picture")>=0) {
				campo.value=0;
				prevfot=getElement("preview_fotos"+c[i]);
				prevfot.innerHTML="";
			} else if(t[i]=="dir") {
				campopreview=getElement("preview_fotos"+c[i]);
				campopreview.innerHTML="";				
			}
			else if(t[i].indexOf("file")>=0) {
				campo.value=0;
				prevfot=getElement("preview_fotos"+c[i]);
				prevfot.innerHTML="";
			} else if(t[i]=="dir") {
				campopreview=getElement("preview_fotos"+c[i]);
				campopreview.innerHTML="";				
			}

	}	

	if(ba=getElement("master_fotos")) if(ba.style.display=="") expande("master_fotos");

	return false;
}

function muda_cor(t,s) {
	corm="#FC2A93";		

	encontrei=false;
	for(ig=0; ig<campos.length; ig++) if(campos[ig]==t) encontrei=true;

	if(encontrei) {
		titulo_c=getElement("tit_"+t);

		if(s) {
			titulo_c.style.backgroundColor=corm;
			titulo_c.style.color="#FFF";
		} else {
			titulo_c.style.backgroundColor='';
			titulo_c.style.color="#000";
		}
	}
}

function insertcode(tag, n) {
	textarea = document.form_insercao.elements[n];
    var open="["+tag+"]";
    var close="[/"+tag+"]";

    if(!textarea.setSelectionRange) {
        selected=document.selection.createRange().text; 
        if(selected.length>0) { 
            document.selection.createRange().text=open+selected+close; 
        }
    } else {
        pretext = textarea.value.substring(0, textarea.selectionStart);
        codetext = open + textarea.value.substring(textarea.selectionStart, textarea.selectionEnd) + close;
		inicio=textarea.selectionStart;
		fim=textarea.selectionEnd;
		posttext = textarea.value.substring(textarea.selectionEnd, textarea.value.length)
        if(codetext != open + close) textarea.value = pretext + codetext + posttext;
		textarea.focus();
		textarea.setSelectionRange(inicio, fim+(close.length*2-1)); 
    }
}


//script que exibe div que segue mouse.
/*var trailimage=["", 100, 99] //image path, plus width and height
var offsetfrommouse=[-10,-10] //image x,y offsets from cursor position in pixels. Enter 0,0 for no offset
var displayduration=0 //duration in seconds image should remain visible. 0 for always.

function gettrailobj(){
	if (document.getElementById) return document.getElementById("aguarde").style
	else if (document.all) return document.all.aguarde.style
}

function truebody(){
	return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function followmouse(e){
	var xcoord=offsetfrommouse[0];
	var ycoord=offsetfrommouse[1];

	if (typeof e!="undefined") {
		xcoord+=e.pageX
		ycoord+=e.pageY
	}
	else if (typeof window.event!="undefined") {
		xcoord+=truebody().scrollLeft+event.clientX
		ycoord+=truebody().scrollTop+event.clientY
	}

	var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth-15
	var docheight=document.all? Math.max(truebody().scrollHeight, truebody().clientHeight) : Math.max(document.body.offsetHeight, window.innerHeight)
	gettrailobj().left=(xcoord+50)+"px"
	gettrailobj().top=ycoord+"px"
}*/

function cont_aguarde(i) {
	if(document.getElementById("aguarded").display!="none") { ; }
	else time="";
}

function retorna_dimensoes(){
	var xScroll, yScroll;
	xScroll = document.documentElement["scrollWidth"];
	yScroll = document.documentElement["scrollHeight"];

	return Array(xScroll,yScroll);
}

function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}


faztimet=false;
time="";
function adt(){
	if(faztimet) {
		texto1=document.getElementById("aguarded");

		posY=f_scrollTop();
		texto1.style.top=(posY+topm)+"px";

		time=setTimeout("adt()",200);
	}
}

topm="";

function aguarde() {
	valores=retorna_dimensoes();	

	travatela=document.getElementById("trava")
	imgtravatela=document.getElementById("aguarded")

	travatela.style.width=valores[0]+"px";
	travatela.style.height=valores[1]+"px";

	topo1=document.documentElement["clientHeight"];

	IpopTop=(topo1-imgtravatela.offsetHeight)/2;
	IpopLeft=(valores[0]-100)/2;

	topm=IpopTop;

	imgtravatela.style.left=IpopLeft+document.body.scrollLeft+"px";
	imgtravatela.style.top=IpopTop+document.body.scrollTop+"px";

	travatela.style.display="";
	imgtravatela.style.display="";
	faztimet=true;

	adt();

	cont_aguarde(0);
}



counter_msg="";
function exibe_mensagem(str) {
	counter_msg="";
	divi=getElement("alert");
	divi.innerHTML=str;
	MM_showHideLayers('alert','','show');

	fecha_aguarde();

	counter_msg=setTimeout("fecha()",3000);
}

function fecha_aguarde() {
//	gettrailobj().display="none";
	faztimet=false;
	document.getElementById("trava").style.display="none";
	document.getElementById("aguarded").style.display="none";
	time="";
}

campo_fotos="";

function abre_fotos(campof,idcampo) {
	muda_cor(campof,0);			

	campo_fotos=campof;
	
	if(!(document.form_insercao.diretorio_form.value<0)) {
		c=getElement("diretorios");
		c.innerHTML="";
	}
	c=getElement("fotos");
	c.innerHTML="";
	valor_dir="";

	valor="";
//	if(document.form_insercao.diretorio_form.value>=0) {
		campofotos=getElement(campo_fotos);
		valor_dir=campofotos.value;
		tant=valor_dir;
		valor=campofotos.value;
//	} 

	document.getElementById("frame_fotos").src="includes/inc_adicionar_imagem.php?s="+secao_atual+"&c="+idcampo+"&dir1="+(valor_dir=="0" ? 1 : valor_dir);

	document.form_insercao.elements["id_campo_img"].value=idcampo;

	x_retorna_lista_fotos(campof,valor,idcampo,valor_dir,exibe_lista_fotos);
}

function exibe_lista_fotos(v) {
//	alert(v);
	v=v.split("|");

	divfotos=getElement(v[0]=="0" ? "diretorios" : "fotos");
	divfotos.innerHTML=v[1];

	mf=getElement("master_fotos");
	if(mf.style.display=="") expande("master_fotos");	

	expande("master_fotos");
	fecha_aguarde();

	if(v[0]=="0") if(v[2]!=0) seleciona_dir('','',v[2],true);
}

function fecha_fotos() {
	cont_aguarde(0);

	if(document.form_insercao.diretorio_form.value<0) {
		quantidadeimg=0;
		campos_img=document.getElementsByTagName("input");
		for(i=0; i<campos_img.length; i++) {
			if(!campos_img[i].id.indexOf(campo_fotos.replace("ed_","")+"_")) quantidadeimg++;
		}

		campofotos=getElement(campo_fotos);
		campopreview=getElement("preview_fotos"+campo_fotos);
		campofotos.value="";
		campopreview.innerHTML="<br />";

		entrei=false;
		for(i=1; i<=quantidadeimg; i++) {
			campoi=getElement(campo_fotos.replace("ed_","")+"_"+i);
			if(campoi.value=="1") {			
				idi=campoi.name.replace(campo_fotos.replace("ed_","")+"_","");
				campofotos.value+=(campofotos.value=="" ? "" : ";")+idi;
				x_retorna_campo_imagem("preview_fotos"+campo_fotos,idi,mostra_imagem);
				entrei=true;
			}
		}

		if(!entrei) expande("master_fotos");


		campo_fotos="";
	} else {
		x_retorna_diretorio(document.form_insercao.diretorio_form.value,1,seta_dir);
		tant=0;
	}
}

function mostra_imagem(v) {
	valor=v.split("||");

	campopreview=getElement(valor[0]);
	campopreview.innerHTML+=valor[1];

	expande("master_fotos");
	fecha_aguarde();
}

function seta_dir(v) {
	v1=v.split(";");
	if(v1[0]=="nt") {
		alert("Você deve cortar todas as fotos desse diretório para poder utilizá-lo!");
		makethumb2(v1[1],v1[2]);
	} else {
		campofotos=getElement(campo_fotos);
		campopreview=getElement("preview_fotos"+campo_fotos);
		campofotos.value=document.form_insercao.diretorio_form.value;
		campopreview.innerHTML="<br />"+v;

		document.form_insercao.diretorio_form.value=0;
		campo_fotos="";	
		expande("master_fotos");
	}
	

	fecha_aguarde();
}

function retorna_valor_radio(campo) {
	quantidaderadio=0;
	campos_radio=document.getElementsByTagName("input");
	for(ia=0; ia<campos_radio.length; ia++) {
		if(!campos_radio[ia].id.indexOf(campo+"_")) quantidaderadio++;
	}

	campovalue="";

	for(ia=1; ia<=quantidaderadio; ia++) {
		campoi=getElement(campo+"_"+ia);
		if(campoi.value=="1") {			
			idi=campoi.name.replace(campo+"_","");
			campovalue+=(campovalue=="" ? "" : ";")+idi;
		}
	}
	return campovalue;
}

count=0;

function delete_batch() {
	conta_del=0;
	ids="";

	ids_campos_del="";

	campos_del=document.getElementsByTagName("input");
	for(i=0; i<campos_del.length; i++) {
		if(!campos_del[i].id.indexOf("del_lista")) {
			ids_campos_del+=(ids_campos_del=="" ? "" : ";")+campos_del[i].id.replace("del_lista","");
		}
	}

	ids_campos_del=ids_campos_del.split(";");

	for(i=0; i<ids_campos_del.length; i++) {
		campo=getElement("del_lista"+ids_campos_del[i]);
		if(campo.value==1) {
			conta_del++;
			ids+=(ids=="" ? "" : ";")+campo.name.replace("del_lista","");
		}
	}

	if(!conta_del) alert("Selecione os itens que você deseja deletar.");
	else {
		s=(conta_del>1 ? "s" : "");
		ns=(conta_del>1 ? "ns" : "m");
		resposta=window.confirm("Tem certeza que deseja deletar o"+s+" ite"+ns+" selecionado"+s+"?");

		if(resposta) {
			if(aberto) { 
				if(ba=getElement("master_fotos")) if(ba.style.display=="") expande("master_fotos");
				el=getElement(elatual);
				el.innerHTML="";
				elant="";
				cor="#DFF6FF";
				alterado=false;
				aberto=false;
				quant_itens_sni_ed=0;
				sni_ed=0;

				expande(elatual);
				elatual="";
				troca_bullets();
			}
			x_exclui_dados(ids, confirma_delecao_batch);
		}
	}
}

function confirma_delecao_batch(v) {
	if(!isNaN(v)) {
		s=(v>1 ? "s" : "");
		exibe_mensagem("Registro"+s+" deletado"+s+" com sucesso!");
		x_remonta_lista(remonta_lista);
	} else alert("Acorreu um erro na deleção dos dados! Tente novamente.");
}

function remonta_lista(v) {		
//	alert(v);

	var items = document.getElementById("listagem").getElementsByTagName("li");	

	items_q=items.length;
	ids=v.split("||");
	ids_q=ids.length;

	nao_encontrado_lista=nao_encontrado_ids="";

	for(x=0; x<items_q; x++) {
		encontrei=false;
		for(y=0; y<ids_q; y++) {
			if(items[x].getAttribute("itemID")==ids[y]) {
				encontrei=true;
				break;
			}
		}

		if(!encontrei) nao_encontrado_ids+=(nao_encontrado_ids=="" ? "" : ";")+items[x].getAttribute("itemID");
	}


	nova_div=document.getElementById("area_dados");
	ndiv=document.createElement("div");

	if(nao_encontrado_ids!="") {
		novo="";

		nao_encontrado_ids+=";"

		idsd=nao_encontrado_ids.split(";");

		var items = document.getElementById("listagem").getElementsByTagName("li");	
		items_q=items.length;

		for(h=0; h<items_q; h++) {
			encontrei=false;
			for(y=0; y<idsd.length-1; y++) {
				if(items[h].getAttribute("itemID")==idsd[y]) {
					encontrei=true;
				}
			}
			
			if(encontrei) {
				try {
					nova_div.removeChild(items[h]);
					h--;
					items_q--;
				} catch(x) {
					alert(x);
				}

				quantidade_de_itens--;
			}
		}
	}

	var items = document.getElementById("listagem").getElementsByTagName("li");
	items_q=items.length;

	for(j=0; j<ids_q; j++) {
		encontrei=false;
		for(t=0; t<items_q; t++) {
			if(items[t].getAttribute("itemID")==ids[j]) {
				encontrei=true;
			}
		}
		if(!encontrei) nao_encontrado_lista+=(nao_encontrado_lista=="" ? "" : ";")+ids[j];
	}
	
	x_retorna_codigo_linha(qt_items_acumula,nao_encontrado_lista,controla_linha);

	fecha_aguarde();
}

function controla_linha(v) {
	v=v.split("||||");

	if(v[0]!="") {		
		try	{
			lin=document.createElement("li");
			a1=v[0].split("||");
			lin.style.background="url('imgs/det_"+(a1[0])+"_rosa.gif') no-repeat 12px 8px;";
			lin.setAttribute("itemID",a1[1]);
			if(a1[2]=="1") lin.onmouseup=grava_ordena;
			lastid=a1[1];

			lin.innerHTML=a1[3];
		} catch (x) {
			alert("a="+x);
		}

		items=document.getElementById("listagem").getElementsByTagName("li");
		lista=document.getElementById("listagem");

		nova_div=document.getElementById("area_dados");
		d=document.createElement("div");

		novo="";

		imprime=imprimiu=false;

		quantidade_total=parseInt(v[1]);

		if(v[2]=="") {
			d.appendChild(lin);
			imprimiu=true;
		}

		try	{
			for(h=0; h<(items.length);) {
				if(imprime) {
					d.appendChild(lin);
					imprime=false;
					imprimiu=true;
				}

				if((items[h].getAttribute("itemID")==parseInt(v[2])) && !imprimiu) imprime=true;
				d.appendChild(items[h]);
			}

			if(!imprimiu && h<=quantidade_max && v[0]!="") {
				d.appendChild(lin);
				imprimiu=true;
			}

			if(imprimiu && h<quantidade_max) {
				quantidade_de_itens++;
				qt_items_acumula++;
			}

			nova_div.innerHTML=d.innerHTML;
		} catch (x) {
			alert(x);
		}	

	}

	if(ordenavel) {
		re=new RegExp("itemid=\""+lastid+"\"", "i")  

		document.getElementById("listagem").innerHTML=document.getElementById("listagem").innerHTML.replace(re,"itemID=\""+lastid+"\" onMouseUp=\"grava_ordena()\"");
//		alert(document.getElementById("listagem").innerHTML);
		dragsort.makeListSortable(document.getElementById("listagem"),verticalOnly, saveOrder);
	}


	if(quantidade_de_itens==1 && page_p!=0) window.location=page_ant+(page_p-1);
	else x_paginacao(exibe_paginacao);

	fecha_aguarde();
} 

function exibe_paginacao(v) {
	dados_p=v.split("||||");
	exibe_i=getElement("itens");
	exibe_p=getElement("numeros");
	if(dados_p[1]!="") {
		exibe_i.style.display='';
		exibe_i=getElement("txt_itens");
		exibe_i.innerHTML=dados_p[1];

		exibe_p.style.display='';
		exibe_i=getElement("txt_paginas");
		exibe_i.innerHTML=dados_p[0];
	} else {
		exibe_i.style.display='none';
		exibe_p.style.display='none';
	}
}

editando=false;

ja_fiz_textarea=Array();

function abre_inclusao(act) {
	if(secao_atual!=0) {
		continua=true;
			
		if(alterado && !act) continua=window.confirm("As alterações realizadas serão perdidas. Deseja continuar?");		

		if(continua) {
			if(aberto) {
				alterado=false;
				clicou=true;
				show_data(elatual);
			}
		
			expande('inclusao1');

			tareas=document.getElementById("inclusao1").getElementsByTagName("textarea");
			for(a=0; a<tareas.length; a++) {
				acheit=false;

				for(b=0; b<ja_fiz_textarea.length; b++) if(tareas[a].id==ja_fiz_textarea[b]) acheit=true;

				if(!acheit) {
					setTimeout("rtextarea('"+tareas[a].id+"',100)");
					ja_fiz_textarea[ja_fiz_textarea.length]=tareas[a].id;
				}
			}

			ainc=getElement('inclusao1');
			if(ainc.style.display=='none') {
				editando=false;
				alterado=false;

				if(sessaorelacionada) {
					//ind possuei o números de registro abertos da dessão relacionada
					encontrei=false;
					for(i=0; i<=sni; i++) {
						mod=getElement("detalhe["+i+"]");						
						if(mod.innerHTML!="" && !encontrei) encontrei=true;
						else if(encontrei) {
							mod.innerHTML="";
							quant_itens_sni--;	
						}
					}
				}
				limpa_campos();		
			} else {
				editando=true;
				items=ainc.getElementsByTagName("input");

				items[0].focus();
			}
		}
	}
}

function deleta(idd) {

	if(window.confirm("Tem certeza que deseja excluir esse item?")) x_exclui_dados(idd, confirma_delecao_batch);
}

alterado=false;

function campo_alterado() {
	alterado=true;
}

function insere_foto(act) {
	exibe_mensagem(act==1 ? "Foto enviada com sucesso!" : "Arquivo enviado com sucesso");
	if(act==1) x_remonta_fotos(campo_fotos,"",document.form_insercao.elements["id_campo_img"].value,reescreve_fotos);
	else x_retorna_lista_fotos('','',document.form_insercao.elements["id_campo_img"].value,act,exibe_lista_fotos);
}

function reescreve_fotos(v) {
	v=v.split("|");

	divfotos=getElement(v[0]=="0" ? "diretorios" : "fotos");
	divfotos.innerHTML=v[1];	

	if(v[2]!=0) seleciona_dir('','',v[2]);


	fecha_aguarde();
}

id_foto_aberta="";
function exclui_arquivo(id) {
	if(id=="") id=id_foto_aberta;
	if(window.confirm("Tem certeza que deseja excluir essa imagem?")) x_exclui_arquivo(id, confirma_exclusao_arquivo);
}

function confirma_exclusao_arquivo(v) {
	if(!isNaN(v)) {
		id_foto_aberta="";		
		
		passa=campo_fotos;
		if(v!=0) passa=v;

		exibe_mensagem("Foto excluida com sucesso!");
		x_remonta_fotos(document.form_insercao.elements["id_campo_img"].value,passa,document.form_insercao.elements["id_campo_img"].value,reescreve_fotos);	
	} else alert("Acorreu um erro na deleção da imagem! Tente novamente.");
}

campov_ant=""
function abre_foto_grande(idf,cfoto) {
	id_foto_aberta=idf;
	
	campoi=getElement(campo_fotos.replace("ed_","")+"_"+cfoto);
	campov_ant=campoi.value;

	x_foto_grande(id_foto_aberta,cfoto,preenche_foto_grande);
}

function preenche_foto_grande(v) {
//	alert(v);
	dados=v.split("||");
	id_fgrande=getElement('fotograndeimg');
	id_fgrande.innerHTML=dados[4];

	div_fgrande=getElement('fotogrande');
	div_fgrande.style.width=parseInt(dados[3])+"px";
	div_fgrande.style.marginLeft=-Math.round(parseInt(dados[3])/2)+"px";

	lgfotogrande=getElement("legenda_foto_gde");
	checkfog=getElement(campo_fotos.replace("ed_","")+"_"+dados[2]);

	if(dados[1]!=" ") {
		lgfotogrande.style.width=parseInt(dados[3]-25)+"px";
		lgfotogrande.innerHTML=dados[1];
		lgfotogrande.style.display="";
	} else 
		lgfotogrande.style.display="none";

	checkvfog=getElement("checkc_foto_grande");
	checkvfog.src="imgs/ckeckbox_"+(checkfog.value==0 ? "" : "checked_")+"2.gif";
	document.form_insercao.c_foto_grande.value=checkfog.value;

	id_foto_aberta+="||"+dados[2];

	expande('fotogrande');
	fecha_aguarde();
}

function fecha_foto_grande() {
	id_fgrande=getElement('fotograndeimg');
	id_fgrande.innerHTML="";

	dados=id_foto_aberta.split("||");

	id_foto_aberta="";
		campoi=getElement("c_foto_grande");

		if(campoi.value!=campov_ant) {
			radio(campo_fotos,id_foto_aberta,dados[1]);
			campov_ant="";
		}

	expande('fotogrande');
}

function deleta_foto_aberta() {
	if(window.confirm("Tem certeza que deseja excluir essa imagem?")) {
		valor=id_foto_aberta.split("||");
		x_exclui_arquivo(valor[0], confirma_exclusao_arquivo);		
		expande('fotogrande');
	}
}

function radio(campo, valor, c) {
	quantidader=0;

	if(campo==0) campo=campo_fotos.replace("ed_","");

	if(campo!="imagem") muda_cor(campo,0);

	tipo_r=document.form_insercao.elements[campo+"multiple"].value;

	if(tipo_r==1) {
		campoi=getElement(campo+"_"+c);
		campoi.value=(campoi.value=="0" ? "1" : "0");
		img=getElement(campo+"_b_"+c);
		img.src="imgs/ckeckbox"+(campoi.value=="1" ? "_checked" : "")+".gif";
	} else {
		campos_img=document.getElementsByTagName("input");
		for(i=0; i<campos_img.length; i++) {
			if(!campos_img[i].id.indexOf(campo+"_")) quantidader++;		
		}
		
		for(i=1; i<=quantidader; i++) {
			campoi=getElement(campo+"_"+i);
			campoi.value=(i==c && campoi.value=="0" ? "1" : "0");

			img=getElement(campo+"_b_"+i);
			img.src="imgs/ckeckbox"+(campoi.value==1 ? "_checked" : "")+".gif";
		}
	}
}

function permissao(idp) {
	check(idp);
	x_permissao(idp,nula);
}

function nula(v) { 
	fecha_aguarde();
}

function rcampo(campoid, regid, sessao, lim) {
	x_retorna_campo_edicao(campoid,regid,sessao,lim,seta_campo_edicao);
}

function seta_campo_edicao(v) {
	dados=v.split("|||");
	div_dados=getElement("field_"+dados[1]+"_"+dados[2]);
	div_dados.innerHTML=dados[0];

	campo_alterado();

	div_dados=getElement("head_"+dados[1]+"_"+dados[2]);
	div_dados.onmousedown="";
	div_dados.style.cursor="";

	if(dados[3]=="1") rtextarea("textarea_ed_"+dados[4]);

	fecha_aguarde();
}

id_edicao="";

function envia_edicao(idin) {
	continua=true;
	if(ba=getElement("master_fotos")) 
		if(ba.style.display=="") {
			continua=false;	
			alert("Conclua as operações na área de imagens para poder continuar a edição do registro!");
		}
	
	if(continua) {
		valido=valida();
		valores="";


		if(valido) {
			if(secao_atual==2 && !valido_user) {
				titulo_c=getElement("tit_usuario");
				tit_campo=titulo_c.innerHTML.replace(":","");

				alert("\n- Já existe um usuário cadastrado com o login escolhido!");
				muda_cor("usuario",1);
				valido_user=false;
				return false;
			} 

			for(i=0; i<campos.length; i++) {
//				alert("ed_"+campos[i]+" "+tipo[i]);
				campo=document.form_insercao.elements["ed_"+campos[i]];
				if(tipo[i]=="select" && campo.type!="hidden") valores+=(valores=="" ? "" : "|||||")+campo.options[campo.selectedIndex].value;
				else if(tipo[i]=="option") {
//					alert("ed_"+campos[i]);
					valor=retorna_valor_radio("ed_"+campos[i]);
					if(valor=="") valor=campo.value;
					valores+=(valores=="" ? "" : "|||||")+valor;
				} else if(tipo[i]=="selectm") {
					valori="";
					if(campo.type=="hidden") valori=campo.value;
					else
						for(t=0; t<campo.length; t++) {
							if(campo.options[t].selected) valori+=(valori=="" ? "" : ";")+campo.options[t].value
						}

					valores=valores+=(valores=="" ? "" : "|||||")+valori;
				} else valores+=(valores=="" ? "" : "|||||")+campo.value;
			}

			id_edicao=idin; 

			srelacionada="";

			if(secao_atual==1) {
				srelacionada="";
				for(i=0; i<qcampos; i++) {
					t=document.form_insercao.elements["ct_"+i];
					if(t.type!="hidden") tipo=t.options[t.selectedIndex].value;
					else tipo=t.value;

					nome_campo=document.form_insercao.elements["cn_"+i].value;
					descricao=document.form_insercao.elements["cd_"+i].value;				
					ordem=document.form_insercao.elements["cr_"+i].value;
					opcoes=document.form_insercao.elements["co_"+i].value;
					obriga=document.form_insercao.elements["cb_"+i].value;
					listagem=document.form_insercao.elements["cl_"+i].value;
					busca=document.form_insercao.elements["cu_"+i].value;
					idcam=document.form_insercao.elements["idcam_"+i].value;
					relat_editavel=document.form_insercao.elements["relat_editavel_"+i].value;

					apo=(!i ? "" : "::");

					srelacionada+=apo+nome_campo+"|"+descricao+"|"+ordem+"|"+opcoes+"|"+obriga+"|"+listagem+"|"+busca+"|"+tipo+"|"+idcam+"|"+relat_editavel;
				}

			}

			if(sessaorelacionada) {
				for(i=1; i<=sni_ed; i++) {
//					alert(i);
					mod=getElement("detalhe_ed["+i+"]");
					if(mod.innerHTML!="") {
						id_reg=document.form_insercao.elements["detalhe_id["+i+"]"].value+(srelacionada=="" ? "|||||" : "");
						for(a=0; a<camposr.length; a++) {
//							alert(a+" "+"ed_"+camposr[a]+"["+i+"]");
							campo=document.form_insercao.elements["ed_"+camposr[a]+"["+i+"]"];

//							alert(campo);

							stra=(a==0 ? "::registro::"+(id_reg) : "");
							if(tipor[a]=="select" && campo.type!="hidden") srelacionada+=stra+(srelacionada=="" ? "" : "|||||")+campo.options[campo.selectedIndex].value;
							else srelacionada+=stra+(srelacionada=="" ? "" : "|||||")+campo.value;
						}
					}
				}
			}

//			alert(srelacionada);
			x_edicao(valores,srelacionada,idin,confirma_edicao);
		}
	}
	return false;	
}

function confirma_edicao(v) {

	if(!isNaN(v)) {
		var items=document.getElementById("listagem").getElementsByTagName("li");			
		for(gf=0; gf<items.length; gf++)
			if(items[gf].getAttribute("itemID")==id_edicao) {
				id_edicao="";
				clicou=true;
				alterado=false;
				show_data(elatual);
				items[gf].setAttribute("itemID","-1");
				qt_items_acumula++;
				break;
			}

		x_remonta_lista(remonta_lista);

		id_edicao="";

		exibe_mensagem("Registro alterado com sucesso!");
	} else alert("Acorreu um erro na edição dos dados! Tente novamente.\n"+v);
}


function novo_item() {
	i=0;
	do {
		mod=getElement("detalhe["+(i++)+"]");
	} while(mod.innerHTML=="");
	

	str=new RegExp("\\["+(i-1)+"\\]","g");

	strdigit=new RegExp("tabindex=\"(\\d+)\"","g");

	if(aberto) sni_ed++;
	else sni++

	ap=(aberto ? sni_ed : sni);

	add=mod.innerHTML.replace(str,"["+ap+"]");
	add=add.replace(strdigit,"tabindex=\""+(campos.length+(camposr.length*sni))+"\"");

	divn=document.createElement("div");
	divn.id="detalhe"+(aberto ? "_ed" : "")+"["+ap+"]";

	if(aberto) {
		str=new RegExp("apaga_item\\('","g");
		add=add.replace(str,"apaga_item('_ed");

		str=new RegExp("ed_preview_fotos","g");
		add=add.replace(str,"preview_fotosed_");

		for(o=0; o<camposr.length; o++) {
			str=new RegExp(camposr[o]+"\\["+ap+"\\]","g");
			add=add.replace(str,"ed_"+camposr[o]+"["+ap+"]")
		}

/*		str=new RegExp("name=\"","g");
		add=add.replace(str,"name=\"ed_");
		str=new RegExp("id=\"","g");
		add=add.replace(str,"id=\"ed_");
		str=new RegExp("muda_cor\\('","g");
		add=add.replace(str,"muda_cor('ed_");
		str=new RegExp("FormataData\\('","g");
		add=add.replace(str,"FormataData('ed_");
		str=new RegExp("calendario\\('","g");
		add=add.replace(str,"calendario('ed_");
		str=new RegExp("abre_fotos\\('","g");
		add=add.replace(str,"abre_fotos('ed_");
		str=new RegExp("ed_tit","g");
		add=add.replace(str,"tit_ed");*/
		add+="<input type=\"hidden\" name=\"detalhe_id\["+ap+"\]\" value=\"0\">";
	}

	divn.innerHTML+=add;		
//	alert(add);

	sr=getElement("sdetalhamentos"+(aberto ? "_ed" : ""));
	
	sr.appendChild(divn);

	if(aberto) quant_itens_sni_ed++;
	else quant_itens_sni++;
}

function apaga_item(item) {
	quanti=item.indexOf("_ed[")<0 ? quant_itens_sni : quant_itens_sni_ed;
	
	if(quanti>1) {
		continua=true;

		if(item.indexOf("_ed[")>=0) continua=window.confirm("Tem certeza que deseja excluir esse item?");		
		
		if(continua) {
			mod=getElement("detalhe"+item);
			mod.innerHTML="";
			if(item.indexOf("_ed[")<0) quant_itens_sni--;	
			else quant_itens_sni_ed--;
		}
	} else alert("É necessário deixar pelo menos um detalhemento para esse registro.");
}

quant_itens_sni_ed=1;
sni_ed=0;
qcampos=0;

function alerta(msg) {
	alert(msg);
}

tant=0;
function seleciona_dir(campof,idcampo,valor_dir) {
	if(!(document.form_insercao.diretorio_form.value<0)) {
		id=valor_dir;	
		if(tant!=0) {
			tanta=getElement("dir"+tant);
			tanta.className="";
		}

		t=getElement("dir"+id);
		document.form_insercao.diretorio_form.value=id;

		t.className="open";
		tant=id;

		document.getElementById("bloco_fotos").style.display="";

		x_retorna_lista_fotos('','',document.form_insercao.elements["id_campo_img"].value,valor_dir,true,exibe_lista_fotos);
	}
}

function insere_dir(iddir) {
	exibe_mensagem("Arquivo enviado com sucesso!");
	x_remonta_fotos(campo_fotos,iddir,document.form_insercao.elements["id_campo_img"].value,reescreve_fotos);
}

legenda_aberto="";
valor_antl="";
function legenda(t) {
	if(legenda_aberto=="") {
		texto="";
		if(t.innerHTML!="legenda da foto") texto=t.innerHTML;

		height=t.offsetHeight;

		dados=id_foto_aberta.split("||");

		id_t=(id_foto_aberta=="" ? t.id : dados[0]);

		lege="<textarea style=\"padding:2px; margin: 0px; overflow:auto; height:"+height+"px; "+(id_foto_aberta=="" ? "background-color:#FEDAEC; width:92px;" : " width:"+t.style.width+";")+"\" id=\"c_"+id_t+"\" name=\"c_"+id_t+"\" onBlur=\"grava_legenda();\">"+texto+"</textarea>";

		t.innerHTML=lege;

		legenda_aberto=id_t;
		valor_antl=texto;

		input_legenda=getElement("c_"+id_t);	
		input_legenda.focus();
	}
}

function checa_tecla(e) {
    if(navigator.userAgent.toUpperCase().indexOf("MSIE")+1) tecla=e.keyCode;
    else tecla=e.which;

	if(tecla==13) {
		grava_legenda();
		return false;
	}		
}

function grava_legenda() {
	if(legenda_aberto!="") {
		input_legenda=getElement("c_"+legenda_aberto);

		if(input_legenda.value==valor_antl) muda_legenda(0);
		else x_grava_legenda(legenda_aberto,input_legenda.value,muda_legenda);
	}

	return false;
}

function muda_legenda(v) {
	passa=legenda_aberto;
	if(legenda_aberto.indexOf("lf")<0) passa="legenda_foto_gde";

	box_legenda=getElement(passa);
	input_legenda=getElement("c_"+legenda_aberto);

	box_legenda.innerHTML=(input_legenda.value=="" ? "legenda da foto" : input_legenda.value);

	if(passa!=legenda_aberto) {
		box_legenda=getElement("lf_"+legenda_aberto);
		box_legenda.innerHTML=(input_legenda.value=="" ? "legenda da foto" : input_legenda.value);	
	}

	legenda_aberto="";	
	valor_antl="";
	fecha_aguarde();	
}

function checa_clique() {
	if(legenda_aberto!="") {
		grava_legenda();
	}

	return true;
}

function makethumb(id,w,h,where) {
	var x; 	var y;
	x = (screen.width-w)/2;	y = (screen.height-h)/2;
	
	arquivo=(where=="1" ? "../" : "")+"thumbnail_crop.php?idimg="+id;

	window.open(arquivo,'','scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,width='+w+',height='+h+',left='+x+',top='+y+',window.focus()');
}

function makethumb2(campo,dir,where) {
	w=100; h=100;
	x = (screen.width-w)/2;	y = (screen.height-h)/2;

	arquivo=(where=="1" ? "../" : "")+"thumbnail_crop.php?campo="+campo+"&dir="+dir;

	window.open(arquivo,'','scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,width='+w+',height='+h+',left='+x+',top='+y+',window.focus()');
}

function abrehelp(id,f,w,h) {
	var x; 	var y;
	x = (screen.width-w)/2;	y = (screen.height-h)/2;
	
	arquivo="mostra_help.php?idimg="+id+"&f="+f;

	window.open(arquivo,'','scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,width='+w+',height='+h+',left='+x+',top='+y+',window.focus()');
}

function abregeral(arquivo,w,h,scroll) {
	var x; 	var y;
	x = (screen.width-w)/2;	y = (screen.height-h)/2;

	window.open(arquivo,'','scrollbars='+scroll+',toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,width='+w+',height='+h+',left='+x+',top='+y+',window.focus()');
}

function s_imagem(a,b,c) {
	alterado=true;
	aguarde();
	radio(a,b,c);
	fecha_aguarde();
}

function indexa() { window.location="index.php"; }

//javascript de chamada do calendário
function calendario(Campo) {
	var cal1 = new calendar1(eval("document.form_insercao.elements['"+Campo+"']"));
    cal1.year_scroll = true;
	cal1.time_comp = false;
	cal1.popup();
}

function troca_rdel(id,a) {
	document.getElementById("tit"+(a+1)+"_"+id).style.display="";
	document.getElementById("tit"+(2-a)+"_"+id).style.display="none";
}

function fecha_box_fotos(dir) {
	if(dir) document.getElementById("bloco_fotos").style.display="none";

	expande('master_fotos')
}

function addEvent(obj, type, fn) {
	try {
		if (obj.attachEvent) {
			var idx = __attachedFns.length;
			__attachedFns[idx] = { obj:obj, type:type, fn:fn };
			var dfn = __attachedFns[idx].dfn = __createDecoupledFn(idx);
			obj.attachEvent("on" + type, dfn);
		} else obj.addEventListener(type, fn, false);
	} catch(x) {
		alert(x);
	}
}

function rtextarea(idt) {
	generate_wysiwyg(idt);
}