// JavaScript Document


// MOSTRA E ESCONDE AS DIV´S REFERENTE AOS PASSOS
function mostra(hhdiv, id){
	for (i=1; i<=3; i++) {
		if (hhdiv != 'contentPasso'+i) {
			document.getElementById('contentPasso'+i).style.display="none";
			document.getElementById('image'+i).src = "img/setaFrente.gif"
		}
	}
	if (document.getElementById(hhdiv).style.display=="none") {
		document.getElementById(hhdiv).style.display="";
		document.getElementById(id).src = "img/setaBaixo.gif"
	}else {
		document.getElementById(hhdiv).style.display="none";
		document.getElementById(id).src = "img/setaFrente.gif"
	}
}

function setSelect(area) {
	if(area=='work') {
			document.getElementById('selOptions').className=' work';
			document.getElementById('optPalestra').style.display='none'; 
			document.getElementById('optWork').style.display='block'; 
	}
	if(area=='palestra') {
			document.getElementById('selOptions').className=' pal';
			document.getElementById('optWork').style.display='none'; 
			document.getElementById('optPalestra').style.display='block'; 
	}			
}





function PopLoginParticipante()
{
	window.open('PopLogin.asp','Login','width=300, height=200','');
}

function PopIndique()
{
	window.open('PopIndique.asp','Indique','width=410, height=390','');
}

function setLoading()
{
    //$("#loadingPanel").show();
}

function setLoadingFalse()
{
    //$("#loadingPanel").hide(); 
}

 $.validator.addMethod( 'cboUF', function(value,element) { 
     return ($("#cboEstado").val() != ""); 
 });

 $().ready(function() {
     //    $("#loadingPanel").fixedPosition(); 
     //   
     //    setLoading();

 $("#faq_accord").accordion({ autoHeight: false });

     $(".rd").click(function() {
         if ($(this).val() == "PJ") {
             $("#trPJ").show();
             $("#trPF").hide();
         }
         else {
             $("#trPF").show();
             $("#trPJ").hide();
         }

     });

     $("#txtCpf").mask("###.###.###-##", { placeholder: " " });
     $("#txtCnpj").mask("##.###.###/####-##", { placeholder: " " });
     $("#txtDtNascimento").mask("##/##/####", { placeholder: " " });
     $("#txtCEP").mask("#####-###", { placeholder: " " });
     $("#txtLoginCpf").mask("###.###.###-##", { placeholder: " " });


     $("#frmSDD").validate({
         rules: {
             txtSenha: { required: true },
             txtSenhaRpt: { required: true, equalTo: "#txtSenha" },
             pagador_nome: { required: true },
             pagador_email: { required: true, email: true },
             txtDtNascimento: { required: function(element) { return ($(".rd").filter(":checked").val() == "PF") }, dateBR: true },
             txtCpf: { required: function(element) { return ($(".rd").filter(":checked").val() == "PF") }, cpf: true },
             txtRazaoSocial: { required: function(element) { return ($(".rd").filter(":checked").val() == "PJ") } },
             txtCnpj: { required: function(element) { return ($(".rd").filter(":checked").val() == "PJ") } },
             pagador_logradouro: { required: true },
             pagador_numero: { required: true },
             pagador_bairro: { required: true },
             pagador_cidade: { required: true },
             pagador_cep: { required: true },
             cboEstado: { required: true }
         },
         messages:
	    {
	        txtDtNascimento: { dateBR: "*" }
	    }
     });

     $("#faq li").click(function() {

         if ($($(this).next()).css("display") == "none") {
             $($(this).next()).show();
             $($(this).parent()).addClass("over");
         }
         else {
             $($(this).next()).hide();
             $($(this).parent()).removeClass("over");
         }

     });

     $("#optWP tr").mouseover(function() { $(this).addClass("over"); });
     $("#optWP tr").mouseout(function() { $(this).removeClass("over"); });
     $("#optWP tr").click(function() {

         var url = "actions/GetEventDetail.asp?sid=" + Math.random();
         url = url + "&id=" + $(this).attr("id");


         $.ajax(
              {
                  url: url,
                  cache: false,
                  dataType: "html",
                  beforeSend: function() {
                      $("#painelEventos").hide();
                      $("#painelLoading").show();
                  },
                  success: function(html) {
                      $(".painelEscolha").html(html);
                      $(".painelEscolha").fadeIn();
                  },
                  error: function() {
                  setMessage("Ocorreu algum erro na aplicação.")
                  }
              }
          );


     });


     getMyEvents();

     $("#mapa").dialog({
        autoOpen: false,
         show: 'blind',
         hide: 'fold',
         draggable: false,
         modal: true,
         position: 'center',
         title: 'Como Chegar',
         width: 560,
         resizable: false
     });

     $("#login").dialog({
         autoOpen: false,
         show: 'blind',
         hide: 'fold',
         draggable: false,
         modal: true,
         position: 'center',
         title: 'Login',
         width: 560,
         resizable: false
     });

     $("#como-chegar").click(function() {
        $('#mapa').dialog('open');
    });

    $("#login-usuario").click(function() {
        $('#login').dialog('open');
    });
   
 });

function getMyEvents()
{

        var url = "actions/GetMyEvents.asp?sid=" + Math.random();
            
         $.ajax(
              {
                    url: url,
                    cache: false,
                    dataType: "html",
                    beforeSend: function()
                    { 
                      
                    },
                    success: function(html)
                    {
                                $("#painelEventos").html(html);
                                $("#painelEventos").show();   
                    },
                    error: function()
                    {
                        setMessage("Erro ao carregar eventos.")
                    }
              }
          ); 

}


function CalculaDesconto()
{
    var url = "actions/CalcDiscount.asp?sid=" + Math.random();
    url = url+ "&codPromo=" + $("#txtPromocional").val();


    $.ajax(
          {
              url: url,
              cache: false,
              dataType: "xml",
              beforeSend: function() { $(".inputData").hide(); $(".loading").show(); },
              success: function(xml) {
                  var valor = "";
                  var txtValor = "";
                  var cdPromo = "";

                  $(xml).find('txtValor').each(function() { txtValor += $(this).text(); });
                  $(xml).find('valor').each(function() { valor += $(this).text(); });
                  $(xml).find('cdPromo').each(function() { cdPromo += $(this).text(); });
                  SetNewValues(valor, txtValor, cdPromo);
              },
              error: function(request, status, error) {
//                    $(".resultValidacao").html(request.responseText);
//                    $(".loading").hide();
//                    $(".resultValidacao").show();
              }
          }
      ); 

}
function SetNewValues(valor, txtValor, cdPromo)
{
    $(".loading").hide();
    
    valorAtual = parseInt($("input[name='valor']").val());
    NovoValor = parseInt(valor);

    if (!isNaN(NovoValor) && valorAtual != NovoValor) {
        $("input[name='valor']").val(valor);
        $("input[name='txtValor']").val(txtValor.replace('.', ','));
        $("#cdPromo").val(cdPromo);
        $(".resultValidacao").html("Código validado com sucesso!");
        $(".resultValidacao").show();
    }
    else {

        strErro = "Código Promocional Inválido.<br /><a href=\"javascript:alterInterfaceCalc();\">Tentar novamente</a>"
        $(".resultValidacao").html(strErro);
        $(".resultValidacao").show();
        
    }
}

function alterInterfaceCalc() 
{
    $(".resultValidacao").hide();
    $(".loading").hide();
    $(".inputData").show(); 
    
}

function DelEvento(id_evento)
{
	
	var url = "actions/DelEvent.asp?sid=" + Math.random();
        url = url+ "&id=" + id_evento;
            
     $.ajax(
          {
                url: url,
                cache: false,
                dataType: "html",
                beforeSend: function(){},
                success: function(html)
                {    
                    getMyEvents();
                },
                error: function(){setMessage('Ocorreu algum erro na aplicação.');
                }
          }
      ); 
	
}

function AddEvento(id_evento, tipo_evento)
{
    var url = "actions/AddEvent.asp?sid=" + Math.random();
        url = url+ "&id=" + id_evento;
        url = url+ "&tipo=" + tipo_evento;
        
            
     $.ajax(
          {
                url: url,
                cache: false,
                dataType: "html",
                beforeSend: function(){},
                success: function(html)
                {    $(".painelEscolha").fadeOut();
                     getMyEvents();
                },
                error: function(request, status, error) {
                setMessage(request.responseText);
                }
          }
      ); 
    
}

function setMessage(msg)
{
    $("#divError").html(msg);
    $(window).scrollTop(0);
    $("#divError").fadeIn(400);
    setTimeout("hideMessages()",8000);
}

function hideMessages()
{
    $("#divError").fadeOut(400);
}

function ValidaForm()
{
	
    if (!ValidaEventos()){
	    setMessage("Preencha todos os eventos")
		return;
    }
 
	if($("#frmSDD").valid())
	{
	    
        var url = "actions/Cadastro.asp?sid=" + Math.random();
            url = url+ "&id_transacao=" + $("#id_transacao").val();
            url = url+ "&rdTipoCadastro=" + $(".rd").filter(":checked").val();
            url = url+ "&txtSenha=" + $("#txtSenha").val();
            url = url+ "&txtNome=" + $("#txtNome").val();
            url = url+ "&txtEmail=" + $("#txtEmail").val();
            url = url+ "&txtDtNascimento=" + $("#txtDtNascimento").val();
            url = url+ "&txtCpf=" + $("#txtCpf").val();
            url = url+ "&txtRazaoSocial=" + $("#txtRazaoSocial").val();
            url = url+ "&txtCnpj=" + $("#txtCnpj").val();
            url = url+ "&txtEndereco=" + $("#txtEndereco").val();
            url = url+ "&txtNumero=" + $("#txtNumero").val();
            url = url+ "&txtComplemento=" + $("#txtComplemento").val();
            url = url+ "&txtBairro=" + $("#txtBairro").val();
            url = url+ "&txtCidade=" + $("#txtCidade").val();
            url = url+ "&txtCep=" + $("#txtCEP").val();
            url = url+ "&cboEstado=" + $("#cboEstado").val();
            url = url+ "&cdPromo=" + $("#cdPromo").val();
            
            gratuito = false;
            
            if(parseInt($("input[name='valor']").val()) == 0)
                gratuito = true;

            $.ajax(
              {
                  url: url,
                  cache: false,
                  dataType: "html",
                  beforeSend: function() { setLoading(); },
                  success: function(html) {
                      setLoadingFalse();
                      if (html.match("OK") != null) {
                          if (!gratuito)
                              document.forms[0].submit();
                          else {
                              UpdateTransacao();
                              setMessage('Cadastro efetuado com sucesso!');
                          }
                      }
                      else if (html.match("EXISTS") != null) 
                      {
                          setMessage("O usuário já se encontra cadastrado no sistema.");
                      }
                      else 
                        setMessage('Ocorreu algum erro na aplicação.');
                  },
                  error: function() {
                      setLoadingFalse(); setMessage('Ocorreu algum erro na aplicação.');
                  }
              }
          ); 
	    
	}
	else
	    setMessage("Preencha corretamente os Dados Cadastrais.")
	
}

function UpdateTransacao()
{
     var url = "actions/NotificacaoMoip.asp?sid=" + Math.random();
         url = url+ "&id_transacao=" + $("#id_transacao").val();
         url = url+ "&valor=0";
         url = url+ "&status_pagamento=1";
         url = url+ "&cod_moip=0001";
         url = url+ "&tipo_pagamento=Gratuidade";
         
          $.ajax(
          {
                url: url,
                cache: false,
                dataType: "html",
                beforeSend: function(){},
                success: function(html){},
                error: function(){setMessage('Ocorreu algum erro na aplicação.');}
          }
      );

}


function SubmeteLogin() {
  
        var url = "actions/Login.asp?sid=" + Math.random();
        url = url + "&txtCpf=" + $("#txtLoginCpf").val();
        url = url + "&txtSenha=" + $("#txtLoginSenha").val();

        $.ajax(
          {
              url: url,
              cache: false,
              dataType: "html",
              beforeSend: function() { },
              success: function(html) {
                  $("#login").dialog('destroy');
                  window.location.href = "Default.asp";
              },
              error: function(request, status, error) {
                  setMessage(request.responseText);
                  $("#login").dialog('close');
              }
          }
      );
    
}

function EsqueciMinhaSenha() {

    var url = "actions/GetSenha.asp?sid=" + Math.random();
    url = url + "&txtCpf=" + $("#txtLoginCpf").val();

    $.ajax(
          {
              url: url,
              cache: false,
              dataType: "html",
              beforeSend: function() { },
              success: function(html) {
                    setMessage("A senha enviada foi enviada para o seu e-mail.");
                  $("#login").dialog('close');
              },
              error: function(request, status, error) {
                  setMessage(request.responseText);
                  $("#login").dialog('close');
              }
          }
      );

}


function ValidaEventos()
{
//    var tW = 0;
//    var tP = 6;
//    //var Ws = $("#hdNumWorkshops").val();
//    var Ws = -1;
//    var Ps = $("#hdNumPalestras").val();
    //    return ((Ws < tW) || (Ps < tP));

    var tP = 6;
    var Ps = $("#hdNumPalestras").val();

    return (Ps == tP);

}
