<?php
   include $_SERVER["DOCUMENT_ROOT"].'/views/simulador/inc/topo.php';
?>
      <section id="content">
         <div class="container content">
            <div class="row">
               <div class="col-12 col-lg-9 col-md-9">
                  <div class="row">
                     <div class="col-12 col-lg-12 col-md-12">
                        <div class="title">Ao vivo</div>
		                  <div class="box-body mobile-no-padding table-responsive">
		                     <table id="matches_table_live" class="table table-bordered table-hover display nowrap margin-top-10 w-p100">
		                        <thead>
		                           <tr>
		                              <th width="100">Tempo</th>
		                              <th width="100">Placar</th>
		                              <th>Partida <span id="loadingIcon" class="pull-right"></span></th>
		                           </tr>
		                        </thead>
		                        <tbody id="getLiveSignals">
		                            <?php
		                              if(isset($api['error'])){ echo '<tr><td colspan="3"><div class="callout callout-danger"> <h4>OOOOPS!</h4> <p>'.$api['error'].'.</p> </div></td></tr>'; }
		                              foreach ($api["live"] as $j) {
		                                if($j['isActive'] == '0'){ continue; }
		                            ?>
		                           <tr>
		                              <td class="text-danger" align="center"><b><?php echo $j['tempo']; ?>'</b></td>
		                              <td class="text-danger" align="center"><b><?php echo $j['placar_jogo']; ?></b></td>
		                              <td>
		                                 <p style="font-size: 13px; margin: 3px 0;"><?php echo $j['campeonato']; ?> <span class="text-green pull-right"><i class="fa fa-spinner fa-spin"></i></span></p>
		                                 <b style="font-size: 16px;"><?php echo $j['nome']; ?></b>

		                                 <p class="matchdate">
		                                  <?php if(in_array('19', $_SESSION["usuario"]["permissoes"])){ ?>
		                                  <button id="changeStatus" onClick="changeStatus(this);" data-type="1" data-name="<?php echo $j['id']; ?>" type="button" class="btn btn-sm btn-toggle btn-success <?php if($j['isActive'] == '1'){ echo 'active'; } ?>" data-toggle="button" aria-pressed="true"><span class="handle"></span></button> |
		                                  <?php } ?> <b style="font-size: 13px;"> &nbsp; <i class="fa fa-circle text-red blink"></i> <?php echo $j["atualizacao"]; ?></b></p>
		                                 <div class="main-odds">
		                                    <a href="#" onClick="javascript:sendBetLive(this);" class="btn bg-navy <?php if($_SESSION['apostas'][$j['id']]['aposta_token'] == $j['casaid']){ echo 'bg-success'; } elseif($j['casa'] == '--'){ echo ' disabled '; } ?>" id="sendBet" data-matchname="<?php echo $j['nome']; ?>" data-odd="<?php echo $j['casa']; ?>" data-choice="Casa" data-bet="Vencedor do Encontro" data-id="<?php echo $j['casaid']; ?>" data-match="<?php echo $j['id']; ?>"><span class="btnBetDescription">Casa</span><?php echo $j['casa']; ?></a>
		                                    <a href="#" onClick="javascript:sendBetLive(this);" class="btn bg-navy <?php if($_SESSION['apostas'][$j['id']]['aposta_token'] == $j['empateid']){ echo 'bg-success'; } elseif($j['empate'] == '--'){ echo ' disabled '; } ?>" id="sendBet" data-matchname="<?php echo $j['nome']; ?>" data-odd="<?php echo $j['empate']; ?>" data-choice="Empate" data-bet="Vencedor do Encontro" data-id="<?php echo $j['empateid']; ?>" data-match="<?php echo $j['id']; ?>"><span class="btnBetDescription">Empate</span><?php echo $j['empate']; ?></a>
		                                    <a href="#" onClick="javascript:sendBetLive(this);" class="btn bg-navy <?php if($_SESSION['apostas'][$j['id']]['aposta_token'] == $j['foraid']){ echo 'bg-success'; } elseif($j['fora'] == '--'){ echo ' disabled '; } ?>" id="sendBet" data-matchname="<?php echo $j['nome']; ?>" data-odd="<?php echo $j['fora']; ?>" data-choice="Visitante" data-bet="Vencedor do Encontro" data-id="<?php echo $j['foraid']; ?>" data-match="<?php echo $j['id']; ?>"><span class="btnBetDescription">Fora</span><?php echo $j['fora']; ?></a>
		                                    <a href="#" id="btnOpenMoreOdds" onClick="openMoreOdds(this, 0);" class="btn btn-dropbox moreOddsMatch<?php echo $j['id']; ?> <?php if($_SESSION['apostas'][$j['id']]['aposta_token'] <> $j['foraid'] && $_SESSION['apostas'][$j['id']]['aposta_token'] <> $j['casaid'] && $_SESSION['apostas'][$j['id']]['aposta_token'] <> $j['empateid'] && isset($_SESSION['apostas'][$j['id']])){ echo 'bg-success'; } ?>" data-toggle="modal" data-target="#modal-options" data-matchname="<?php echo $j['nome']; ?>" data-match="<?php echo $j['id']; ?>"><span class="btnBetDescription">Mais</span>+</a>
		                                 </div>
		                              </td>
		                           </tr>
		                           <?php }  ?>
		                        </tbody>
		                     </table>
		                  </div>
                     </div>
                  </div>
               </div>
             <div class="col-12 col-lg-3 col-md-3">
                <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>
      </section>
<?php include $_SERVER["DOCUMENT_ROOT"].'/views/simulador/inc/rodape.php'; ?>
<!-- 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"></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="/assets/vendor_plugins/DataTables-1.10.15/extensions/Buttons/js/buttons.html5.min.js"></script -->
<!-- script src="/assets/vendor_plugins/DataTables-1.10.15/extensions/Buttons/js/buttons.print.min.js"></script -->
<!-- end - This is for export functionality only -->
<!-- Unique_Admin for Data Table -->
<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 refreshs = 0;
    $(function() {
        $(document).ready(function() {
            clearOption();
            getLiveSignal();
            setInterval(function(){ getLiveSignal(); }, 3000);

            $('[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) {
                      reviewBet();
                      $('#footerReviewBet').prepend('<div class="callout callout-danger" id="reviewError"> <h4>OOOOPS!</h4> <p>'+d+'.</p> </div>');

                      // Atualiza cotações no cupom
                      $.get('/ajax/getOddsCoupon', function(d){
                        var info = $.parseJSON(d);
                        $.each(info.options, function(i, item) {
                          $('.option'+i).find('#itemOdd').html(item);
                        });
                        calcReturn($('#priceBetReview').val());
                      });
                  }

                  $('[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(){
              reviewBet();
            });

            $('#betslip .toogleCoupon').click(function() {
                $('#coupon-content').slideToggle();
            });

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

    function reviewBet(){
      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>');
    }

    function changeStatus(el){
      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');
          }
      });
    }

    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 sendBetLive(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/addBetLive?match=' + match_id + '&choice=' + choice_id, function(d) {
            if (d != '1') {
                alert(d);
                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);
    }

    var permsToChangeMatches = <?php if(in_array('19', $_SESSION["usuario"]["permissoes"])){ echo '1'; } else { echo '0'; } ?>;
    var viewPlacedBets = <?php if(in_array('37', $_SESSION["usuario"]["permissoes"])){ echo '1'; } else { echo '0'; } ?>;

    function getLiveSignal(){
      if(refreshs >= 100){ location.reload(); }
      refreshs = parseInt(refreshs) + parseInt(1);
      console.log('Getting live signals...');
      var el = $('#getLiveSignals');
      $('#loadingIcon').html('<i class="fa fa-spinner fa-spin"></i>');
      $.get('/api/getLive?autolive=1', function(d){
        var info = $.parseJSON(d);
        if(info.error != undefined){ el.html(''); el.append('<tr><td colspan="3"><div class="callout callout-danger"> <h4>OOOOPS!</h4> <p>'+info.error+'.</p> </div></td></tr>'); return false; }
        el.html('');
        $.each(info.live, function(i, item) {
          if(item["isActive"] == '0' && permsToChangeMatches == '0'){ return true; }
          var itemToAppend = '';
          if(viewPlacedBets == '0'){ item["placed_bets"] = '--'; }
          if(item['isGoal'] == '1'){ itemToAppend = itemToAppend + '<tr class="bg-yellow">'; } else { itemToAppend = itemToAppend + '<tr>'; }
          itemToAppend = itemToAppend + '<td class="text-danger" align="center"><b>'+item["tempo"]+'\'</b></td> <td class="text-danger" align="center"><b>'+item["placar_jogo"]+'</b></td> <td> <p style="font-size: 13px; margin: 3px 0;">'+item["campeonato"]+'';
          if(item["transmissao"] == 'True'){ itemToAppend = itemToAppend + ' &nbsp; <a href="http://tv.sistemafbet.com/transmissao/'+item['id']+'" target="_blank" class="btn btn-xs bg-dark btn-flat"><i class="fa fa-desktop"></i> &nbsp; Assistir</a>'; }
           itemToAppend = itemToAppend + '</p><b style="font-size: 16px;">'+item["nome"]+'</b> <p class="matchdate">';
           itemToAppend = itemToAppend + '<b style="font-size: 13px;"> &nbsp; <i class="fa fa-circle text-red blink"></i> '+item["atualizacao"]+'</b></p> <div class="main-odds"> <a href="#" onClick="javascript:sendBetLive(this);" class="btn bg-navy ';
           if(item["casaIsSelected"] == '1'){ itemToAppend = itemToAppend + ' bg-success '; }
           itemToAppend = itemToAppend + '" id="sendBet" data-matchname="'+item['nome']+'" data-odd="'+item['casa']+'" data-choice="Casa" data-bet="Vencedor do Encontro" data-id="'+item['casaid']+'" data-match="'+item['id']+'">'+item['casa']+'</a> <a href="#" onClick="javascript:sendBetLive(this);" class="btn bg-navy ';
           if(item["empateIsSelected"] == '1'){ itemToAppend = itemToAppend + ' bg-success '; }
           itemToAppend = itemToAppend + ' " id="sendBet" data-matchname="'+item['nome']+'" data-odd="'+item['empate']+'" data-choice="Empate" data-bet="Vencedor do Encontro" data-id="'+item['empateid']+'" data-match="'+item['id']+'">'+item['empate']+'</a> <a href="#" onClick="javascript:sendBetLive(this);" class="btn bg-navy ';
           if(item["foraIsSelected"] == '1'){ itemToAppend = itemToAppend + ' bg-success '; }
           itemToAppend = itemToAppend + '" id="sendBet" data-matchname="'+item['nome']+'" data-odd="'+item['fora']+'" data-choice="Visitante" data-bet="Vencedor do Encontro" data-id="'+item['foraid']+'" data-match="'+item['id']+'">'+item['fora']+'</a> <a href="#" id="btnOpenMoreOdds" onClick="openMoreOdds(this, 0);" class="btn btn-dropbox moreOddsMatch'+item['id']+' " data-toggle="modal" data-target="#modal-options" data-matchname="'+item['nome']+'" data-match="'+item['id']+'">+</a> </div> </td> </tr>';

           el.append(itemToAppend);
           if(item['isGoal'] == '1' && $('#enableSound').hasClass('active')){ el.append('<audio src="/sounds/goal.ogg" autoplay="autoplay"></audio>'); }
        });
        $('#loadingIcon').html('<i class="fa fa-check text-green"></i>');
      });
    }

    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';
        }
    }

    var interval;
    function openMoreOdds(btn, isLoop){
      console.log('Getting more odds');
      clearInterval(interval);
      interval = setInterval(function(){ openMoreOdds(btn, '1'); }, 6000);
      if(isLoop == '0'){
        $('#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 = $(btn).attr('data-match');
      var match_name = $(btn).attr('data-matchname');
      $('#modal-options .modal-title').html(match_name);
      $.get('/api/getOptionsLive/' + match_id, function(data) {
          var info = $.parseJSON(data);
          var dinfo = info.data;
          el.html('');
          el.append('<div class="live-tracker"> <div class="tracker"> <div class="tracker-title tracker-padding"> Tempo: '+dinfo["tempo"]+'" <span class="tracker-icons pull-right"> <div class="tracker-icon trico-corner"></div> <div class="tracker-icon trico-yellow"></div> <div class="tracker-icon trico-red"></div> <div class="tracker-icon trico-cfora"></div> <div class="tracker-icon trico-gols"></div> </span> </div> <div class="tracker-t1 tracker-padding"> '+dinfo["team1"]+' <span class="tracker-icons pull-right"> <div class="tracker-icon">'+dinfo["escanteios"][0]+'</div> <div class="tracker-icon">'+dinfo["amarelos"][0]+'</div> <div class="tracker-icon">'+dinfo["vermelhos"][0]+'</div> <div class="tracker-icon">'+dinfo["substituicoes"][0]+'</div> <div class="tracker-icon tracker-yellow">'+dinfo["placar"][0]+'</div> </span> </div> <div class="tracker-t2 tracker-padding"> '+dinfo["team2"]+' <span class="tracker-icons pull-right"> <div class="tracker-icon">'+dinfo["escanteios"][1]+'</div> <div class="tracker-icon">'+dinfo["amarelos"][1]+'</div> <div class="tracker-icon">'+dinfo["vermelhos"][1]+'</div> <div class="tracker-icon">'+dinfo["substituicoes"][1]+'</div> <div class="tracker-icon tracker-yellow">'+dinfo["placar"][1]+'</div> </span> </div> <div class="tracker-update"><i class="fa fa-circle blink tracker-signal"></i> &nbsp; '+dinfo["atualizacao"]+'</div> </div> </div>');
          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:sendBetLive(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();
      });
    }
</script>