<?php
   include $_SERVER["DOCUMENT_ROOT"].'/views/simulador/inc/topo.php';
   require $_SERVER["DOCUMENT_ROOT"].'/api/pages/nova-aposta.php';
?>
      <section id="content">
         <div class="container content">
            <div class="row">
               <div class="col-12 col-lg-3 col-md-3">
                  <div class="box-title">Países</div>
                  <ul class="leagues">
                     <?php foreach ($p["data"] as $pais => $i) { ?>
                     <li><a href="?esporte=<?php if($GETQUERY["esporte"] <> ''){ echo $GETQUERY['esporte']; } else { echo 'futebol'; } ?>&data=<?php echo $GETQUERY['data']; ?>&paises[]=<?php echo ($pais); ?>"><span class="flags flags-category flags--sm flags--<?php echo slugs($pais); ?>"></span> &nbsp; <?php echo ($pais); ?></a></li>
                     <?php } ?>
                  </ul>
               </div>
               <div class="col-12 col-lg-9 col-md-9">
                  <div class="slider"><img src="<?php echo PATH_BASE ?>/img/banner1.jpg" alt=""></div>

                  <div class="row">
                     <div class="col-12 col-lg-8 col-md-8">
                        <form action="" method="GET" id="homeSearchMatches">
                           <?php
                              foreach ($GETQUERY as $k => $v) {
                                 if($k == 'q'){ continue; }
                                 if($k == 'esporte' && $v == ''){ $v = 'futebol'; }
                                 echo '<input type="hidden" name="'.$k.'" value="'.$v.'" />';
                              }
                           ?>
                              <div class="input-group input-group-lg mb-2">
                                 <?php if(isset($GETQUERY['q'])){ ?>
                                    <div class="input-group-prepend">
                                       <a href="?esporte=<?php if($GETQUERY["esporte"] <> ''){ echo $GETQUERY['esporte']; } else { echo 'futebol'; } ?>&data=<?php echo $GETQUERY["data"]; ?>" class="btn btn-danger"><i class="fa fa-times"></i></a>
                                    </div>
                                 <?php } ?>
                                 <input type="text" class="form-control" name="q" placeholder="Pesquise por um país, campeonato ou time..." value="<?php if(isset($GETQUERY['q'])){ echo $GETQUERY['q']; } ?>" />
                                 <div class="input-group-append">
                                    <button type="submit" class="btn btn-info"><i class="fa fa-search"></i></button>
                                 </div>
                              </div>
                        </form>
                        <div class="table-responsive">
                           <table class="table table-striped matches_table">
                              <tr class="bg-main">
                                 <td>Partidas</td>
                                 <td align="center">1</td>
                                 <td align="center">X</td>
                                 <td align="center">2</td>
                                 <td align="center">+</td>
                              </tr>

                              <?php
                                 $qtd_available_matches = 0;
                                 $filtroPaises = array();
                                 foreach ($p["data"] as $pais => $i) {
                                    array_push($filtroPaises, $pais);
                                    if(!in_array($pais, $p["filtroPaises"]) && count($p["filtroPaises"]) > 0){ continue; }
                                    foreach ($i as $event => $m) {
                                       if(in_array($event, $removidos)){ continue; }
                              ?>
                              <tr class="bg-league-name">
                                 <td colspan="5"><span class="flags flags-category flags--sm flags--<?php echo slugs($pais, 0); ?>"></span> <?php echo $event; ?></td>
                              </tr>
                              <?php
                                 foreach ($m as $mid => $match) {
                                    if(in_array($mid, $removidos)){ continue; }
                                    // if(dataValida($match["data"], 1) == FALSE){ continue; }
                                    if($match["casa"] <= 1.01){ $match["casa"] = '--'; }
                                    if($match["empate"] <= 1.01){ $match["empate"] = '--'; }
                                    if($match["fora"] <= 1.01){ $match["fora"] = '--'; }
                                    $qtd_available_matches++;
                              ?>
                              <tr class="match_tr">
                                 <td><div class="mname"><b><?php echo $match['name']; ?></b></div><?php echo $match['data']; ?></td>
                                 <td align="center" class="btn_opt_td <?php if($_SESSION['apostas'][$match['id']]['aposta_token'] == $match['casaid']){ echo 'bg-success'; } elseif($match['casa'] == '--'){ echo ' disabled '; } ?>" onClick="javascript:sendBet(this);" id="sendBet" data-matchname="<?php echo $match['name']; ?>" data-odd="<?php echo $match['casa']; ?>" data-choice="Casa" data-bet="Vencedor do Encontro" data-id="<?php echo $match['casaid']; ?>" data-match="<?php echo $match['id']; ?>"><?php echo $match['casa']; ?></td>
                                 <td align="center" class="btn_opt_td <?php if($_SESSION['apostas'][$match['id']]['aposta_token'] == $match['empateid']){ echo 'bg-success'; } elseif($match['empate'] == '--'){ echo ' disabled '; } ?>" onClick="javascript:sendBet(this);" id="sendBet" data-matchname="<?php echo $match['name']; ?>" data-odd="<?php echo $match['empate']; ?>" data-choice="Empate" data-bet="Vencedor do Encontro" data-id="<?php echo $match['empateid']; ?>" data-match="<?php echo $match['id']; ?>"><?php echo $match['empate']; ?></td>
                                 <td align="center" class="btn_opt_td <?php if($_SESSION['apostas'][$match['id']]['aposta_token'] == $match['foraid']){ echo 'bg-success'; } elseif($match['fora'] == '--'){ echo ' disabled '; } ?>" onClick="javascript:sendBet(this);" id="sendBet" data-matchname="<?php echo $match['name']; ?>" data-odd="<?php echo $match['fora']; ?>" data-choice="Visitante" data-bet="Vencedor do Encontro" data-id="<?php echo $match['foraid']; ?>" data-match="<?php echo $match['id']; ?>"><?php echo $match['fora']; ?></td>
                                 <td align="center" class="btn_opt_td moreOddsMatch<?php echo $match['id']; ?> <?php if($_SESSION['apostas'][$match['id']]['aposta_token'] <> $match['foraid'] && $_SESSION['apostas'][$match['id']]['aposta_token'] <> $match['casaid'] && $_SESSION['apostas'][$match['id']]['aposta_token'] <> $match['empateid'] && isset($_SESSION['apostas'][$match['id']])){ echo 'bg-success'; } ?>" data-toggle="modal" data-target="#modal-options" data-matchname="<?php echo $match['name']; ?>" data-match="<?php echo $match['id']; ?>"" href="#" id="btnOpenMoreOdds">+ <?php if((int)$match['choices'] > 0){ echo $match['choices']; } ?></td>
                              </tr>
                              <?php
                                 } } }

                                if($qtd_available_matches == 0){
                                  echo '<td colspan="5" class="alert alert-warning text-center"><h4>Não há jogos disponíveis para esta data ou pesquisa.</h4></td>';
                                }
                              ?>
                           </table>
                        </div>
                     </div>
                     <div class="col-12 col-lg-4 col-md-4">
                        <div class="box-title">Bilhete</div>
                        <div id="couponContent">
                          <?php
                           $odds = 0;
                           foreach ($_SESSION["apostas"] as $match_id => $m) {
                             echo '<div class="box box-outline-warning coupon-item option'.$m["aposta_token"].'" id="item'.$match_id.'"><div class="box-header"><h4 class="box-title"><small class="coupon-match-name">'.$m["aposta_jogo_nome"].'</small></h4><a class="pull-right fontSize18" data-match="'.$match_id.'" id="clearCoupon"><i class="fa fa-times text-red"></i></a></div><div class="box-body coupon-body-item"><p class="noMargin">'.$m["aposta_nome_aposta"].'</p><p class="noMargin"><strong>'.$m["aposta_opcao"].'</strong> <span class="pull-right" id="itemOdd">'.$m["aposta_cotacao"].'</span></p></div></div>';

                             if($odds == '0'){ $odds = $m["aposta_cotacao"]; }
                             else { $odds *= $m["aposta_cotacao"]; }
                           }
                          ?>
                        </div>
                        <div class="box box-outline-success">
                           <div class="box-body">
                             <?php if($odds > $_SESSION['configs']['config_multiplicador']){ $odds = $_SESSION['configs']['config_multiplicador']; } ?>
                              <p class="noMargin font16">Cotação: <b class="pull-right" id="totalOdds"><?php echo number_format($odds, 2); ?></b></p>
                              <p class="noMargin font16">Retorno: <b class="pull-right" id="totalReturns">R$0,00</b></p>
                              <p class="noMargin"><input type="text" class="form-control pull-right" placeholder="Valor" onkeyup="send(event)" id="priceBet" oninput="this.value = SimpleMaskMoney.format(this.value); calcReturn(this.value);" /></p>
                              <p class="noMargin"><input type="text" class="form-control pull-right" placeholder="Cliente" id="clientName" /></p>
                              <a data-toggle="modal" data-target="#modal-review-bet" class="btn btn-block btn-success btn-md btn-flat" id="review-bet" style="overflow: hidden;"><i class="fa fa-check"></i> &nbsp; Finalizar</a>
                           </div>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </section>
<?php include $_SERVER["DOCUMENT_ROOT"].'/views/simulador/inc/rodape.php'; ?>
<!-- InputMask -->
<script src="/assets/vendor_plugins/input-mask/jquery.inputmask.js"></script>
<script src="/assets/vendor_plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="/assets/vendor_components/bootstrap-daterangepicker/daterangepicker.js"></script>
<script src="/assets/vendor_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js"></script>


<!-- Modal -->
<div class="modal fade bgWhite" id="modal-options" tabindex="-1">
  <div class="modal-dialog modal-lg">
   <div class="modal-content">
     <div class="modal-header">
      <h5 class="modal-title">Mais opções</h5>
      <button type="button" class="close" data-dismiss="modal">
        <span aria-hidden="true">&times;</span>
      </button>
     </div>
     <div class="modal-body">
     </div>
     <div class="modal-footer modal-footer-uniform">
      <a class="btn btn-bold btn-pure btn-danger float-right" data-dismiss="modal">Cancelar</a>
     </div>
   </div>
  </div>
</div>
<!-- /.modal -->

<!-- Modal -->
<div class="modal fade bgWhite" id="modal-review-bet" tabindex="-1">
  <div class="modal-dialog modal-lg">
   <div class="modal-content">
     <div class="modal-header">
      <h5 class="modal-title">Revisar e finalizar</h5>
      <button type="button" class="close" data-dismiss="modal">
        <span aria-hidden="true">&times;</span>
      </button>
     </div>
      <?php
        if(isset($_SESSION["usuario"])){
          echo '<div class="btn btn-success btn-lg msg_creditos">Você tem <b class="creditInformation">R$'.formataReal($_SESSION["usuario"]["credito"]).'</b> em créditos.</div>';
        } else {
          echo '<div class="btn btn-warning btn-lg">Esta é uma <b>SIMULAÇÃO</b>.</div>';
        }
      ?>
     <div class="modal-body">
      <div class="box-body">
         <div class="revisar_bet">
           <center><blockquote>Informações do bilhete</blockquote></center>
           <form id="finishBetForm" action="/api/finishBet" method="POST">
             <div class="media-list media-list-hover media-list-divided">
                <div class="media">
                   <div class="media-body">
                      <p>
                         <a class="hover-primary" href="#"><strong>Nome do cliente</strong></a>
                         <time class="float-right"><input type="text" name="cliente" class="form-control" placeholder="Nome do cliente" id="clientNameReview"></time>
                      </p>
                   </div>
                </div>
                <div class="media">
                   <div class="media-body">
                      <p>
                         <a class="hover-primary" href="#"><strong>Valor da aposta</strong></a>
                         <time class="float-right"><input type="text" name="valor" required="required" onkeyup="send(event)" id="priceBetReview" oninput="this.value = SimpleMaskMoney.format(this.value); calcReturn(this.value);" class="form-control" placeholder="Ex: 10,00"></time>
                      </p>
                   </div>
                </div>
                <div class="media">
                   <div class="media-body">
                      <p>
                         <a class="hover-primary" href="#"><strong>Possível Retorno</strong></a>
                         <time class="float-right"><input type="text" id="totalReturns" class="form-control" disabled="" placeholder="0,00"></time>
                      </p>
                   </div>
                </div>
             </div>
            </form>

           <center><blockquote>Jogos adicionados</blockquote></center>
           <div class="media-list media-list-hover media-list-divided" id="reviewMatchesList">
              <div class="loading_more_odds"><img width="30" class="floader" src="/loaders/grid.svg" /> Carregando seleções...</div>
           </div>
          </div>

         <div class="cupom_concluido">
          <div class="alert alert-success alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            <h4><i class="icon fa fa-check"></i> Pronto!</h4>
            <?php
              if(isset($_SESSION["usuario"])){
                echo 'Seu bilhete foi finalizado com sucesso.';
              } else {
                echo 'Seu PIN foi gerado com sucesso. Agora, vá até um vendedor credenciado para finalizar o bilhete.';
              }
            ?>
          </div>

           <center><blockquote>Código</blockquote></center>
           <div class="media-list media-list-hover media-list-divided">
              <center>
                <h1><b id="codigo_bilhete"></b></h1><br />
              </center>
           </div>

           <center><blockquote>O que fazer agora?</blockquote></center>
           <div class="media-list media-list-hover media-list-divided">
              <center>
                <div class="btn-group">

                  <?php
                    if(isset($_SESSION["usuario"])){
                      echo '<a href="/imprimir" target="framePrint" class="btn mobile-btn-block btn-lg btn-info" id="printButtonFinishBet"><i class="fa fa-print"></i> &nbsp; Imprimir</a>';
                    }
                  ?>

                  <a href="#" class="btn mobile-btn-block btn-lg btn-success" data-dismiss="modal"><i class="fa fa-check"></i> &nbsp; Concluir</a>
                </div>
              </center>

              <iframe src="" id="framePrint" name="framePrint" frameborder="0" height="1"></iframe>
           </div>
         </div>

      </div>
     </div>
     <div class="modal-footer modal-footer-uniform" id="footerReviewBet">
      <a class="btn btn-lg btn-bold btn-pure btn-success float-right" id="finishBet">
        <?php
          if(isset($_SESSION["usuario"])){
            echo '<i class="fa fa-check"></i> &nbsp; Finalizar';
          } else {
            echo '<i class="fa fa-file-text-o"></i> &nbsp; Gerar PIN';
          }
        ?>
      </a>
      <a class="btn btn-lg btn-bold btn-pure btn-danger" data-dismiss="modal">Cancelar</a>
     </div>
   </div>
  </div>
</div>
<!-- /.modal -->

<script src="/js/moneymask.js"></script>
<script>
    let input = document.getElementsByTagName('input')[0];

    // configuration
    SimpleMaskMoney.args = {
        prefix: '',
        suffix: '',
        fixed: true,
        fractionDigits: 2,
        decimalSeparator: ',',
        thousandsSeparator: '.',
        autoCompleteDecimal: false
    };

    // Your send method
    send = (e) => {
        if (e.key !== "Enter") return;
        // This method return value of your input in format number to save in your database
        SimpleMaskMoney.formatToNumber(input.value);
    }

    var selected_choices = [];
    var spinner = '<div class="loadermodal"><center><img class="floader" src="/loaders/rings.svg" /> Carregando...</center></div>';
    $(function() {
        $(document).ready(function() {
            clearOption();
            $('[data-tooltip="tooltip"]').tooltip();

            $('[data-target="#setLimits"]').click(function(){
              $('#loadingInfoSetLimits .loadermodal').remove();
              var btn = $(this);
              var match_id = btn.attr('data-id');
              $('[name="lim_matchid"]').val(match_id);
              $('#loadingInfoSetLimits').prepend(spinner);
              $('#setLimitsMatchName').html(btn.attr('data-match'));
              $.get('/api/getMatchLimits?id='+match_id, function(data) {
                  var info = $.parseJSON(data);
                  $('[name="lim_maxprice"]').val(info.maxprice);
                  $('[name="lim_maxbet"]').val(info.maxbet);
                  $('#loadingInfoSetLimits .loadermodal').remove();
              });
            });

            $('[id="finishBet"]').click(function(){
              var btn = $(this);
              if($('#priceBetReview').val() == ''){ alert('Informe o valor do bilhete.'); return false; }

              btn.html('<i class="fa fa-spinner fa-spin" style="margin-right: 5px;"></i> Finalizando').removeClass('bg-success').addClass('btn-info');
              $('#finishBetForm').submit();
            });

            $('#finishBetForm').submit(function(e){
              var dados = $( this ).serialize();
              $('#reviewError').remove();
              var f = $(this);

              $.ajax({
                type: "POST",
                url: f.attr('action'),
                data: dados,
                success: function( d )
                {
                  try {
                      JSON.parse(d);
                      var dd = $.parseJSON(d);
                      if(dd.codigo != 'undefined'){
                        $('#codigo_bilhete').html(dd.codigo);

                        // RESET VARS
                        $('.creditInformation').html('R$'+dd.credito);
                        $('.cupom_concluido, .revisar_bet, .msg_creditos, #footerReviewBet').toggle();
                        $('#printButtonFinishBet').attr('href', '/imprimir/'+dd.codigo);
                        $('#couponContent').html('');
                        $('#priceBet, #clientName').val('');
                        $('#totalReturns').html('R$0,00');
                        $('#totalOdds, #coupon-qtd').html('0');
                        $('[id="sendBet"], [id="btnOpenMoreOdds"]').removeClass('bg-success');
                      }
                  } catch (e) {
                      $('#footerReviewBet').prepend('<div class="callout callout-danger" id="reviewError"> <h4>OOOOPS!</h4> <p>'+d+'.</p> </div>');
                  }

                  $('[id="finishBet"]').html('<i class="fa fa-check" style="margin-right: 5px;"></i> Finalizar').removeClass('btn-info').addClass('bg-success');
                }
              });

              return false;
              e.preventDefault();
            });

            $('#review-bet').click(function(){
                var clientName = $('#clientName').val();
                var priceBet = $('#priceBet').val();
                $('#reviewMatchesList').html('<div class="loading_more_odds"><img width="30" class="floader" src="/loaders/grid.svg" /> Carregando seleções...</div>');

                $('.revisar_bet, .msg_creditos, #footerReviewBet').show();
                $('.cupom_concluido').hide();

                $('#clientNameReview').val(clientName);
                $('#priceBetReview').val(priceBet);

                // Carrega jogos adicionados
                $('#reviewMatchesList').append('<div class="media-list media-list-hover media-list-divided">');
                $.get('/api/getJSONCoupon', function(d){
                    var info = $.parseJSON(d);
                    $('#reviewMatchesList').html('');

                    if(info.login == true){
                      $('#finishBet').html('<i class="fa fa-check"></i> &nbsp; Finalizar');
                    } else {
                      $('#finishBet').html('<i class="fa fa-file-text"></i> &nbsp; Gerar PIN').removeClass('btn-success').addClass('btn-info');
                    }

                    $.each(info, function(i, item){
                      if(i == 'login'){ return false; }
                      $('#reviewMatchesList').append('<div class="media"> <div class="media-body"> <p> <a class="hover-primary" href="#"><strong>'+item.nome+'</strong></a> <time class="float-right"><b>'+item.cotacao+'</b></time> </p> <p>'+item.nome_aposta+' - <b>'+item.opcao+'</b></p> </div> </div>');
                    });
                });
                $('#reviewMatchesList').append('</div>');
            });

            $('#betslip .toogleCoupon').click(function() {
                $('#coupon-content').slideToggle();
            });
            $('.paisesItem *').click(function() {
                $(this).toggleClass('bg-black').parents('.paisesItem').toggleClass('bg-black');
            });

            $('#goDate').click(function() {
                $('#goDateForm').submit();
            });

            $('#btnEscolherData').click(function() {
                $(this).toggleClass('btn-success');
                $('.escolherData').slideToggle();
            });

            $('[id="changeStatus"]').click(function() {
                var el = $(this);
                var type = el.attr('data-type');
                var name = el.attr('data-name');
                var status = '0';
                if (el.hasClass('active')) {
                    status = '1';
                }

                $.get('/administracao/change-status?status=' + status + '&type=' + type + '&name=' + name, function(d) {
                    if (d != '1') {
                        alert(d);
                        el.toggleClass('active');
                    }
                });
            });

            $('#datepicker').datepicker({
                autoclose: true,
                format: 'yyyy-mm-dd',
            });

            $('#expandEvents').click(function() {
                $('.boxEvent').show();
                $('.box-btn-slide').removeClass('rotate-180');
            });

            $('[id="btnOpenMoreOdds"]').click(function() {
                $('#modal-options .modal-body').html('<div class="loading_more_odds"><img class="floader" src="/loaders/rings.svg" /> Carregando opções...</div>');
                var el = $('#modal-options .modal-body');
                var match_id = $(this).attr('data-match');
                var match_name = $(this).attr('data-matchname');
                $('#modal-options .modal-title').html(match_name);
                $.get('/api/getOptions/' + match_id, function(data) {
                    var info = $.parseJSON(data);
                    el.append('<ul class="list-group">');
                    $.each(info.markets, function(i, item) {
                        var items = Object.keys(item).length;
                        var bootstrapClass = defineClassByItems(items);
                        el.append('<li class="list-group-item btn bg-dark betNameList">' + i + '</li><li class="list-group-item li_inline_odds"><div class="row">');
                        for (var c in item) {
                            var isSelected = '';
                            /*if ($.inArray(item[c]['id'], selected_choices) != -1) {
                                isSelected = 'bg-success';
                            }*/
                            if ($('.option'+item[c]['id']).length) {
                                isSelected = 'bg-success';
                            }
                            el.append('<a href="#" onClick="javascript:sendBet(this);" class="col-12 col-sm-' + bootstrapClass + ' ' + isSelected + ' btn btn-default inline_odds btn-md ' + item[c]['active'] + '" data-matchname="' + match_name + '" data-odd="' + item[c]['odd'] + '" data-choice="' + item[c]['name'] + '" data-bet="' + i + '" data-id="' + item[c]['id'] + '" data-match="' + match_id + '">' + item[c]['name'] + ' <span class="pull-right">' + item[c]['odd'] + '</span></a>');
                        }
                        el.append('</li></div>');
                    });
                    el.append('</ul>');
                    $('#modal-options .modal-body .loading_more_odds').remove();
                });
            });
        });
    });

    function defineClassByItems(items) {
        switch (items) {
            case 2:
                return '6';
                break;
            case 3:
                return '4';
                break;
            case 4:
                return '6';
                break;
            case 6:
                return '6';
                break;
            case 8:
                return '6';
                break;
            case 10:
                return '6';
                break;
            case 12:
                return '4';
                break;
            case 14:
                return '6';
                break;
            case 16:
                return '6';
                break;
            case 18:
                return '4';
                break;
            case 20:
                return '6';
                break;
            default:
                return '6';
        }
    }

    function clearOption(){
      $('[id="clearCoupon"]').click(function(){
        var matchToClear = $(this).attr('data-match');
        var atualQtd = $('#coupon-qtd').html();
        $.get('/api/addBet?clear='+matchToClear, function(e){
          if(e != '1'){ alert(e); }
          else {
            if(matchToClear == 'all'){
              // RESET VARS
              $('#couponContent').html('');
              $('#priceBet, #clientName').val('');
              $('#totalReturns').html('R$0,00');
              $('#totalOdds, #coupon-qtd').html('0');
              $('[id="sendBet"], [id="btnOpenMoreOdds"]').removeClass('bg-success');
            } else {
              $('#item'+matchToClear).remove();
              $('[data-match="'+matchToClear+'"]').removeClass('bg-success');
              $('#coupon-qtd').html(atualQtd - 1);
            }
          }
        });
      });
    }

    function sendBet(el) {

        $('#item' + $(el).attr('data-match')).remove();
        var choice_id = $(el).attr('data-id');
        var match_id = $(el).attr('data-match');
        var htmlEl = $(el).html();
        $(el).html('<i class="fa fa-spinner fa-spin"></i>');
        $.get('/api/addBet?match=' + match_id + '&choice=' + choice_id, function(d) {
            if (d != '1') {
                alert(d);
                $(el).html($(el).attr('data-odd'));
                return false;
            } else {
                //////////////////////////////////////////////////////////////////
                if ($(el).hasClass('bg-success')) {
                    $('[data-id="' + choice_id + '"]').removeClass('bg-success');
                    selected_choices.splice($.inArray($(el).attr('data-id'), selected_choices), 1);
                    $('.moreOddsMatch' + $(el).attr('data-match')).removeClass('bg-success');
                } else {
                    $('[data-match="' + $(el).attr('data-match') + '"]').removeClass('bg-success');
                    $(el).addClass('bg-success');
                    $('[data-id="' + choice_id + '"]').addClass('bg-success');

                    if ($(el).attr('data-bet') != 'Vencedor do Encontro') {
                        $('.moreOddsMatch' + $(el).attr('data-match')).addClass('bg-success');
                    }
                    selected_choices.push($(el).attr('data-id'));
                    var item = '<div class="box box-outline-warning coupon-item option' + $(el).attr('data-id') + '" id="item' + $(el).attr('data-match') + '"><div class="box-header"><h4 class="box-title"><small class="coupon-match-name">' + $(el).attr('data-matchname') + '</small></h4><a class="pull-right fontSize18" id="clearCoupon" data-match="' + $(el).attr('data-match') + '"><i class="fa fa-times text-red"></i></a></div><div class="box-body coupon-body-item"><p class="noMargin">' + $(el).attr('data-bet') + '</p><p class="noMargin"><strong>' + $(el).attr('data-choice') + '</strong> <span class="pull-right" id="itemOdd">' + $(el).attr('data-odd') + '</span></p></div></div>';
                    $('#couponContent').append(item);
                }

                $(el).html(htmlEl);

                $('#coupon-qtd').html($('.coupon-item').length);
                if ($('.coupon-item').length > 0) {
                    //$('#coupon-minimize').addClass('rotate-180');
                    //$('#coupon-content').css('display', 'block');
                }
                //////////////////////////////////////////////////////////////////

                calcReturn($('#priceBet').val());
                clearOption();
            }
        });
    }

    function calcReturn(price) {
        var odds = 0;
        var multiplicador = "<?php echo $_SESSION['configs']['config_multiplicador']; ?>";
        var max_ganhos_reais = "<?php echo $_SESSION['configs']['config_max_ganhos_reais']; ?>";
        price = price.replace(".", "");
        price = price.replace(",", ".");

        $('[id="itemOdd"]').each(function() {
            if (odds == '0') {
                odds = parseFloat($(this).html());
            } else {
                odds = parseFloat($(this).html()) * parseFloat(odds);
            }

        });
        odds = odds.toFixed(2);
        odds = odds.replace(",", "");
        if(parseInt(odds) > parseInt(multiplicador)){ odds = multiplicador; }
        var ret = parseFloat(price) * odds;
        ret = ret.toFixed(2);
        if(ret == 'NaN'){ ret = '0,00'; }

        retCents = ret.replace(".", "");
        if(parseInt(retCents) > parseInt(max_ganhos_reais)){
          ret = (max_ganhos_reais / 100);
          ret = ret.toFixed(2);
        }

        $('[id="totalOdds"]').html(odds);
        $('[id="totalReturns"]').html('R$ ' + ret);
        $('input[id="totalReturns"]').val('R$ ' + ret);
    }

</script>