var elemento;
var editar = false;

function HabEdit(id){
	if (editar){
		var value = document.FormAdmin.id.value;
		elemento.innerHTML = value;
		editar = false;	
	}
	
	if (!editar) {
		var obj = document.getElementById(id);
		elemento = obj;
		var content = obj.innerHTML;
		obj.innerHTML = "<input class='box' type='text' id='campo' name='id' value='"+content+"' />";
		document.FormAdmin.id.focus();
		editar = true;
	}
}

function DesEdit(){
	if (editar){
		var field = elemento.id;
		var campo = document.getElementById('campo');
		var conteudo = campo.value;
		elemento.innerHTML = conteudo;
	}
}

function ExibePainel(id, fase){

	var resultado = document.getElementById("resultado");
	resultado.style.display = "none";

	var painel = document.getElementById("painel");
	painel.style.display = "";

	ExibeGarota(id, fase)
}

function EscondePainel(){
	
	var resultado = document.getElementById("resultado");
	var painel = document.getElementById("painel");
	resultado.style.display = "";
	painel.style.display = "none";

}

var xmlHttp

function SalvaDados(){
	DesEdit();	
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null) {
		 alert ("Browser does not support HTTP Request") 
		return
	}

	id           = document.getElementById('id').innerHTML;
	rg           = document.getElementById('rg').innerHTML;
	cpf          = document.getElementById('cpf').innerHTML;
	datan        = document.getElementById('datan').innerHTML;
	ddd          = document.getElementById('ddd').innerHTML;
	telefone     = document.getElementById('telefone').innerHTML;
	rua          = document.getElementById('rua').innerHTML;
	numero       = document.getElementById('numero').innerHTML;
	complemento  = document.getElementById('complemento').innerHTML;
	cep          = document.getElementById('cep').innerHTML;
	cidade_natal = document.getElementById('cidade_natal').innerHTML;
	apelido      = document.getElementById('apelido').innerHTML;
	signo        = document.getElementById('signo').innerHTML;
	olhos        = document.getElementById('olhos').innerHTML;
	cabelos      = document.getElementById('cabelos').innerHTML;
	peso         = document.getElementById('peso').innerHTML;
	altura       = document.getElementById('altura').innerHTML;
	quadril      = document.getElementById('quadril').innerHTML;
	busto        = document.getElementById('busto').innerHTML;
	manequin     = document.getElementById('manequin').innerHTML;
	livro        = document.getElementById('livro').innerHTML;
	filme        = document.getElementById('filme').innerHTML;
	musica       = document.getElementById('musica').innerHTML;
	idolo        = document.getElementById('idolo').innerHTML;
	animal       = document.getElementById('animal').innerHTML;
	faz          = document.getElementById('faz').innerHTML;
	ama          = document.getElementById('ama').innerHTML;
	odeia        = document.getElementById('odeia').innerHTML;

	var url="salvadados.php?id="+id+"&rg=" + rg + "&cpf=" + cpf + "&datan=" + datan + "&ddd=" + ddd + "&telefone=" + telefone + "&rua=" + rua + "&numero=" + numero + "&complemento=" + complemento + "&cep=" + cep + "&cidade_natal=" + cidade_natal + "&apelido=" + apelido + "&signo=" + signo + "&olhos=" + olhos + "&cabelos=" + cabelos + "&peso=" + peso + "&altura=" + altura + "&quadril=" + quadril + "&busto=" + busto + "&manequin=" + manequin + "&livro=" + livro + "&filme=" + filme + "&musica=" + musica + "&idolo=" + idolo + "&animal=" + animal + "&faz=" + faz + "&ama=" + ama + "&odeia=" + odeia;  

	xmlHttp.onreadystatechange=stateChanged
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
}

function ExibeGarota(id, fase) {
        xmlHttp=GetXmlHttpObject()
        if (xmlHttp==null) {
                alert ("Browser does not support HTTP Request")
                return
        }

        var url="garota.php?id="+id+"&fase="+fase
        xmlHttp.onreadystatechange=stateChanged
        xmlHttp.open("GET",url,true)
        xmlHttp.send(null)
}

/*function GetXmlHttpObject() {
        var xmlHttp=null;
        try {
                // Firefox, Opera 8.0+, Safari
                xmlHttp=new XMLHttpRequest();
        } catch (e) {
                //Internet Explorer
                try {
                        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
        }
        return xmlHttp;
}*/

function stateChanged() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		document.getElementById("resposta").innerHTML=xmlHttp.responseText
	}
}

function ValidaForm(tipo){
	var msg = "";

	if (tipo == 1){
		var formulario = document.FormInscricao1;
	}

	if (tipo == 2){
		var formulario = document.FormInscricao2;
	}

	if (tipo == 3){
		var formulario = document.FormInscricao3;
	}

	if (formulario.nome.value == ""){
		msg+="Nome\n";
	}

	if (formulario.email.value == ""){
		msg+="Email\n";
	} else {
		var filter=/^[A-Za-z][A-Za-z0-9_]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
		if (!filter.test(formulario.email.value)){
			alert("Endereço de email não é valido.");
			return;
		}
	}

	if (formulario.rg.value == ""){
		msg+="RG\n";
	}

	if (formulario.cpf.value == ""){
		msg+="CPF\n";
	} else {
		var cpf = formulario.cpf.value;
		if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
			cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
			cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
			cpf == "88888888888" || cpf == "99999999999"){
			alert("O CPF informado não é válido.");
			return;
		}

	soma = 0;

	for(i = 0; i < 9; i++)
		soma += parseInt(cpf.charAt(i)) * (10 - i);
		resto = 11 - (soma % 11);
		if(resto == 10 || resto == 11)
			resto = 0;
		if(resto != parseInt(cpf.charAt(9))){
			alert("O CPF informado não é válido.");
			return false;
 		  }

		soma = 0;
		for(i = 0; i < 10; i ++)
			soma += parseInt(cpf.charAt(i)) * (11 - i);

		resto = 11 - (soma % 11);

		if(resto == 10 || resto == 11)
			resto = 0;
		if(resto != parseInt(cpf.charAt(10))){
			alert("O CPF informado não é válido.");
			return false;
		}

	}

	if (formulario.datan.value == ""){
		msg+="Data de Nascimento\n";
	} else {
		
		var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
		var msgErro = 'A data fornecida não é valida.';
		if (!(formulario.datan.value.match(expReg))) {
			alert(msgErro);
			return;
		}
	}

 	if(formulario.telefone.value == ""){
		msg+="Telefone\n";
	}

	if (formulario.ddd.value == ""){
		msg+="DDD\n";
	}

	if (formulario.endereco.value == ""){
		msg+="Rua\n";
	}

	if (formulario.numero.value == ""){
		msg+="Número\n";
	}
	
	if (formulario.cep.value == ""){
		msg+="CEP\n";
	} else {
	
		var objER = /^[0-9]{5}-[0-9]{3}$/;
		if(!objER.test(formulario.cep.value)){
			alert("O CEP fornecido não é valido.");
    	    return;
        }

	}

	if (formulario.cidade.value == ""){
		msg+="Cidade\n";
	}

	if (tipo > 1){
	
		if (formulario.cidade_natal.value == ""){
			msg+="Cidade onde Nasceu\n";
		}

		if (formulario.estado_natal.value == ""){
			msg+="Estado onde Nasceu\n";
		}
	
		if (formulario.apelido.value == ""){
			msg+="Apelido\n";
		}

		if (formulario.signo.value == ""){
			msg+="Signo\n";
		}

		if (formulario.olhos.value == ""){
			msg+="Cor dos Olhos\n";
		}

		if (formulario.cabelos.value == ""){
			msg+="Cor dos Cabelos\n";
		}

		if (formulario.peso.value == ""){
			msg+="Peso\n";
		}

		if (formulario.altura.value == ""){
			msg+="Altura\n";
		}
			
		if (formulario.quadril.value == ""){
			msg+="Quadril\n";
		}

		if (formulario.busto.value == ""){
			msg+="Busto\n";
		}

		if (formulario.manequim.value == ""){
			msg+="Manequim\n";
		}

		if (formulario.estado_civil.value == ""){
			msg+="Estado Civil\n";
		}

		if (formulario.livro.value == ""){
			msg+="Livro da sua Vida\n";
		}

		if (formulario.filme.value == ""){
			msg+="Filme que Marcou\n";
		}

		if (formulario.musica.value == ""){
			msg+="Música Inserquecível\n";
		}

		if (formulario.idolo.value == ""){
			msg+="Um Ídolo\n";
		}

		if (formulario.animal.value == ""){
			msg+="Animal de Estimação\n";
		}

		if (formulario.ocupacao.value == ""){
			msg+="O que faz?\n";
		}

		if (formulario.ama.value == ""){
			msg+="O que mais ama?\n";
		}

		if (formulario.odeia.value == ""){
			msg+="O que odeia?\n";
		}
	}

	if (tipo > 2){
		if (formulario.foto.value == ""){
			msg+="Retrato\n";
		}
		if (formulario.foto1.value == ""){
            alert("Atenção! Você deve inserir ao menos uma imagem para a galeria.");
            return
        }	
		if (formulario.reg.checked != true){
			alert("Você deve concordar com o regulamento para efetuar sua inscrição.");
			return			
		}
	}

	if (msg == ""){
		formulario.submit();
	} else {
		msg = "Atenção!\nOs seguintes campos devem ser preenchidos:\n" + msg + "Obrigado.";
		alert(msg);	
	}
}

function MaskData(objeto, evt) { return Mascara(objeto, evt, '##/##/####');}

function MaskCPF(objeto, evt) { return Mascara(objeto, evt, '###########');}

function MaskRG(objeto, evt) { return Mascara(objeto, evt, '#########');}

function MaskTelefone(objeto, evt) { return Mascara(objeto, evt, '########');}

function MaskDDD(objeto, evt) { return Mascara(objeto, evt, '##');}

function MaskNumero(objeto, evt) { return Mascara(objeto, evt, '########');}

function MaskCEP(objeto, evt) { return Mascara(objeto, evt, '#####-###');}

function Mascara(objeto, evt, mask) {
	try {
		var LetrasU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		var LetrasL = 'abcdefghijklmnopqrstuvwxyz';
		var Letras  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
		var Numeros = '0123456789';
		var Fixos  = '().-:/ ';
		var Charset = " !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_/`abcdefghijklmnopqrstuvwxyz{|}~";

		evt = (evt) ? evt : (window.event) ? window.event : "";
		var value = objeto.value;
		if (evt) {
			var ntecla = (evt.which ) ? evt.which : evt.keyCode;
			tecla = Charset.substr(ntecla - 32, 1);
			if (ntecla < 32) return true;
			if (ntecla == 46) return true;
			if (ntecla == 37) return true;
			if (ntecla == 39) return true;

			var tamanho = value.length ;
			if (tamanho >= mask.length) return false;

			var pos = mask.substr(tamanho,1);
			while (Fixos.indexOf(pos) != -1) {
				value += pos;
				tamanho = value.length;
				if (tamanho >= mask.length) return false;
				pos = mask.substr(tamanho,1);
			}

			switch (pos) {
				case '#' : if (Numeros.indexOf(tecla) == -1) return false; break;
				case 'A' : if (LetrasU.indexOf(tecla) == -1) return false; break;
				case 'a' : if (LetrasL.indexOf(tecla) == -1) return false; break;
				case 'Z' : if (Letras.indexOf(tecla) == -1) return false; break;
				case '*' : objeto.value = value; return true; break;
				default : return false; break;
			}
		}
		objeto.value = value;
	}catch(e) { }
	return true;
}


function MudaImagem(img, folder){
	foto = img;
	pasta = folder;
	
	var painel = document.getElementById("segurafoto");
	painel.innerHTML = "<img src='thumbs/perfil_grande/"+folder+"/"+img+".jpg' alt='' title='' /><a href='javascript:void(FotoAnterior())' id='fotoanterior'><</a><a href='javascript:void(FotoProxima())' id='fotoproxima'>></a>";

	if (img == total){
		document.getElementById("fotoproxima").style.display = "none";
	}

	if (img == 2){
		document.getElementById("fotoanterior").style.display = "none";
	}
}

function FotoAnterior(){
	foto--;
	MudaImagem(foto, pasta);	
}

function FotoProxima(){
	foto++;
	MudaImagem(foto, pasta);
}

function BuscaGarota(){
	if (document.formGarota.nome.value == "Digite o nome da garota"){
		document.formGarota.nome.value = "";
	}
}

function PerdaFoco(){
	if (document.formGarota.nome.value == ""){
		document.formGarota.nome.value = "Digite o nome da garota";
	}
}

function changeColor(obj){
	obj.style.background = "#F5F5DC";	
}

function backColor(obj){
	obj.style.background = "#FFFFFF";
}

function ExcluirGarota(id, pg_ref){
	var r=confirm("Deseja Excluir este Perfil?");
	if (r==true) {
        
		xmlHttp=GetXmlHttpObject()
        if (xmlHttp==null) {
                alert ("Browser does not support HTTP Request")
                return
        }

        var url="excluir.php?id="+id+"&pg_ref="+pg_ref
        xmlHttp.onreadystatechange=stateChangedExclui
        xmlHttp.open("GET",url,true)
        xmlHttp.send(null)
	}
}
function AprovarGarota(id){
    var r=confirm("Deseja Aprovar este Perfil?");
    if (r==true) {

        xmlHttp=GetXmlHttpObject()
        if (xmlHttp==null) {
                alert ("Browser does not support HTTP Request")
                return
        }

        var url="aprovar.php?id="+id
        xmlHttp.onreadystatechange=stateChangedAprova
        xmlHttp.open("GET",url,true)
        xmlHttp.send(null)
    }
}
function GetXmlHttpObject() {
        var xmlHttp=null;
        try {
                // Firefox, Opera 8.0+, Safari
                xmlHttp=new XMLHttpRequest();
        } catch (e) {
                //Internet Explorer
                try {
                        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
        }
        return xmlHttp;
}

function stateChangedExclui() {
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
        //document.getElementById("resposta").innerHTML=xmlHttp.responseText
		alert("Perfil Excluído com Sussesso.");
		window.location.reload()
    }
}
function stateChangedAprova() {
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
        //document.getElementById("resposta").innerHTML=xmlHttp.responseText
		alert("Perfil Aprovado com Sussesso.");
		window.location.reload()
    }
}

function AdicionaSegundaFase(id){

	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null) {
		alert ("Browser does not support HTTP Request")
		return
	}

	var url="segunda.php?id="+id
	xmlHttp.onreadystatechange=stateChangedSegFase
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
}

function stateChangedSegFase() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		alert("Garota foi adicionada para a segunda fase do concurso.");
	}
}

function ExcluirSegundaFase(id){

    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null) {
        alert ("Browser does not support HTTP Request")
        return
    }

    var url="removesegunda.php?id="+id
    xmlHttp.onreadystatechange=stateChangedRemSegFase
    xmlHttp.open("GET",url,true)
    xmlHttp.send(null)

}

function stateChangedRemSegFase() {
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
        alert("Garota foi removida da segunda fase do concurso.");
		window.location.reload()
    }
}


function ExcluirImagem(folder, img){

    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null) {
        alert ("Browser does not support HTTP Request")
        return
    }

    var url="removeimagem.php?id="+img+"&folder="+folder
    xmlHttp.onreadystatechange=stateChangedRemImagem
    xmlHttp.open("GET",url,true)
    xmlHttp.send(null)


}

function stateChangedRemImagem() {
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		document.getElementById("ExibeFotos").innerHTML = xmlHttp.responseText;
    }
}
function abre_votacao(item){
//  window.open('confirma.phtml?item='+item, 'Voto Finalistas', 'height=550, width=250');
	sl_pag('confirma.phtml?item='+item,'', 0, '', '550', '250' );
}

function fecha_votacao(){
//  window.close();
	sl_fech(0);
}
function sl_pag (pag, leg, id, nivel, h, w)
{
	if (id == 0)
	{
		divona = 'fotona';
	}
	else
	{
		divona = 'fotona_'+id;
	}

	if (parseInt(navigator.appVersion)>3) {
		if (navigator.appName=="Netscape") {
			winH = window.innerHeight-16;
		}
		if (navigator.appName.indexOf("Microsoft")!=-1) {
			//winH = document.body.offsetHeight-20;
			winH = document.documentElement.clientHeight-20;
		}
	}
	var divs = document.getElementsByTagName('object');
		for(var i=0,len=divs.length;i<len;i++) {
			divs[i].style.visibility = "hidden";
		}

	valor = (winH-h)/2;

	var yScroll;
	if (self.pageYOffset) yScroll = self.pageYOffset;
	else if (document.documentElement && document.documentElement.scrollTop) yScroll = document.documentElement.scrollTop;
	else if (document.body) yScroll = document.body.scrollTop;

	yScroll += valor;

	document.getElementById(divona).style.top = yScroll + 'px';
	document.getElementById(divona).style.width = w + 'px';

	document.getElementById('divsombra').style.display = "inline";

//    document.getElementById(divona).innerHTML = '<a href="javascript: sl_fech ('+id+')" class="slfech">Fechar</a><a href="javascript: sl_fech ('+id+')"><iframe src="' + pag + '" alt="' + leg + '" title="' + leg + '" frameborder="0" width="'+ (w+20) +'" height="'+ (h) +'" /><p>' + leg + '</p>';
	document.getElementById(divona).innerHTML = '<a href="javascript: sl_fech ('+id+')"><iframe src="' + pag + '" alt="' + leg + '" title="' + leg + '" frameborder="0" width="'+ w +'" height="'+ h +'" SCROLLING="NO" /><p>' + leg + '</p>';
	document.getElementById(divona).style.display = "inline";
}
function sl_fech (id)
{
	if (id == 0)
	{
		divona = 'fotona';
	}
	else
	{
		divona = 'fotona_'+id;
	}

	document.getElementById("divsombra").style.display = "none";
	document.getElementById(divona).style.display = "none";

	var divs = document.getElementsByTagName('object');
		for(var i=0,len=divs.length;i<len;i++) {
			divs[i].style.visibility = "visible";
		}
}

