var grupo, sorteio;

function Participante(nome, email, organizador, confirma, string) {
  this.nome = nome;
  this.email = email;
  this.organizador = organizador || "false";
  this.confirma = confirma || "false";
  this.string = string || "";
}

function adicionar(N,E) {
  f = document.amigo;
  N = trim(N.replace(/\;+/g, " "));
  E = trim(E.toLowerCase());
  selPart = document.getElementById("part");  
  S = selPart.options.length;
  org = false;  

//confirmação para emails do Yahoo    
//  if(E.indexOf("@yahoo.com") != -1) {
//    if(!confirm("Devido às políticas antispam do Yahoo avisamos que podem ocorrer atrasos na entrega das mensagens para esse e-mail. Recomendamos que utilize outro endereço.\nSe deseja adicionar mesmo assim clique em OK.")) return;
//  }
  
  if(E == "amigo_oculto@acessa.com") {
    alert("Ops! Você deve adicionar esse email na \"lista branca\" do seu filtro ANTISPAM e não no sorteio!");
    return;
  }  

  if (N != "" && validaEmail(E)) {
    if(S == 0) {
      if (confirm("O primeiro participante será o ORGANIZADOR do sorteio. Deseja continuar?")) {
        org = true;  
      } else {
        return;
      }
    }
    part = new Participante(N,E,org);
    
    if(!existeParticipante(N,E)) part = (org) ? new Option(part.nome + " | "+part.email + " (Organizador)", part.nome+";"+part.email+";"+part.organizador+";"+part.confirma+";"+part.string) : new Option(part.nome + " | "+part.email, part.nome+";"+part.email+";"+part.organizador+";"+part.confirma+";"+part.string) ;
    else return;
    
    part.className = "nao_conf";      
    selPart.options[S] = part;
    f.participante.value = "";
    f.email_participante.value = "";
    f.participante.focus();
    liberaSalva();
  } else {
    alert("Preencha os campos corretamente!");
  }
}


function removerParticipante() {
  selPart = document.getElementById("part");
  if(selPart.options.selectedIndex == -1) {
    alert("Selecione um participante");
    return;
  }
  part = opt2Part(selPart.options.selectedIndex);
  
  if(grupo && part.organizador == "true") {
    alert("Você não pode excluir o ORGANIZADOR do sorteio!!");
    return;
  }  
  if (confirm("Deseja excluir o participante "+part.nome.toUpperCase()+"?")) {
    if(part.confirma == "true") if(!confirm("Esse participante já confirmou participação.\nDeseja excluir mesmo assim?")) return;  
    selPart.options[selPart.selectedIndex] = null;
    liberaSalva();
  }
}

function editarParticipante() {
  selPart = document.getElementById("part");
  ind = selPart.options.selectedIndex;
  if(ind == -1) {
    alert("Selecione um participante");
    return;
  }
  
  if(sorteio == true && !confirm("O sorteio já foi realizado. NÃO É RECOMENDADO fazer alterações agora.\nSe mesmo assim você quiser prosseguir, clique em OK.")) { 
    return false;
  }
  
  part = opt2Part(ind);
  nome_aux = part.nome;
  
  if (confirm("Deseja editar o participante "+nome_aux.toUpperCase()+"?")) {
    if(part.confirma == "true" && !confirm("Esse participante já confirmou participação.\nDeseja editar mesmo assim?")) return;
    if(sorteio != true) {      
      novo_nome = prompt("Informe o novo nome ou clique em CANCELAR para não alterar:", nome_aux);    
      if(novo_nome != null && trim(novo_nome) != "" && !existeNome(novo_nome)) {
        opt = new Option(novo_nome+" | "+part.email+(part.organizador == "true" ? " (Organizador)" : ""), novo_nome+";"+part.email+";"+part.organizador+";"+part.confirma+";"+part.string);
        opt.className = (part.confirma == "true") ? "conf" : "nao_conf";
        selPart.options[ind] = opt;
        nome_aux = novo_nome;
        liberaSalva();
      }
    }    
    
    novo_email = prompt("Informe o novo email ou clique em CANCELAR para não alterar:", part.email);
    if(novo_email != null && trim(novo_email) != "amigo_oculto@acessa.com" && !existeEmail(novo_email) && validaEmail(novo_email)) {
      part.confirma = (sorteio == true) ? "true" : "false";       
      opt = new Option(nome_aux+" | "+novo_email+(part.organizador == "true" ? " (Organizador)" : ""), nome_aux+";"+novo_email+";"+part.organizador+";"+part.confirma+";"+part.string);
      opt.className = (part.confirma == "true") ? "conf" : "nao_conf";
      selPart.options[ind] = opt;
      liberaSalva();
    }   
  } 
}

function alterarOrganizador() {
  selPart = document.getElementById("part");
  ind = selPart.options.selectedIndex;
  if(ind == -1) {
    alert("Selecione um participante");
    return;
  }
  for(i=0; i<selPart.options.length;i++) {
    part = opt2Part(i);
    if(i == ind) {
      selPart.options[i].text = part.nome+" | "+part.email+" (Organizador)";
      selPart.options[i].value = part.nome+";"+part.email+";true"+";"+part.confirma+";"+part.string;
    } else {
      selPart.options[i].text = part.nome+" | "+part.email;
      selPart.options[i].value = part.nome+";"+part.email+";false"+";"+part.confirma+";"+part.string;
    }
  }
}

function convidarParticipante(f) {
  if(!document.getElementById("save").disabled) {
    alert("Você fez alterações e deve salvá-las antes de continuar.")
    return;
  }   
  selPart = document.getElementById("part");
  ind = selPart.options.selectedIndex;
  if(ind == -1) {
    alert("Selecione um participante");
    return;
  }
  part = opt2Part(ind);
  if(part.confirma == "true") {
    alert("Esse participante já confirmou participação.");
    return;
  }
  f.acao.value="convidar";
  f.submit();
}

function reenviarSorteio(f) {
  if(!document.getElementById("save").disabled) {
    alert("Você fez alterações e deve salvá-las antes de continuar.")
    return;
  }   
  selPart = document.getElementById("part");
  ind = selPart.options.selectedIndex;
  if(ind == -1) {
    alert("Selecione um participante");
    return;
  }
  f.acao.value="reenviar";
  f.submit();
}

function atualizar(f) {
  if(!document.getElementById("save").disabled) {
    if(!confirm("Você fez alterações. Deseja continuar sem salvá-las?")) return;
  }     
  f.acao.value="atualizar";
  f.submit();
}

function criarGrupo(f) {
  selPart = document.getElementById("part");
  bt_envia = document.getElementById("send"); 
  bt_envia.disabled=true;
  S = selPart.options.length;
  selecionaTodos();
  
  if (f.nome_sorteio.value=="") {
    alert("Você deve informar o nome do amigo oculto!");
    bt_envia.disabled=false;
    return;
  } else if (S == 0) {
    alert("Você deve adicionar os participantes!");
    bt_envia.disabled=false;
    return;
  } else if (S < 3) {
    alert("Você deve adicionar mais participantes!");
    bt_envia.disabled=false;
    return;
  } else if(!existeOrganizador()) {
    alert("O sorteio deve ter um organizador!\nSelecione um e clique em ALTERAR ORGANIZADOR");
    bt_envia.disabled=false;
    return;
  } else {
    f.submit();    
  }
}

function salvarAlteracoes(f) {
  bt_envia = document.getElementById("save");
  bt_envia.disabled=true;
  if(!existeOrganizador()) {
    alert("O sorteio deve ter um organizador!");
    bt_envia.disabled=false;
    return;
  }
  selecionaTodos();
  f.acao.value="salvar";  
  f.submit();    
}

function sortear(f) {
  bt_envia = document.getElementById("send");
  selPart = document.getElementById("part");
  bt_envia.disabled=true;
  if(selPart.options.length < 2) {
    alert("Você deve convidar mais participantes");
    return;
  }
  if(!document.getElementById("save").disabled) {
    alert("Você fez alterações e deve salvá-las antes de continuar.")
    return;
  }  
  if(!verificaConfirmados()) {
    alert("Você só pode sortear após TODOS os participantes aceitarem o convite.\nSe deseja sortear mesmo assim, remova os que não confirmaram.");
    bt_envia.disabled=false;
    return;
  }   
  if(confirm("Confira TODOS OS PARTICIPANTES antes de sortear.\nClique OK para continuar ou CANCELAR.")) {
    selecionaTodos();
    f.acao.value="sortear";
    f.submit();      
  }
  bt_envia.disabled=false;
}

function sair() {                                      
  document.location="/amigooculto/";
}

function existeParticipante(N,E) {
  if(!existeNome(N) && !existeEmail(E)) return false;
  return true;
}

function existeNome(N) {
  selPart = document.getElementById("part");
  for(i=0; i<selPart.options.length; i++) {
    aux = selPart.options[i].value.split(";");
    if(N == aux[0]) {
      alert("Nome já cadastrado!");
      return true;
    }
  }
  return false;
}

function existeEmail(E) {
  selPart = document.getElementById("part");
  for(i=0; i<selPart.options.length; i++) {
    aux = selPart.options[i].value.split(";");
    if(E == aux[1]) {
      alert("E-mail já cadastrado!");
      return true;
    }
  }
  return false;
}

function existeOrganizador() {
  selPart = document.getElementById("part");
  for(i=0; i<selPart.options.length; i++) {
    aux = selPart.options[i].value.split(";");
    if(aux[2] == "true") {
      return true;
      break
    }
  }
  return false;
}

function liberaSalva() {
  if(grupo) document.getElementById("save").disabled=false;
}

function selecionaTodos() {
  selPart = document.getElementById("part");
  for(i=0; i<selPart.options.length; i++) {
    selPart.options[i].selected = true;
  }
}

function opt2Part(id) {
  selPart = document.getElementById("part");
  aux = selPart.options[id].value.split(";");
  return new Participante(aux[0],aux[1],aux[2],aux[3],aux[4]);
}

function verificaConfirmados() {
  selPart = document.getElementById("part");
  for(i=0; i<selPart.options.length; i++) {
    aux = selPart.options[i].value.split(";");
    if(aux[3] == "false") {
      return false;
      break
    }
  }
  return true;
}

function confirmaAlteracao() {
  if(!document.getElementById("save").disabled) {
    if(confirm("Você fez alterações. Deseja continuar sem salvá-las?")) return true;
    else return false;
  }   
}