/*
 Sintaxe:		object elementoId( string )
 Descr: 		Retorna um ponteiro para o elemento com o ID referenciado por 'id'
 Alterado:		05/01/2004 - Fernando Rodrigo Bilinski
*/

function elementoId(elemID){
	if(document.all){
		return document.all(elemID);
	}
	if (document.getElementById){
		return document.getElementById(elemID);
	}
	if (document.layers){
		return document.layers[elemID];
	}
}


// esta função verifica se um valor inteiro é numérico ou não
function numerico(valor) {
	aux = parseFloat(valor);
	if (aux == valor) return true;
	else return false;
}

// esta função toma as devidas providências quando um campo de formulário não está correto
function acoes(campo,mensagem) {
	alert(mensagem);
	campo.focus();
}

// esta função recebe dois valores, e retorna TRUE caso sejam idênticos, e FALSE caso o contrário
function verificaSenhas(valor1, valor2){
	return (valor1 == valor2);
}

// Abre uma janela centralizada
function abrepop(arquivo, largura, altura){
	alturascr = window.screen.availHeight;
	largurascr = window.screen.availWidth;
	
	pontoesq = parseInt(largurascr/2) - parseInt(largura/2);
	pontotop = parseInt(alturascr/2) - parseInt(altura/2);
	
	checkformw = window.open(arquivo,"formw","toolbar=no, location=no, directories=no, status=yes, menubar=no, scrollbars=no, resizable=no, menubar=no, width=" + largura + ", height=" + altura);
	checkformw.moveTo(pontoesq,pontotop);
	checkformw.focus;
}

// Abre uma janela centralizada
function abrepopscroll(arquivo, largura, altura){
	alturascr = window.screen.availHeight;
	largurascr = window.screen.availWidth;
	
	pontoesq = parseInt(largurascr/2) - parseInt(largura/2);
	pontotop = parseInt(alturascr/2) - parseInt(altura/2);
	
	checkformw = window.open( arquivo,"formw","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, menubar=no, width=" + largura + ", height=" + altura );
	checkformw.moveTo(pontoesq,pontotop);
	checkformw.focus;
}

// Abre uma janela centralizada
function popscrollmult( arquivo, largura, altura, nome ){
	alturascr = window.screen.availHeight;
	largurascr = window.screen.availWidth;
	
	pontoesq = parseInt(largurascr/2) - parseInt(largura/2);
	pontotop = parseInt(alturascr/2) - parseInt(altura/2);
	
	checkformw = window.open(arquivo, nome, "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, menubar=no, width=" + largura + ", height=" + altura );
	checkformw.moveTo(pontoesq,pontotop);
	checkformw.focus;
}

// Verifica se a data respeita o formato: dd/mm/aaaa
function checaData(campo){
	if ((campo.indexOf("/") == 2) && (campo.lastIndexOf("/") == 5) && (campo.length == 10)){
		return true;
	}
	else
	{
		return false;
	}
}

// Funcoes do Dreamweaver

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

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

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

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


function adArquivo( obj ){
	//Campo file atualmente ativo para adicao
	file_atual = document.getElementById('atual').firstChild
	
	//expressão regular para não vazio
	re = /[^ ]+/;
	
	//Testeando se o campo não está vazio
	if( !re.test( file_atual.value ) ){
		alert('Você deve escolher um arquivo antes');
		return false;
	}
	
	rb_id = ( typeof(rb_id) == 'undefined')?0:++rb_id;
	
	rb = document.createElement('input');
	rb.type = 'checkbox';
	rb.id = 'radio_' + rb_id;
	rb.name = 'arq_adicionado';
	rb.value = 'radio_' + rb_id;
	//addEvent( rb, 'click', testar );
	
	basename = file_atual.value;
	basename = basename.split('\\');
	basename = basename[basename.length-1].split('/');

	text    = document.createTextNode( basename[basename.length-1] );
	//text    = document.createTextNode( file_atual.value );

	file_atual.style.display = 'none';
	
	label = document.createElement('label');
	label.htmlFor = 'radio_' + rb_id;
	label.appendChild(rb);
	label.appendChild(text);
	label.appendChild(file_atual);
	
	link = document.createElement('a');
	link.target = '_blank';
	link.href = (file_atual.value);
	link.appendChild(document.createTextNode(' [visualizar]'));;
	
	tr = document.createElement('tr');
	
	td = document.createElement('td');
	td.appendChild(label);
	tr.appendChild(td);
	
	td = document.createElement('td');
	td.width = '1%';
	td.appendChild(link);
	tr.appendChild(td);
	
	tbody = document.createElement('tbody');
	tbody.appendChild(tr);
	table = document.createElement('table');
	table.className = 'textowhite';
	table.width = '100%';
	table.appendChild(tbody);
	
	div = document.createElement('div');
	div.id   = 'file_' + rb.value;
	div.appendChild( table );

	document.getElementById('lista').appendChild( div );

	novo_arq = document.createElement('input');
	novo_arq.type    = 'file';
	novo_arq.className  = file_atual.className;
	novo_arq.style.width = '100%';
	novo_arq.name = file_atual.name;

	document.getElementById('atual').insertBefore( novo_arq, document.getElementById('atual').firstChild );
	
	desabilita_imprimir();
	
	return true;
}

function remArquivo( obj , removertodos ){
	elems = document.forms[0].elements;
	for(i = 0; i < elems.length; i++){
		if( elems[i].name == 'arq_adicionado' && (elems[i].checked||removertodos) ){
			document.getElementById('lista').removeChild( document.getElementById('file_' + elems[i].value) );
			desabilita_imprimir();
			i = 0;
		}
		if( elems[i].name == 'arq_dobanco_temp' && (elems[i].checked) ){
			document.getElementById('anexo' + elems[i].value).style.display='none';
			document.getElementById('o' + elems[i].id).checked=true;
			desabilita_imprimir();
		}
		if( elems[i].name == 'arq_dobanco[]' && (removertodos) ){
			document.getElementById('anexo' + elems[i].value).style.display='';
		}
	}
	return true;
}

// a função analisa retorna false quando string_analise é vazio ou se possui apenas espaços em branco
// e do contrário retorna true
function analisa(string_analise) {
	string_final = ""
	string_teste = ""
	tamanho = string_analise.length;
	// quando string_analise é vazia, o for não é executado
	for (var i=0;i<tamanho;i++) {
		aux = string_analise.substring(i,i+1)
		if (aux == ' ') {
			string_final = string_final + ' ';
	 	}	
		string_teste = 	string_teste + ' ';
   	}
	if (string_teste == string_final)  return false;
	else return true;	
}

// esta função verifica se um valor inteiro é numérico ou não
function numerico(valor) {
	aux = parseFloat(valor);
	if (aux == valor) return true;
	else return false;
}

// esta função valida o email
function valida_email(campo) {
	erro = true;
	p1 = campo.indexOf("@")
	p2 = campo.lastIndexOf(".")
	t = campo.length - 1;
	if((p1==t) || (p2==t) || (p2==-1) || (p1>p2) || ((p2-p1)==1))
	 erro = false;
	return erro;
}

// Verifica se a data respeita o formato: dd/mm/aaaa
function checaData(campo){
	dia = campo.substr(0,2);
	mes = campo.substr(3,2);
	ano = campo.substr(6,4);
	if (
		Number(dia) && 
		Number(mes) && 
		Number(ano) && 
		(campo.indexOf("/") == 2) && 
		(campo.lastIndexOf("/") == 5) && 
		(campo.length == 10)
	){
		return true;
	}
	else
	{
		return false;
	}
}


function validaform(oform){
	oform.salvar = document.getElementsByName('salvar')[0];
	if(oform.salvar.disabled) return false;
	msgErroHeader = 'Os seguintes campos não foram preenchidos corretamente:\n\n';
	msgErroBody = '';
	for(i=0;i<oform.length;i++){
		if(oform.elements[i].type=='submit') continue;
		if(oform.elements[i].type=='reset') continue;
		if(oform.elements[i].type=='button') continue;
		if(oform.elements[i].type=='image') continue;
		if(oform.elements[i].type=='radio'){
			if(oform.elements[i].checked)
				oform.elements['_'+oform.elements[i].name].value = oform.elements[i].value;
			continue;
		}
		if( oform.elements[i].type=='select-one' || oform.elements[i].type=='select-multiple' ){
			oform.elements['_'+oform.elements[i].name].value = oform.elements[i].value;
			continue;
		}
		if( oform.elements[i].type=='textarea'){
			if( analisa(oform.elements[i].value) ){
				oform.elements['_'+oform.elements[i].name].value = 1;
			}else{
				oform.elements['_'+oform.elements[i].name].value = '';
			}
			continue;
		}
		switch( oform.elements[i].accept ){
			case 'obrigatorio':
			if( (oform.elements[i].type=='checkbox' && !oform.elements[i].checked) || !analisa(oform.elements[i].value) )
				msgErroBody += ' * ' + oform.elements[i].title + '\n';
			break;
			case 'numerico':
			if( !numerico(oform.elements[i].value) )
				msgErroBody += ' * ' + oform.elements[i].title + ' (somente números)\n';
			break;
			case 'data':
			if( !checaData(oform.elements[i].value) )
				msgErroBody += ' * ' + oform.elements[i].title + ' (data em formato inválido)\n';
			break;
			case 'email':
			if( !valida_email(oform.elements[i].value) )
				msgErroBody += ' * ' + oform.elements[i].title + ' (e-mail em formato inválido)\n';
			break;
			default:
				if(oform.elements[i].accept) 
					if(oform.elements[oform.elements[i].accept].value!=oform.elements[i].value)
						msgErroBody += ' * ' + oform.elements[i].title + ' (deve ser igual a '+
						oform.elements[oform.elements[i].accept].title+')\n';
		}
	}
	if(msgErroBody){
		alert (msgErroHeader + msgErroBody);
		return false;
	}
	oform.salvar.disabled=true;
	return true;
}

function gE(obj) { return document.getElementById(obj); }
//function loading() { closeAll(); }

function muda_class(obj, botao, new_class)
{
	closeAll();
	var obj = gE(obj);
	obj.style.display = 'block';
}

function closeAll()
{
	gE('smnCap').style.display = "none";
	gE('smnHistoria').style.display = "none";
	gE('smnArena').style.display = "none";	
	gE('smnCT').style.display = "none";	
	gE('smnEquipes').style.display = "none";		
	gE('smnEscolas').style.display = "none";				
	gE('smnNegocios').style.display = "none";
	gE('smnCampeonatos').style.display = "none";
	gE('smnGaleria').style.display = "none";
	gE('smnContato').style.display = "none";
}