Tesla.Events.AddOnLoad( InicializaCadastro );
Tesla.Events.AddOnLoad( divBotoes );

var Pagina = {};
var busca=0;
var profile = {};

var counter = 1;
var newPath = '';
var filePath = '';
var DadosLogin = {};

function divBotoes()
{
    document.getElementById('divBotoes').style.display='';
}

var ids = [];
Tesla.CadastroNewsletterInfo = null;
function EndRetornaNewsletterInfo(result)
{
    Tesla.CadastroNewsletterInfo = result;
    var campo = null;
    var idCidade = 1;
    var cmbCidades = document.getElementsByName('cd_city')[0];
    for (var i=0; i<cmbCidades.options.length; i++)
        if (cmbCidades.options[i].selected) idCidade = cmbCidades.options[i].value;
    var frm		= document.createElement('form');
    frm.action	= 'http://md.zartana.com/dmm/form_integracao/188Q8888888w';
    frm.method	= 'post';
    frm.name	= 'fr1';
    frm.target	= '_self';
    document.body.appendChild(frm);
    var chks = document.getElementsByName('chkCanais');

    for(var i=0; i<chks.length; i++)
    {
        if (!chks[i].checked) continue;
        
        campo = document.createElement('input');
        campo.name = 'z_listas';
        campo.value = Tesla.CadastroNewsletterInfo[parseInt(chks[i].value)].IDs[idCidade];
        campo.setAttribute('type', 'hidden');
        frm.appendChild(campo);
    }

    campo = document.createElement('input');
    campo.name = 'z_dado_email';
    campo.value = Pagina.txtEmail.value;
    campo.setAttribute('type', 'hidden');
    frm.appendChild( campo );
    
    campo = document.createElement('input');
    campo.name = 'acao';
    campo.value = 'cadastrar';
    campo.setAttribute('type', 'hidden');
    frm.appendChild(campo);
                                           
    campo = document.createElement('input');
    campo.name = 'z_sucesso';
    campo.value = 'http://www.guiadasemana.com.br';
    campo.setAttribute('type', 'hidden');
    frm.appendChild( campo );
                                
    campo = document.createElement('input');
    campo.name = 'z_erro';
    campo.value = 'http://www.guiadasemana.com.br';
    campo.setAttribute('type', 'hidden');
    frm.appendChild( campo );
	        	
    frm.submit();
}
function CadastraNewsLetter2()
{
    fnRetornaNewsletterInfo(EndRetornaNewsletterInfo);
}

function InicializaCadastro()
{
    meuWizard.OnStepChange = MudaPasso;
    meuWizard.OnFinish = FinalizaCadastro;
    
    Pagina.News = document.getElementById('chkNews');
    Pagina.txtNome = document.getElementById('txtNome');
    Pagina.txtSobreNome = document.getElementById('txtSobreNome');
    Pagina.txtEndereco = document.getElementById('txtEndereco');
    Pagina.txtEmail = document.getElementById('txtEmail');
    Pagina.txtCidade = document.getElementById('txtCidade');
    Pagina.txtNascimento = document.getElementById('txtNascimento');
    if(window.EdicaoUsuario)
    {
        document.getElementById('txtSenha').value = 'xxxx';
        document.getElementById('txtConfirmacao').value = 'xxxx';
    }
    Pagina.txtSenha = document.getElementById('txtSenha');
    Pagina.txtSenhaHidden = document.getElementById('txtSenhaHidden');
    Pagina.txtConfirmacao = document.getElementById('txtConfirmacao');
    
    Pagina.txtCPF = document.getElementById('txtCPF');
    Pagina.Sexo = document.getElementById('dropSexo');
    Pagina.Cep = document.getElementById('txtCep');
    Pagina.txtBairro = document.getElementById('txtBairro');
    Pagina.txtApelido = document.getElementById('txtApelido');
    Pagina.divUploadFoto = document.getElementById('divUploadFoto');
   

    Pagina.txt_qst_01 = document.getElementById('txt_qst_1');
    Pagina.txt_qst_02 = document.getElementById('txt_qst_2');
    Pagina.txt_qst_03 = document.getElementById('txt_qst_3');
    Pagina.txt_qst_04 = document.getElementById('txt_qst_4');
    Pagina.txt_qst_05 = document.getElementById('txt_qst_5');
    Pagina.txt_qst_06 = document.getElementById('txt_qst_6');
    Pagina.txt_qst_07 = document.getElementById('txt_qst_7');
    Pagina.txt_qst_08 = document.getElementById('txt_qst_8');
    Pagina.txt_qst_09 = document.getElementById('txt_qst_9');
    Pagina.txt_qst_10 = document.getElementById('txt_qst_10');
    Pagina.txt_qst_11 = document.getElementById('txt_qst_11');
    Pagina.txt_qst_12 = document.getElementById('txt_qst_12');
    Pagina.txt_qst_13 = document.getElementById('txt_qst_13');

    Pagina.dropCidades = document.getElementById('dropCidades');
    Pagina.dropCidades.onchange = function(){ AtualizaCinemas(this.value); AtualizaCanais(this.value); }
    //Pagina.dropCanal1 = document.getElementById('dropCanal1');
    //Pagina.dropCanal2 = document.getElementById('dropCanal2');
    //Pagina.dropAssunto1 = document.getElementById('dropAssunto1');
    //Pagina.dropAssunto2 = document.getElementById('dropAssunto2');
    Pagina.Noticia = document.getElementById('cd_news_1');
    //Pagina.RSS1 = document.getElementById('st_rss_1');
    //Pagina.RSS2 = document.getElementById('st_rss_2');
    Pagina.Cinema = document.getElementById('dropCinema');
    Pagina.Image = document.getElementById('fileImagem');


    Pagina.dropCidade = document.getElementById('cd_city');
    Pagina.txtBusca = document.getElementById('txtBusca');

    Pagina.Face1 = document.getElementById('rdFace1');
    Pagina.Face2 = document.getElementById('rdFace2');
    Pagina.Face3 = document.getElementById('rdFace3');
    Pagina.Face4 = document.getElementById('rdFace4');
    Pagina.Face5 = document.getElementById('rdFace5');
    Pagina.Face6 = document.getElementById('rdFace6');
    Pagina.Face7 = document.getElementById('rdFace7');
    
    Pagina.Face1.onclick = function(e){if (this.checked) { SelecionaImagemDefault('../../../images/ico_1.gif'); } };
    Pagina.Face2.onclick = function(e){if (this.checked) { SelecionaImagemDefault('../../../images/ico_2.gif'); } };
    Pagina.Face3.onclick = function(e){if (this.checked) { SelecionaImagemDefault('../../../images/ico_3.gif'); } };
    Pagina.Face4.onclick = function(e){if (this.checked) { SelecionaImagemDefault('../../../images/ico_4.gif'); } };
    Pagina.Face5.onclick = function(e){if (this.checked) { SelecionaImagemDefault('../../../images/ico_5.gif'); } };
    Pagina.Face6.onclick = function(e){if (this.checked) { SelecionaImagemDefault('../../../images/ico_6.gif'); } };
    Pagina.Face7.onclick = function(e){if (this.checked) { AtualizaImagemExibicao(); } };


    var fileUpload = document.getElementById("fileUpload");
    fileUpload.style.display = '';
    document.getElementById("phFileUpload").appendChild( fileUpload );
    ListControlFunctions.BindFunctions(Pagina.Cinema);
    ListControlFunctions.BindFunctions(Pagina.Noticia);
}
function AtualizaCinemas(idCidade)
{
    Pagina.Cinema.options.length = 0;
    var listacinemas = fnListaCinemas(idCidade);
    if (listacinemas)
        Pagina.Cinema.Bind(listacinemas, 'CD_PLACE', 'ST_NAME_PLACE');
}
function AtualizaCanais(idCidade)
{
    Pagina.Noticia.options.length = 0;
    var listaCanais = fnListaCanais(idCidade);
    if (listaCanais)
        Pagina.Noticia.Bind(listaCanais, 'CD_CHANNEL', 'ST_NAME_CHANNEL');
}
function RetornaUsuario()
{
    var usuario = {};

    usuario.Nome = Pagina.txtNome.value;
    usuario.Apelido = Pagina.txtApelido.value;
    usuario.Sobrenome = Pagina.txtSobreNome.value;
    usuario.Email = Pagina.txtEmail.value;
    usuario.Newsletter = Pagina.News.checked ? 1 : 0;
    usuario.Endereco = Pagina.txtEndereco.value;
    usuario.EnderecoCEP = Pagina.Cep.value;
    usuario.EnderecoCidade = Pagina.txtCidade.value;
    usuario.EnderecoBairro = Pagina.txtBairro.value;
    usuario.DataNascimento = Pagina.txtNascimento.value;
    usuario.Telefone = null;
    usuario.Celular = null;
    usuario.Senha = Pagina.txtSenha.value;
    usuario.AlterouSenha = (Pagina.txtSenhaHidden.value == 1);
    usuario.CPF = Pagina.txtCPF.value;
    usuario.Sexo = Pagina.Sexo.value;
    usuario.usuarioInternet = null;
    usuario.cdVia = null;
    usuario.EnderecoCep = Pagina.Cep.value;
    usuario.TopicosDeInteresse = null;
    usuario.Filhos = null;
    usuario.NivelEducacional = null;
    usuario.CampoDeTrabalho = null;
    usuario.Rendimentos = null;
    usuario.TipoUsuario = null;
    usuario.FrequenciaDeCompra = null
    usuario.CartaoCredito = null;
    usuario.Banco = null;
    usuario.Parceiro = null;
    usuario.Socio = null;
    usuario.Funcao = null;
    usuario.Karma = null;
    usuario.Foto=null;

    return usuario;
}

function RetornaPerfil()
{
    var perfil = {};

    perfil.Questao1 = Pagina.txt_qst_01.value;
    perfil.Questao2 = Pagina.txt_qst_02.value;
    perfil.Questao3 = Pagina.txt_qst_03.value
    perfil.Questao4 = Pagina.txt_qst_04.value
    perfil.Questao5 = Pagina.txt_qst_05.value;
    perfil.Questao6 = Pagina.txt_qst_06.value
    perfil.Questao7 = Pagina.txt_qst_07.value
    perfil.Questao8 = Pagina.txt_qst_08.value;
    perfil.Questao9 = Pagina.txt_qst_09.value;
    perfil.Questao10 = Pagina.txt_qst_10.value;
    perfil.Questao11 = Pagina.txt_qst_11.value;
    perfil.Questao12 = Pagina.txt_qst_12.value;
    perfil.Questao13 = Pagina.txt_qst_13.value;

    return perfil;
}


function RetornaPreferencia()
{
    //var profile = {};
    profile.IDCidade = Pagina.dropCidades.value;
    //profile.Canal1 = Pagina.dropCanal1.value;
    //profile.Canal2 = Pagina.dropCanal2.value;
    //profile.Assunto1 = Pagina.dropAssunto1.value;
    //profile.Assunto2 = Pagina.dropAssunto2.value;
    profile.IDNews = Pagina.Noticia.value;
    //profile.RSS1 = Pagina.RSS1.value;
    //profile.RSS2 = Pagina.RSS2.value;
    profile.IDTip = null
    profile.Secoes = 1;
    profile.IDClient = null;
    profile.IDPerfil = null;
    profile.IDEnquete = Pagina.Noticia;
    profile.IDCinema = Pagina.Cinema.value;

    return profile;
}

function RetornaGeneros()
{
    var generos = {};

    generos.Itens = PercorreCombo('listGeneroMusica');
    //generos.Itens += PercorreCombo('listGeneroPublico');
    //generos.Itens += PercorreCombo('listGeneroGastronomia');
    //generos.Itens += PercorreCombo('listGeneroPerfil');
    //generos.Itens += PercorreCombo('listGeneroFilme');
    generos.Itens += PercorreCombo('listGeneroArte');

    return generos;
}

function MudaPasso( idxPasso, nomePasso )
{
    if (idxPasso == 1 )
    {
        if(!ValidaPasso1()) return false;
        InserirUsuario();
        InserirPreferencia();
    }

    if (idxPasso == 2) 
    {
       InserirPerfil();
    }

    if (idxPasso == 3)
    {
        AlterarPreferencia();
        document.getElementById('btnConfirmarPasso').style.display = 'none';
//      Será necessário passar pelo último passo do wizard quando o usuario estiver alterando o cadastro.
//      então, só finaliza o wizard na function FinalizaCadastro()
//      if (window.EdicaoUsuario)
//      {
//          FuncionalidadesRestritas.IrParaMeuGuia.CallBackFunction(true,null);
//          return false;
//      }
     }

    for(var i=1; i<=4; i++)
        document.getElementById("tdPasso"+i).bgColor = ((nomePasso!=("Passo"+i)) ? "#c0c0c0" : "green");

    return true;
}
function FinalizaCadastro()
{
    CadastraNewsLetter2();
    
//    if (DadosLogin.Email)
//    {
//        fnEfetuaLogin(DadosLogin.Email, DadosLogin.Senha);
//        FuncionalidadesRestritas.IrParaMeuGuia.CallBackFunction(true,null);
//    }
}

function ValidaPasso1()
{
    profile.NMImage =  obtemImagemUsuario();

    var camposNaoPreenchidos = '';
    var listaCamposObrigatorios = 'Apelido<br>Nome<br>SobreNome<br>Email<br>Cidade<br>Data de Aniversario<br>Senha<br>Confirmacao de Senha.';

    if( String.IsNullOrEmpty( Pagina.txtNome.value ) )
        camposNaoPreenchidos += 'Nome<br>';

    if(String.IsNullOrEmpty( Pagina.txtApelido.value ) )
        camposNaoPreenchidos += 'Apelido<br>';

    if(String.IsNullOrEmpty( Pagina.txtSobreNome.value ) )
        camposNaoPreenchidos += 'SobreNome<br>';

    if (String.IsNullOrEmpty( Pagina.txtEmail.value ) )
        camposNaoPreenchidos += 'Email<br>';

    if (String.IsNullOrEmpty( Pagina.txtCidade.value ) )
        camposNaoPreenchidos += 'Cidade<br>';

    if (String.IsNullOrEmpty( Pagina.txtNascimento.value ) )
        camposNaoPreenchidos += 'Data de nascimento<br>';

    if (String.IsNullOrEmpty( Pagina.txtSenha.value ) || String.IsNullOrEmpty( Pagina.txtConfirmacao.value ))
        camposNaoPreenchidos += 'Senha<br>';

    if (camposNaoPreenchidos != '')
    {
        ExibeMensagem('<b>Os seguintes campos não preenchidos são obrigatórios:.</b>', camposNaoPreenchidos);
        return false;
    }

    if(Pagina.txtSenha.value != Pagina.txtConfirmacao.value )
    {
        ExibeMensagem('<b>Erro!</b>', 'Os campos Senha e Confirmacao da senha devem ser iguais.');
        return false;
    }

    if(!validaData(Pagina.txtNascimento.value))
    {
        ExibeMensagem('<b>Erro</b>', 'Data Invalida!');
        return false;
    }
    
    if ( !window.EdicaoUsuario && !fnValidaEmail(Pagina.txtEmail.value))
    {
        ExibeMensagem('<b>Erro</b>', 'Email já utilizado!');
        return false;
    }

    return true;
}

function InsereUsuario()
{
    ExibeMensagem('<b>Gravando informacoes</b>', 'Por favor aguarde...', true, '../../../images/carrega_busca.gif');
    var usr = RetornaUsuario();
    fnInsereUsuarios( usr, RetornaPerfil(), RetornaPreferencia(), RetornaGeneros(), InsereUsuarioEnd )
}

function InserirUsuario()
{
    var image='';
    image = obtemImagemUsuario();

    ExibeMensagem('<b>Gravando informacoes</b>', 'Por favor aguarde...', true, '../../../images/carrega_busca.gif');
    var usr = RetornaUsuario();
    DadosLogin.Email = usr.Email;
    DadosLogin.Senha = usr.Senha;
    fnInsereUsuario(RetornaUsuario(),image,InsereUsuarioEnd);
}

function InserirPerfil()
{
    ExibeMensagem('<b>Gravando informacoes</b>', 'Por favor aguarde...', true, '../../../images/carrega_busca.gif');
    fnInserePerfil(RetornaPerfil(),InsereCadastroEnd);
}

function InserirPreferencia() 
{
    //ExibeMensagem('<b>Gravando informacoes</b>', 'Por favor aguarde...', true, '../../../images/carrega_busca.gif');
    fnInserePreferencia(RetornaPreferencia(),null,InsereCadastroEnd);
}
function AlterarPreferencia() 
{
    ExibeMensagem('<b>Gravando informacoes</b>', 'Por favor aguarde...', true, '../../../images/carrega_busca.gif');
    fnInserePreferencia(RetornaPreferencia(),RetornaGeneros(),InsereCadastroEnd);
}

function InsereCadastroEnd(msg)
{
    if(!String.IsNullOrEmpty( msg ) ) ExibeMensagem('<b>Ocorreu um erro inesperado.</b>', msg);
    else EscondeMensagem();
}

function upload(caminho,tamanho) 
{
    ExibeMensagem('<b>Aguarde.Transferindo imagem...</b>', 'Por favor aguarde...', true, '../../../images/carrega_busca.gif');
    fnstartUpload(caminho,tamanho,InsereCadastroEnd);
}

function InsereUsuarioEnd( msg )
{
    if( !String.IsNullOrEmpty( msg ) ) ExibeMensagem('<b>Ocorreu um erro inesperado.</b>', msg);
    else ExibeMensagem('<b>Cadastro efetuado com sucesso.</b>', msg);
}

function recuperaEstabelecimento()
{
    profile.IDPlace1 = document.getElementById('cd_place_1').value;
    profile.IDPlace2 = document.getElementById('cd_place_2').value;
    profile.IDPlace3 = document.getElementById('cd_place_3').value;
}

function pecorrerCombo()
{
    var combo = {}
    combo = document.getElementById('listGeneroMusica');
    var i;
    //document.getElementById('SEL_st_rss_1').options[document.getElementById('SEL_st_rss_1').selectedIndex].value;

}

function BuscaEstabelecimento()
{
    busca = 1;
    ExibeMensagem('<b>Efetuando pesquisa..</b>', 'Por favor aguarde...', true, '../../../images/carrega_busca.gif');
    fnBuscaEstabelecimento(Pagina.dropCidade.value,Pagina.txtBusca.value,BuscaEstabelecimentoEnd);
}

function BuscaEstabelecimentoEnd(result)
{
    EscondeMensagem();
    rptEstabelecimento.Bind( result );

    Pagina.Pos = document.getElementById('POS');
    Pagina.Place1 =  document.getElementById('st_place_1');
    Pagina.Place2 = document.getElementById('st_place_2');
    Pagina.Place3 = document.getElementById('st_place_3');
    Pagina.CDPlace1 = document.getElementById('cd_place_1');
    Pagina.CDPlace2 = document.getElementById('cd_place_2');
    Pagina.CDPlace3 = document.getElementById('cd_place_3');
}

function PercorreCombo(combo)
{
    var itens='';
    var sel = document.getElementById(combo);

    for (i = 0; i < sel.options.length; i++)
        if (sel.options[i].selected) itens += sel.options[i].value + ',';

    return itens;
}

function obtemImagemUsuario()
{
    var nomeImage='';

    if(Pagina.Face1.checked)
        nomeImage = 'ico_1.gif';

    if(Pagina.Face2.checked)
        nomeImage = 'ico_2.gif';

    if(Pagina.Face3.checked)
        nomeImage = 'ico_3.gif';

    if(Pagina.Face4.checked)
        nomeImage = 'ico_4.gif';

    if(Pagina.Face5.checked)
      nomeImage = 'ico_5.gif';

    if(Pagina.Face6.checked)
        nomeImage = 'ico_6.gif';

    return nomeImage;
}

function validaData(strData)
{
    var dia,mes,ano;
    var arrData = strData.split("/");

    var dia = arrData[0];
    var mes = arrData[1];
    var ano = arrData[2];

    if (isNaN(dia) || isNaN(mes) || isNaN(ano)) return false;

    if (dia<=0 || dia>31 || mes<=0 || mes>12 || ano<1900) return(false);

    if(anobissexto(ano)) 
        if (mes==02 && dia>29) return(false); 
    else 
        if (mes==02 && dia>28) return false;

    if (mes==4 || mes==6 || mes==9 || mes==11)
        if (dia>30) return false;

    return true;
}


function anobissexto(ano)
{
    return ((ano % 4 == 0) && ((!(ano % 100 == 0)) || (ano % 400 == 0)));
}

function validaUpload(file)
{
    if (file.value.indexOf('gif') == -1 && (file.value.indexOf('jpg') == -1 && (file.value.indexOf('GIF')== -1 && (file.value.indexOf('JPG')== -1))))
        ExibeMensagem('<b>Upload:</b>', 'Voce deve selecionar uma imagem nos seguintes formatos: .GIF ou .JPG');
    else
    {
        AjaxUpload(file);
        //ExibeMensagem('<b>Upload</b>', 'Imagem transferida com sucesso.');
        setTimeout('AtualizaImagemExibicao()',1500);
    }
}
function AtualizaImagemExibicao()
{
    Pagina.divUploadFoto.style.display = '';
    var url = '../ImagemUsuario/ImagemUsuario.aspx?rnd=' + Math.floor(Math.random() * 10000).toString();
    //window.open(url,'_blank');
    document.getElementById('imgfotoLoad').src = url;
    document.getElementById('imgFoto').style.display = 'none';
    document.getElementById('imgfotoLoad').style.display = '';
}
function SelecionaImagemDefault(url)
{
    document.getElementById('imgfotoLoad').src = url;
    document.getElementById('imgFoto').style.display = 'none';
    document.getElementById('imgfotoLoad').style.display = '';
    Pagina.divUploadFoto.style.display = 'none';
}
function habilitaAlterarSenha()
{
    document.getElementById('txtSenhaHidden').value = "1";
}