/*_____________________________________Validadores ___________________________________*/

//valida numero
function numero(n){if(!n.match(/^[-]?[0-9]*$/)){return true}else{return false}}

//valida valor
function moeda(n){if(!n.match(/^[0-9,\.]*$/)){return true}else{return false}}

//valida e_mail
function mail(email){if(!email.match(/[A-Za-z0-9_.-]+@([A-Za-z0-9_-]+\.)+[A-Za-z]{2,4}/)){return true}else{return false}}

//valida telefone
function telefone(fone){if(!fone.match(/^[0-9,]*$/)||fone.length<7){return true}else{return false}}

//valida cep
function cep(cep){if(!cep.match(/^[0-9]*$/)||cep.length<8){return true}else{return false}}

//valida data
function data(data){if (data.match(/(0[1-9]|[12][0-9]|3[01])(\/)(0[1-9]|1[012])(\/)[12][0-9]{3}/)){return true}else{return false}}

//Valida cpf
function cpf(cpf){
	while (cpf.match(/[^0-9]/))	cpf=cpf.replace(/[^0-9]/,'')
	if (cpf.length==11){
		c=cpf.substr(0,9);
		v=cpf.substr(9,2);
		d=0;
		val=true;
		for (j=0;j<9;j++){
			d+=c.charAt(j)*(10-j);
		}
		d==0 ? val=false:null;
		d=(11-(d%11))>9 ? 0:11-(d%11);
		v.charAt(0)!=d ? val=false:null;
		d*=2;
		for (j=0;j<9;j++){
			d+=c.charAt(j)*(11-j);
		}
		d=(11-(d%11))>9 ? 0:11-(d%11);
		v.charAt(1)!=d ? val=false:null;
		cpf.match(/0{11}|1{11}|2{11}|3{11}|4{11}|5{11}|6{11}|7{11}|8{11}|9{11}/) ? val=false:null;
	} else {
		val=false
	}
	return val 
}

//validaCGC
function cgc(cnpj){
	while (cnpj.match(/[^0-9]/))cnpj=cnpj.replace(/[^0-9]/,'')
	val=0;
	ind=2;
	for (y=12;y>0;y--){
		val+=cnpj.substr(y-1,1)*ind;
		ind>8 ? ind=2 : ind++;
	}
	val%=11;
	val==0||val==1 ? val=0 : val=11-val;
	val!=cnpj.substr(12,1)||cnpj.length!=14 ? vc=false : vc=true;
	return vc;
}

//funcao de busca 
function w_usuario(pai,param){
	wdor.innerHTML=param==0 ?"<b>Buscar: </b><input type=text name=wr class=text maxlenght=30><input type=button class=button onclick=\"window.location='?pai="+pai+"&w='+wr.value\" value='ok'><input type=button value=' x ' onclick=w_usuario(1) class=button>":'';
}

/*_____________________________________Sistema________________________________________*/

//função de postagem
function posta(id,valor,nome){
	conf= nome=='apaga' ? confirm('O item excluído não\npoderá mais ser recuperado\n\nDeseja realmente continuar'):conf=true
	conf? window.location='?pai='+pai.value+'&i='+i.value+'&id='+id+'&'+nome+'='+escape(valor):null;
}
//função de postagem
function pajax(id,valor,nome){
	re = new RegExp('>(.*?)<','g');
	cha=bkp.match(re).toString().substring(1)
	cha=cha.substring(0,cha.length-1)
	bkp=bkp.replace('>'+cha+'<','>'+(nome=='senha'?'********':valor)+'<')
	bkp=bkp.replace("'"+cha+"'","'"+(nome=='senha'?'********':valor)+"'")
	document.getElementById(nome+id).innerHTML=bkp
	carrega('?id='+id+'&'+nome+'='+valor,'jax')
}
//Gera caixa
caixa=true
function c(id,nome,valor,tamanho,caracteres,tipo){
	if (caixa){
		l=document.getElementById(nome+id)
		bkp=l.innerHTML
		valor=unescape(valor)
		while (valor.match('"'))valor=valor.replace('"','&xquot;')
		l.innerHTML='<input type=text name='+nome+' value="'+valor+'" class=text size='+tamanho+' maxlength='+caracteres+' onclick=this.select()>'+ (tipo==0?'<input type=button onclick=posta('+id+','+nome+'.value,"'+nome+'") value=ok class=button>':'<input type=button onclick=pajax('+id+','+nome+'.value,"'+nome+'") value=ok class=button>')+'<input type=button value=" X " class=button onclick=retorna('+id+')>'
	} else {
		l.innerHTML=bkp
		caixa=true
		c(id,nome,valor,tamanho,caracteres,tipo)
	} 
	caixa=false
}
function retorna(id){
	!caixa ? l.innerHTML=bkp:null;
	caixa=true
}

mu=''
acao=0
//Gera caixa suspensa
function pot(a,b,c,d,e){//id,valor,label,tamanho
	mu=a
	ir=c	
	acao=e
	texto.style.width=d
	labl.innerHTML=c
	texto.value=b	
	ver('barra3',event)
}

//gera botao select
function men(a,b,c,d,e,f,g,h,j){//id,selecionar,array,label,excluir,exclui,limpa,acao
	mu=a
	ir=d
	acao=j
	labe.innerHTML=d
	ver('barra2',event)
	if (g==0) while (meu.length>0) meu.remove(0)
	for (ii=0;ii<c.length;ii++) {
		if (c[ii]){
			if (f==1&&h[ii]==e){
			} else {
				var opt = document.createElement('OPTION')
				meu.options.add(opt)
				opt.innerText = c[ii]
				opt.value = h[ii]
				h[ii]==b?opt.selected=true:null
			}
		}
	}
}

//gera niveis
seguranca=0
function niv(sel,se){
	seguranca=se
	ver('barra1',event)
	sel=','+sel
	tes=''
	while (per.length>0) per.remove(0)
	while (neg.length>0) neg.remove(0)	
	for (ii=0;ii<n1.length;ii++) {
			var opt = document.createElement('OPTION')
			sel.match(','+n0[ii]+',')? neg.options.add(opt):per.options.add(opt);
			opt.innerText = n0[ii]==1?'Todos':n1[ii]
			opt.value = n0[ii]
	}
}
//move dados
function mn(ind,dev){
	if (ind>=0){
		a=(dev==0?neg:per)
		b=(dev==0?per:neg)
		var opt = document.createElement('OPTION')
		x=dev==0?document.all.permite:document.all.nega
		a.options.add(opt)
		opt.innerText =x[ind].innerText
		opt.value = x[ind].value
		b.remove(ind)
	}
}
//arrasta objeto
move=0
drag=0
dragObj=''
window.document.onmousemove = mouseMove
window.document.onmousedown = mouseDown
window.document.onmouseup = mouseUp
window.document.ondragstart = mouseStop
function mouseDown(e) {
	if (drag) {
		clickleft=(document.all?window.event.x-parseInt(dragObj.style.left):e.layerX)
		clicktop=(document.all?window.event.y-parseInt(dragObj.style.top):e.layerY)
		dragObj.style.zIndex += 1
		move = 1
	}
}
function mouseStop(e) {
	document.all ? window.event.returnValue = false:e.preventDefault()
}

function mouseMove(e) {	
	if (move) {
		dragObj.style.left=(document.all?window.event.x:e.pageX)-clickleft
		dragObj.style.top=(document.all?window.event.y:e.pageY)-clicktop	
	}
}
function mouseUp() {
	move = 0
}

//exibe camadas
bbkp=null
function ver(cam,com){//camada,comando 
	objeto=document.getElementById(cam)
	if (!location.href.match('editorvisual.php')){
		bbkp?document.getElementById(bbkp).style.visibility='hidden':null
		bbkp=cam
	}
	y=document.all?(event?document.body.scrollTop+window.event.y:null):com.layerY
	x=document.all?(event?document.body.scrollLeft+window.event.x:null):com.layerX		
	if (x+objeto.clientWidth>document.body.clientWidth)x=x-(x+objeto.clientWidth-document.body.clientWidth)-5
	objeto.style.visibility=objeto.style.visibility=='visible'?'hidden':'visible'
	objeto.style.top=y
	objeto.style.left=x
}
function ver_n(cam){
	document.getElementById(cam).style.visibility='hidden'
}

//ativa comandos nas classes
function classe() {
	//fechar
	ix=document.getElementsByName('fecha')
	for (ii=0;ii<ix.length;ii++) ix[ii].onclick=function (){ver_n(this.parentNode.parentNode.parentNode.parentNode.id)}
	//existir
	ni=document.getElementsByTagName('TABLE')
	for (ii=0;ii<ni.length;ii++) if (ni[ii].className=='camada cor3') ni[ii].onmouseover= function () {dragObj=this}
	//arastar
	ic=document.getElementsByName('barra')
	for (ii=0;ii<ic.length;ii++){
		ic[ii].onmouseover= function () {drag=1}
		ic[ii].onmouseout= function () {drag=0}
		ic[ii].onselectstart= function () {return false}
		ic[ii].className='barra cor4'
	}
	//cor
	fi=document.getElementsByName('flip')
	for (ii=0;ii<fi.length;ii++){
		fi[ii].onmouseover= function () {this.className='cor3'}
		if (fi[ii].className=='cor1'){
			fi[ii].onmouseout= function () {this.className='cor1'}
		} else if (fi[ii].className=='cor2') {
			fi[ii].onmouseout= function () {this.className='cor2'}
		}
	}

/*
	tags='TABLE,TR,TD'.split(',')
	for(tag in tags){
	    elements=document.getElementsByTagName(tags[tag])
	    for (ij=0;ij<elements.length;ij++) {
			//Cria camada
			if (elements[ij].className=='camada cor3') elements[ij].onmouseover= function () {dragObj=this}		
			//Barra para arrastar
			if (elements[ij].className=='barra cor4') {
				elements[ij].onmouseover= function () {drag=1}
				elements[ij].onmouseout= function () {drag=0}
				elements[ij].onselectstart= function () {return false}
			}
			//Muda cor
			if (elements[ij].className=='cor1') {
				elements[ij].onmouseover= function () {this.className='cor3'}
				elements[ij].onmouseout=  function () {this.className='cor1'}
			}
			if (elements[ij].className=='cor2') {
				elements[ij].onmouseover= function () {this.className='cor3'}
				elements[ij].onmouseout=  function () {this.className='cor2'}
			}		
		}
	}
*/
}

//Paletas de cores
function cor(){}
function pic(k){
	l=lcp.value
	cor.value=k
	pmc.style.visibility='hidden' 
	if (k!='null'){
		if (l=='backcolor'||l=='forecolor') {
			editar(l,k)		
		} else {
			document.all['c'+l].style.background=k
			document.all[l].value=k
		}
	}
}

function corp(v){
	lcp.value=v
	pmc.style.top=document.body.scrollTop+window.event.y
	pmc.style.left=document.body.scrollLeft+window.event.x
	pmc.style.visibility='visible'
}

//posta enquete
function enquete_posta(id){
	quant=document.enquete_post.r.length
	for (a=0;a<quant;a++){
		if (document.enquete_post.r[a].checked) {
			document.enquete_post.resposta.value=a
			document.enquete_post.submit()
		}
	}
}

//imprime conteudo visualizado
function imprime(camada){
	x_print=window.open('','imprime','toolbar=0,location=0,directories=0,status=0,menubar0,scrollbars=1,resizable=0,width=570,height=600')
	x_print.document.open();
	x_print.document.write('<html><head><title>Imprimir</title><link rel=stylesheet href='+(window.location.href.match("admin")?'../':'')+'_gravar/css.css></head><body topmargin=0 leftmargin=0 onload=self.print()><table border=0 width=550 cellspacing=0><tr><td>'+camada.innerHTML+'</td></tr></table></body></html>')
	x_print.document.close()
}

//funções ajax
var req;
camada='';
function carrega(url,cam,pos){
	po=''
	camada=cam
	if (cam=='jax'&&jax)jax.style.visibility='visible'
	req = null;
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try {
			req = new ActiveXObject('Msxml2.XMLHTTP.4.0');
		} catch(e) {
			try {
				req = new ActiveXObject('Msxml2.XMLHTTP.3.0');
			} catch(e) {
				try {
				req = new ActiveXObject('Msxml2.XMLHTTP');
				} catch(e) {
					try {
						req = new ActiveXObject('Microsoft.XMLHTTP');
					} catch(e) {
						req = false;
					}
				}
			}
		}
	}
	url=pos?pos.action:url
	if (req) {
		req.open((pos?'POST':'GET'), (url+''+(url.match("\\?")?'&':'?')+'random='+Math.random()), true);
		if (pos) {
			for (fi=0;fi<pos.length;fi++) po+=pos[fi].name+'='+escape(pos[fi].value)+'&'
			req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
			req.setRequestHeader('Content-length', po.length);
			req.setRequestHeader('Connection', 'close');
		}
		req.onreadystatechange = processa;
		req.send((pos?po:null));
		
	}	
}

function processa(){
	if (req.readyState == 4) {
		if (document.getElementById('jax')!=null) ver_n('jax')
		if (req.status == 200) {			
 			camada!='jax'?document.getElementById(camada).innerHTML = unescape(req.responseText):'';
		} else { 
			alert('Houve um problema ao obter os dados:'+req.statusText);
		}
	}
}

//menu horizontal
function menum(Menu,e){
	ie=document.all
	if (window.menu&&menu.id!=Menu.id) menue(menu)
   		menu=Menu
		menu.style.visibility=="hidden"?menu.style.visibility="visible":menue()
		menu.style.left=document.body.scrollLeft+e.clientX-(ie?e.offsetX:e.layerX)
		menu.style.top=document.body.scrollTop+e.clientY-(ie?e.offsetY-15:e.layerY-17)
		ie?event.cancelBubble=true:e.stopPropagation()
}
function menue() {
	if (window.menu) menu.style.visibility="hidden"
}
document.onclick=menue

//escreve banner na tela
function banner(src,largura,altura){
	document.write("<EMBED src='"+src+"' wmode=transparent quality=high scale=noscale salign=LT bgcolor=#FFFFFF WIDTH="+largura+" HEIGHT="+altura+" TYPE=application/x-shockwave-flash PLUGINSPAGE=http://www.macromedia.com/go/getflashplayer></EMBED>")
}