<?php 
include_once('../../../php/sessionStart.php'); 
include_once('../../../php/db/dbExec.php');
include_once('../../../php/timezone.php');

$dtFec=date("Y-m-d");
$nAnio=date("Y");
$nMes=date("m");

$empCod = $_SESSION['empCod'];

# QUERYS
$sTipoaboc = "SELECT * FROM tipoaboc WHERE ta_otros='S' ORDER BY ta_cod";
$sMeses = "SELECT * FROM meses";
$sCiemes = "SELECT ciem_stat FROM ciemes WHERE ciem_emp='$empCod' AND ciem_ano=$nAnio AND ciem_mes=$nMes";
$sBancos = "SELECT *, 
              TRIM(ban_nom) as ban_nom,
              TRIM(ban_ctab) as ban_ctab,
              TRIM(ban_ctac) as ban_ctac
            FROM bancos WHERE ban_emp='$empCod'";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["tipoaboc"] = $db->query($sTipoaboc);
$select["meses"] = $db->query($sMeses);
$select["bancos"] = $db->query($sBancos);
$select["bancos2"] = $db->query($sBancos);
$mesCerrado = ($db->sFetchAssoc($sCiemes)["ciem_stat"] == "C") ? "true" : "false";
$anoTrab=date("Y", strtotime($_SESSION['empFtrab']));
$mesTrab=date("m", strtotime($_SESSION['empFtrab']));
?>
<?php include_once('../includes/htmlOpen.php'); ?>
    <main class="main" style="">
      <?php 
        $li[0] = '<i class="fas fa-file-invoice"></i>';
        $li[1] = $_GET["opcNom"];
        include_once('../../../php/includes/ol.php');
      ?>

      <!-- MODAL DOCP -->
      <div class="modal fade" id="modalDocp" tabindex="-1" role="dialog" aria-labelledby="modalDocpTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
          <div class="modal-content bg-dark">
            <div class="modal-header">
              <ul class="nav nav-pills" id="pills-tab" role="tablist">
                <li class="nav-item">
                  <a class="nav-link active" id="pills-006-tab" data-toggle="pill" href="#pills-006" role="tab" aria-controls="pills-006" aria-selected="true"></a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-white" aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">

              <div class="tab-content bg-transparent border-0" id="pills-tabContent">
                <div class="tab-pane fade show active" id="pills-006" role="tabpanel" aria-labelledby="pills-006-tab">
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">
                      <div class="form-row">
                        <div class="col-md-4">
                          <label for="txtDserie">Serie</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtDserie" disabled>
                        </div>
                        <div class="col-md-4">
                          <label for="numDnum">Número</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numDnum" disabled>
                        </div>
                      </div>
                      <div class="form-row">
                        <div class="col-md-4">
                          <label for="txtDcod">Codigo</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtDcod" disabled>
                        </div>
                        <div class="col-md-8">
                          <label for="txtDcli">Nombre Cliente</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtDcli" disabled>
                        </div>
                      </div>
                      <div class="form-row">
                        <div class="col-md-6">
                          <label for="numDsaldo">Saldo del Documento</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numDsaldo" placeholder="0.00" disabled>
                        </div>
                        <div class="col-md-6">
                          <label for="numDabono">Abono a Aplicar</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numDabono" placeholder="0.00">
                        </div>
                      </div>
                    </div>
                    <button type="button" class="btn btn-success btn-block" id="btnModificarDocp">Modificar</button>
                  </form>

                </div>
              </div>
           </div>
          </div>
        </div>
      </div>

      <!-- MODAL LISTA DE DOCUMENTOS -->
      <div class="modal fade" id="modalLisDocp" tabindex="-1" role="dialog" aria-labelledby="modalLisDocpTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg" role="document">
          <div class="modal-content bg-dark">
            <div class="modal-header">
              <ul class="nav nav-pills" id="pills-tab" role="tablist">
                <li class="nav-item">
                  <a class="nav-link active" id="pills-007-tab" data-toggle="pill" href="#pills-007" role="tab" aria-controls="pills-007" aria-selected="true">Lista de documentos con Saldo</a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-white" aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">

              <div class="tab-content bg-transparent border-0" id="pills-tabContent">
                <div class="tab-pane fade show active" id="pills-007" role="tabpanel" aria-labelledby="pills-007-tab">
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">
                      <div class="form-row">
                        <div class="col-md-4">
                          <label for="txtDcodlis">Codigo</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtDcodlis" disabled>
                        </div>
                        <div class="col-md-8">
                          <label for="txtDclilis">Nombre Cliente</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtDclilis" disabled>
                        </div>
                      </div>
                      <div class="form-row">
                          <label> </label>
                      </div>
                      <div class="form-row">
                        <div class="col-md-12">
                          <div class="table-responsive">
                            <table class="table table-hover table-bordered table-dark table-xs" id="tblDocpLis">
                              <thead>
                                <tr>
                                  <th scope="col" class="text-center" width="120">SERIE</th>
                                  <th scope="col" class="text-center" width="120">NÚMERO</th>
                                  <th scope="col" class="text-center" width="45">FEC/DOCTO.</th>
                                  <th scope="col" class="text-center" width="70">T/CAMBIO</th>
                                  <th scope="col" class="text-center" width="100">SALDO</th>
                                  <th scope="col" class="text-center" width="100">ABONO</th>
                                  <th scope="col" class="text-center" width="100">INCLUIR</th>
                                </tr>
                              </thead>
                              <tbody>
                              </tbody>
                              <tfoot>
                                <th scope="col"></th>
                                <th scope="col"></th>
                                <th scope="col"></th>
                                <th scope="col" class="text-right">Totales</th>
                                <th scope="col" id="dataTotSalLis" class="text-right">0.00</th>
                                <th scope="col" id="dataTotAboLis" class="text-right">0.00</th>
                                <th scope="col"></th>
                              </tfoot>
                            </table>
                          </div>
                        </div>
                      </div>
                    </div>
                    <button type="button" class="btn btn-success btn-block" id="btnContiLisDocp">Regresar</button>
                  </form>

                </div>
              </div>
           </div>
          </div>
        </div>
      </div>

      <!-- MODAL POLIZA -->
      <div class="modal fade" id="modalPol" tabindex="-1" role="dialog" aria-labelledby="modalPolTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
          <div class="modal-content bg-dark">
            <div class="modal-header">
              <ul class="nav nav-pills" id="pills-tab" role="tablist">
                <li class="nav-item">
                  <a class="nav-link active" id="pills-00-tab" data-toggle="pill" href="#pills-00" role="tab" aria-controls="pills-00" aria-selected="true"></a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" id="pills-01-tab" data-toggle="pill" href="#pills-01" role="tab" aria-controls="pills-01" aria-selected="false">Buscar Cuentas</a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-light" aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">

              <div class="tab-content bg-transparent border-0" id="pills-tabContent">
                <div class="tab-pane fade show active" id="pills-00" role="tabpanel" aria-labelledby="pills-00-tab">
                  
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">
                      <div class="form-row">
                        <div class="col-md-4">
                          <label for="txtCta">Cuenta</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtCta" placeholder="">
                        </div>
                        <div class="col-md-8">
                          <label for="txtCtaNom">Nombre Cuenta</label>
                          <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtaNom" placeholder="" disabled>
                        </div>
                      </div>
                      <div class="form-row">
                        <div class="col-md-6">
                          <label for="numDebe">Debe</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numDebe" placeholder="0.00">
                        </div>
                        <div class="col-md-6">
                          <label for="numHaber">Haber</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numHaber" placeholder="0.00">
                        </div>
                      </div>
                    </div>

                    <button type="button" class="btn btn-success btn-block" id="btnAgregar">Agregar</button>
                    <button type="button" class="btn btn-success btn-block" id="btnModificar">Modificar</button>
                  </form>

                </div>
                <div class="tab-pane fade" id="pills-01" role="tabpanel" aria-labelledby="pills-01-tab">
                  <?php
                    $a='00';
                    $b='01';
                    include('../busCuentasMov/index.html');
                  ?>
                </div>
              </div>

            </div>
          </div>
        </div>
      </div>



      <div class="container-as">
        <div class="row">
          <div class="col">
            <ul class="nav nav-pills mb-1" id="pills-tab" role="tablist">
              <li class="nav-item">
                <a class="nav-link active" id="pills-0-tab" data-toggle="pill" href="#pills-0" role="tab" aria-controls="pills-0" aria-selected="true">Mantenimiento</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" id="pills-1-tab" data-toggle="pill" href="#pills-1" role="tab" aria-controls="pills-1" aria-selected="true">Buscar Cliente</a>
              </li>
            </ul>
            <div class="tab-content bg-transparent border-0" id="pills-tabContent">
              <div class="tab-pane fade show active" id="pills-0" role="tabpanel" aria-labelledby="pills-0-tab">

                <form action="" name="thisform" autocomplete="off" enctype="multipart/form-data">
                  <div class="form-row">
                    <div class="col-12 col-sm-10">
                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-md-4">
                            <label class="font-size-sm" for="selTabo">Tipo de Abono</label>
                            <select class="form-control form-control-sm form-control-as" name="selTabo" id="selTabo">
                              <?php
                                while ($rec = $db->fetchAssoc($select['tipoaboc'])) {
                                  echo  '<option value="'.$rec['ta_cod'].'" data-afe="'.$rec['ta_afe'].'" data-partsn="'.$rec['ta_partsn'].'" data-trela="'.$rec['ta_trela'].'">'.utf8_encode($rec['ta_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-md-3">
                            <label class="font-size-sm" for="numNum">Número de Documento</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numNum" placeholder="0">
                          </div>
                          <div class="col-md-3">
                            <label class="font-size-sm" for="dtFec">Fecha del Documento</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFec" placeholder="">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-4">
                            <label class="font-size-sm" for="txtCodp">Codigo Cliente</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtCodp" maxlength="20">
                          </div>
                          <div class="col-8">
                            <label class="font-size-sm" for="txtCli">Nombre del Cliente</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtCli" maxlength="20" disabled>
                          </div>
                          <div class="col-3 ">
                            <label class="font-size-sm" for="numTcam">Tasa de Cambio</label>
                            <input type="number" class="form-control form-control-sm form-control-as dec-6" id="numTcam">
                          </div>
                          <div class="col-2.5">
                            <label class="font-size-sm pr-1">Moneda de la Transacción</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crTmone1" name="crTmone" class="custom-control-input calcular" value="L">
                              <label class="font-size-sm custom-control-label" for="crTmone1">Local</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crTmone2" name="crTmone" class="custom-control-input calcular" value="E">
                              <label class="font-size-sm custom-control-label" for="crTmone2">Extranjera</label>
                            </div>
                          </div>
                        </div>

                        <div class="form-row">
                          <div class="col-12">
                            <label class="font-size-sm" for="txtCon">Concepto</label>
                            <textarea class="form-control form-control-sm form-control-as" id="txtCon" rows="2"></textarea>
                          </div>
                        </div>
                        <div class="form-row">
                          <label>  </label>
                        </div>
                        <h4 class="text-success">FORMA DE PAGO:</h4>
                        <div class="form-row">
                          <div class="col-2">
                            <label class="font-size-sm text-success" for="numEfec">Efectivo</label>
                            <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numEfec" placeholder="0.00" min="0">
                          </div>
                          <div class="col-4">
                            <label class="font-size-sm text-success" for="txtNtarj">No. Tarjeta</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtNtarj" maxlength="50">
                          </div>
                          <div class="col-2">
                            <label class="font-size-sm text-success" for="numVtarj">Valor Tarjeta</label>
                            <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numVtarj" placeholder="0.00" min="0">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-2">
                            <label class="font-size-sm text-success" for="numNch">Numero de Cheque</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numNch">
                          </div>
                          <div class="col-4">
                            <label class="font-size-sm text-success" for="txtBanch">Nombrel del Banco del Cheque</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtBanch" maxlength="50">
                          </div>
                          <div class="col-2">
                            <label class="font-size-sm text-success" for="numVch">Valor Cheque</label>
                            <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numVch" placeholder="0.00" min="0">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-md-4">
                            <label class="font-size-sm text-success" for="selBan">Banco Deposito</label>
                            <select class="form-control form-control-sm form-control-as" name="selBan" id="selBan">
                              <?php
                                while ($rec = $db->fetchAssoc($select['bancos'])) {
                                  echo  '<option value="'.$rec['ban_num'].'" data-ctab="'.$rec['ban_ctab'].'" data-ctac="'.$rec['ban_ctac'].'" data-forma="'.$rec['ban_forma'].'">'.utf8_encode($rec['ban_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-md-3">
                            <label class="font-size-sm text-success" for="numNdepo">No. Deposito</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numNdepo" placeholder="0">
                          </div>
                          <div class="col-md-3">
                            <label class="font-size-sm text-success" for="dtFdepo">Fecha Deposito</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFdepo">
                          </div>
                          <div class="col-2">
                            <label class="font-size-sm text-success" for="numVdepo">Valor Deposito</label>
                            <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numVdepo" placeholder="0.00" min="0">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-md-4">
                            <label class="font-size-sm text-success" for="selBan2">Banco Transferencia</label>
                            <select class="form-control form-control-sm form-control-as" name="selBan2" id="selBan2">
                              <?php
                                while ($rec = $db->fetchAssoc($select['bancos2'])) {
                                  echo  '<option value="'.$rec['ban_num'].'" data-ctab="'.$rec['ban_ctab'].'" data-ctac="'.$rec['ban_ctac'].'" data-forma="'.$rec['ban_forma'].'">'.utf8_encode($rec['ban_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-md-3">
                            <label class="font-size-sm text-success" for="numNdepo2">No. Transferencia</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numNdepo2" placeholder="0">
                          </div>
                          <div class="col-md-3">
                            <label class="font-size-sm text-success" for="dtFdepo2">Fecha Transferencia</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFdepo2">
                          </div>
                          <div class="col-2">
                            <label class="font-size-sm text-success" for="numVdepo2">Valor Transferencia</label>
                            <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numVdepo2" placeholder="0.00" min="0">
                          </div>
                        </div>
                      </div>
                      <div class="form-row">
                        <div class="col-4">
                          <button type="button" class="btn btn-warning" id="btnBusdocp">
                            <i class="fas fa-plus-circle"></i> BUSCAR DOCUMENTOS
                          </button>
                        </div>
                      </div>

                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-12 text-right mb-2">
                          </div>
                          <div class="col-md-9">
                            <div class="table-responsive">
                              <table class="table table-hover table-bordered table-dark table-xs" id="tblDocp">
                                <thead>
                                  <tr>
                                    <th scope="col" class="text-center ignore" width="50">ACCIONES</th>
                                    <th scope="col" class="text-center" width="150">SERIE</th>
                                    <th scope="col" class="text-center" width="150">NÚMERO</th>
                                    <th scope="col" class="text-center" width="45">FEC/DOCTO.</th>
                                    <th scope="col" class="text-center" width="90">T/CAMBIO</th>
                                    <th scope="col" class="text-center" width="120">SALDO</th>
                                    <th scope="col" class="text-center" width="120">ABONO</th>
                                  </tr>
                                </thead>
                                <tbody>
                                </tbody>
                                <tfoot>
                                  <th scope="col" class="ignore"></th>
                                  <th scope="col"></th>
                                  <th scope="col"></th>
                                  <th scope="col"></th>
                                  <th scope="col" class="text-right">Totales</th>
                                  <th scope="col" id="dataTotSal" class="text-right">0.00</th>
                                  <th scope="col" id="dataTotAbo" class="text-right">0.00</th>
                                  <th scope="col"></th>
                                </tfoot>
                              </table>
                            </div>
                          </div>
                        </div>
                      </div>

                      <h3 class="text-light"></h3>

                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-5">
                            <button type="button" class="btn btn-success" id="btnAdd">
                              <i class="fas fa-plus-circle"></i> Agregar
                            </button>
                          </div>
                          <div class="col-7 text-right">
                            <button class="btn btn-primary" id="btnPartida" type="button"><i class="fas fa-poll-h"></i> Generar Partida</button>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-12 text-right mb-2">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-md-12">
                            <div class="table-responsive">
                              <table class="table table-hover table-bordered table-dark table-sm" id="tblPol">
                                <thead>
                                  <tr>
                                    <th scope="col" class="text-center ignore" width="50">ACCIONES</th>
                                    <th scope="col" class="text-center">CUENTA</th>
                                    <th scope="col" class="text-center">DESCRIPCIÓN</th>
                                    <th scope="col" class="text-center">DEBE</th>
                                    <th scope="col" class="text-center">HABER</th>
                                  </tr>
                                </thead>
                                <tbody>
                                </tbody>
                                <tfoot>
                                  <th scope="col" class="ignore"></th>
                                  <th scope="col"></th>
                                  <th scope="col" class="text-right">Totales</th>
                                  <th scope="col" id="dataTotDebe" class="text-right">0.00</th>
                                  <th scope="col" id="dataTotHaber" class="text-right">0.00</th>
                                </tfoot>
                              </table>
                            </div>
                          </div>
                        </div>
                      </div>

                      <div class="form-group">
                        <div class="form-row">
                        </div>
                      </div>
                    </div>

                    <div class="col-12 col-sm-2">
                      <div class="form-group position-fixed-sm">

                        <div class="form-row">
                          <div class="col-12 mt-2">
                            <button class="btn btn-info btn-block" id="btnGuardarImprimir" type="button">Imprimir / Guardar</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-success btn-block" id="btnGuardar" type="button">Guardar</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-danger btn-block" id="btnAnular" type="button">Anular</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-primary btn-block" id="btnBorrar" type="button">Borrar</button>
                          </div>
                        </div>

                      </div>
                    </div>
                  </div>
                </form>
              </div>
              <div class="tab-pane fade" id="pills-1" role="tabpanel" aria-labelledby="pills-1-tab">
                <?php
                  $a='0';
                  $b='1';
                  include('../busCliencc/index.html')
                ?>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var totant = 0;
  var inputDocp = "numNum";
  var tblPolAnt;
  var tblDocpAnt;
  var mesCerrado = <?php echo $mesCerrado ?>;
  var mesCerradoI = <?php echo $mesCerrado ?>;
  var btnAddEdit = "00";
  var nuevoClien = true;
  var inputCtaMov = "txtCta";
  var inputClien = "txtNit"
  var inputDepo = "numNum";
  
  var sumcta=0;
  var falcta=0;

  const numNum = document.thisform.numNum;
  const selTabo = document.thisform.selTabo;
  const txtCodp = document.thisform.txtCodp;
  const txtCli = document.thisform.txtCli;
  const dtFec = document.thisform.dtFec;
  const numEfec = document.thisform.numEfec;
  const txtNtarj = document.thisform.txtNtarj;
  const numVtarj = document.thisform.numVtarj;
  const selBan = document.thisform.selBan;
  const numNdepo = document.thisform.numNdepo;
  const dtFdepo = document.thisform.dtFdepo;
  const numVdepo = document.thisform.numVdepo;
  const selBan2 = document.thisform.selBan2;
  const numNdepo2 = document.thisform.numNdepo2;
  const dtFdepo2 = document.thisform.dtFdepo2;
  const numVdepo2 = document.thisform.numVdepo2;
  const numTcam = document.thisform.numTcam;
  const crTmone = document.thisform.crTmone;
  const txtCon = document.thisform.txtCon;


  const txtCta = document.getElementById("txtCta");
  const txtCtaNom = document.getElementById("txtCtaNom");
  const numDebe = document.getElementById("numDebe");
  const numHaber = document.getElementById("numHaber");

  function addRowDocp(tipod, seried, numd, fecd, tcam, saldo, abono){
    const row = "<tr>"
                  +"<td scope='col' class='ignore'>"
                    +"<div class='btn-group btn-group-sm' role='group' aria-label='Third group'>"
                      +"<button type='button' class='btn btn-danger btn-sm btn-actions' id='btnDelDocp'><i class='fas fa-trash-alt'></i></button>"
                      +"<button type='button' class='btn btn-primary btn-sm btn-actions' id='btnEditDocp' data-toggle='modal' data-target='#modalDocp'><i class='fas fa-edit'></i></button>"
                    +"</div>"
                  +"</td>"
                  +"<td id='datatipod' class='text-left d-none'>"+tipod+"</td>"
                  +"<td id='dataseried' class='text-left'>"+seried+"</td>"
                  +"<td id='datanumd' class='text-left'>"+numd+"</td>"
                  +"<td id='datafecd'>"+fecd+"</td>"
                  +"<td id='datatcam' class='text-left'>"+tcam+"</td>"
                  +"<td id='datasaldo' class='text-right'>"+saldo+"</td>"
                  +"<td id='dataabono' class='text-right'>"+abono+"</td>"
                +"</tr>";
    $("#tblDocp tbody").append(row);
  }

  sumCaja();

  function addRowDocpLis(tipodlis,seriedlis, numdlis, fecdlis, tcamlis, saldolis, abonolis,l){
    const row = "<tr>"
                  +"<td id='datatipodlis' class='text-left d-none'>"+tipodlis+"</td>"
                  +"<td id='dataseriedlis' class='text-left'>"+seriedlis+"</td>"
                  +"<td id='datanumdlis' class='text-left'>"+numdlis+"</td>"
                  +"<td id='datafecdlis'>"+YMDToDMY(fecdlis)+"</td>"
                  +"<td id='datatcamlis' class='text-left'>"+tcamlis+"</td>"
                  +"<td id='datasaldolis' class='text-right'>"+saldolis+"</td>"
                  +"<td id='dataabonolis' class='text-right'>"+abonolis+"</td>"
                  +"<td class='text-center'>"
                    +"<div class='custom-control custom-checkbox'>"
                    +"<input type='checkbox' class='custom-control-input' id='dataCheck"+l+"' name='cblis'>"
                    +"<label class='custom-control-label mt-0' for='dataCheck"+l+"'></label>"
                    +"</div>"
                  +"</td>"
                +"</tr>";
    $("#tblDocpLis tbody").append(row);
  }

  sumCajaLis();

  function sumCaja() {
    var acum = 0;
    var acuma = 0;

    $("#tblDocp").find('tbody tr').each(function () {
      acuma += parseFloat($(this).find('#dataabono').text());
      acum += parseFloat($(this).find('#datasaldo').text());
    });
    $("#tblDocp #dataTotSal").text(acum.toFixed(2));
    $("#tblDocp #dataTotAbo").text(acuma.toFixed(2));
  }

  function sumCajaLis() {
    var acum = 0;
    var acuma = 0;

    $("#tblDocpLis").find('tbody tr').each(function () {
      if ($(this).find('td input[name="cblis"]').is(":checked")){
        if (parseFloat($(this).find('#dataabonolis').text()) == "0.00") {
           $(this).find('#dataabonolis').text($(this).find('#datasaldolis').text());
        }
        acuma += parseFloat($(this).find('#dataabonolis').text());
      } else {
        $(this).find('#dataabonolis').text("0.00");
      } 
      acum += parseFloat($(this).find('#datasaldolis').text());
    });
    $("#tblDocpLis #dataTotSalLis").text(acum.toFixed(2));
    $("#tblDocpLis #dataTotAboLis").text(acuma.toFixed(2));
  }


  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(selTabo.value)) {
        selTabo.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Tipo de Documento"}});
        return true;
      }
      if (isNullPer(numNum.value)  || numNum.value == 0) {
        numNum.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE DOCUMENTO"}});
        return true;
      }
      if ($("#dataTotDebe").text() != $("#dataTotHaber").text() && partsn == 'S') {
        alWarning({"msg":{"title":"Valores Incorrectos","text":"La partida no cuadra, verifique los valores"}});
        return true;
      }
      // PARA VER SI LA PARTIDA ESTÁ VACÍA
      if ($("#tblPol tbody").children().length == 0 && partsn == 'S' && (numEfec.value!=0 || numVtarj.value!=0)) {
        alWarning({"msg":{"title":"Partida Vacía","text":"Es necesario Generar Partida"}});
        return true;
      }
      // RECORRER PARTIDA PARA BUSCAR UNA CUENTA INCORRECTA
      var ctaInc = false;
      var ctaIncBan = true;
      var debInc = false;
      var sumtot = (numEfec.value+numVtarj.value);
      $("#tblPol tbody tr").each(function(){
        if ($(this).find("td:eq(1)").text().includes('XXXX')) { ctaInc = true }
        if ($(this).find("td:eq(1)").text() == ctacli.toString()) {
          ctaIncBan = false;
          if ($(this).find("td:eq(4)").text() != (Number(sumtot)).toFixed(2)) {
            debInc = true;
          }
        }
      });
      /*if (ctaInc || ctaIncBan) {
        alWarning({"msg":{"title":"Cuenta Incorrecta","text":"Alguna cuenta de la partida no está asignada correctamente, verifique"}});
        return true;
      }
      if (debInc) {
        alWarning({"msg":{"title":"Debito Incorrecto","text":"Lo que quiere debitar en la cuenta de Proveedor NO COINCIDE CON EL TOTAL DEL DOCUMENTO, verifique."}});
        return true;
      } */
    } else {
      if (isNullPer(selTabo.value) || isNullPer(numNum.value)) {
        return true;
      }
    }
    return false;
  }


  function restriccionCamposVacios() {
    if (isNullPer(selTabo.value)) {
      selTabo.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Tipo de Documento"}});
      return true;
    }
    if (isNullPer(numNum.value)) {
      numNum.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE DOCUMENTO"}});
      return true;
    }
    return false;
  }

  function condicionesobligatorias() {
    if (isNullPer(txtCodp.value)) {
      txtCodp.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CODIGO DEL CLIENTE"}});
      return true;
    }
    if (isNullPer(numEfec.value) && isNullPer(numVch.value) && isNullPer(numVtarj.value) && isNullPer(numVdepo.value) && isNullPer(numVdepo2.value)) {
      numEfec.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario que ingrese algun valor en LA FORMA DE PAGO"}});
      return true;
    }
    if (isNullPer(numTcam.value)) {
      numTcam.value = (1).toFixed(6);
      numTcam.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar algun Valor en la Tasa de Cambio"}});
      return true;
    }
  }


  function restriccionMesCerrado() {
    if (mesCerrado) {
      alError({"msg":{"type":"error","title":"Mes Cerrado","text":"No puede trabajar con este mes porque ya fue cerrado", "ok":"Aceptar"}});
      return true;
    }
    return false;
  }


  function restriccionCta() {
    if (isNullPer(txtCta.value)) {
      txtCtaNom.value = "";
      return true;
    }
    return false;
  }

  function restriccionCtaCod() {
    if (isNullPer($("#"+inputCtaMov).val())) {
      $("#"+inputCtaMov+"Nom").val("");
      return true;
    }
    return false;
  }

  function restriccionModal() {
    if (restriccionCta()) {
      txtCta.focus();
      alWarningTimer({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar la CUENTA","timer":timeOutWarningSm}});
      return true;
    }
    $('#modalPol').modal('toggle');
    return false;
  }

  function restriccionModalDocp(saldo) {
    if (numDabono.value > Number(saldo)) {
      numDabono.focus(); 
      alWarning({"msg":{"title":"Error En el Abono","text":"Intenta registrar un Abono superior al saldo"}});      
      return true;
    } 
    if (numDabono.value < 0.00) {
      numDabono.focus(); 
      alWarning({"msg":{"title":"Error En el Abono","text":"No debe ingresar valor negativo"}});
      return true;
    } 
    $('#modalDocp').modal('toggle');
    return false;
  }


  function addRowPol(cta, ctaNom, debe, haber){
    const row = "<tr>"
                +"<td scope='col' class='ignore'>"
                  +"<div class='btn-group btn-group-sm' role='group' aria-label='Third group'>"
                    +"<button type='button' class='btn btn-danger btn-sm btn-actions' id='btnDel'><i class='fas fa-trash-alt'></i></button>"
                    +"<button type='button' class='btn btn-primary btn-sm btn-actions' id='btnEdit' data-toggle='modal' data-target='#modalPol'><i class='fas fa-edit'></i></button>"
                  +"</div>"
                +"</td>"
                +"<td id='dataCta'>"+cta+"</td>"
                +"<td id='dataCtaNom'>"+ctaNom+"</td>"
                +"<td id='dataDebe' class='text-right'>"+debe+"</td>"
                +"<td id='dataHaber' class='text-right'>"+haber+"</td>"
                +"</tr>";
    $("#tblPol tbody").append(row);
  }


  function consultarDocabo(){
    if (restriccion(true)) {return};
    
    //txtNext = dtFec;

    const parametros = new FormData();
    parametros.append("action", "consultar");

    parametros.append("numNum", numNum.value);
    parametros.append("selTabo", selTabo.value);

    //txtNext.focus()

    $.ajax({
      data:  parametros,
      url:   window.location.origin+window.location.pathname+"actions.php",
      type:  "post",
      contentType: false,
      processData: false,
      success: function (jsonPhp) {
        console.log(jsonPhp);
        const jsonJS = JSON.parse(jsonPhp);
        tblDocpAnt = JSON.stringify(jsonJS.abo_detc);
        tblPolAnt = JSON.stringify(jsonJS.poli_det);

        if(jsonJS.error == true){
          alError(jsonJS);
        } else {
          limpiar();
          tblClear("tblPol");
          sumPol();
          tblClear("tblDocp");
          sumCaja();

         
          if (isNullPer(jsonJS.abonosc)) {
            nuevo = true;
            crTmonea = "L";
            numTcama = (1).toFixed(6);
            selBanant=0;
            numNdepoant=0;
            numVdepoant=0;
            selBan2ant=0;
            numNdepo2ant=0;
            numVdepo2ant=0;
          } else {
            dtFec.value = jsonJS.abonosc.abo_fec;
            txtCodp.value = jsonJS.abonosc.abo_codp;
            txtCli.value = jsonJS.abonosc.cli_nom;
            nitcli = jsonJS.abonosc.cli_nit;
            ctacli = jsonJS.abonosc.cli_cta;
            numEfec.value = jsonJS.abonosc.abo_efec;
            txtNtarj.value = jsonJS.abonosc.abo_ntarj;
            numVtarj.value = jsonJS.abonosc.abo_vtarj;
            txtBanch.value = jsonJS.abonosc.abo_banch;
            numNch.value = jsonJS.abonosc.abo_nch;
            numVch.value = jsonJS.abonosc.abo_vch;
            selBan.value = jsonJS.abonosc.abo_nban;
            numNdepo.value = jsonJS.abonosc.abo_ndepo;
            dtFdepo.value = jsonJS.abonosc.abo_fdepo;
            numVdepo.value = jsonJS.abonosc.abo_vdepo;
            selBan2.value = jsonJS.abonosc.abo_nban2;
            numNdepo2.value = jsonJS.abonosc.abo_ndepo2;
            dtFdepo2.value = jsonJS.abonosc.abo_fdepo2;
            numVdepo2.value = jsonJS.abonosc.abo_vdepo2;
            selBanant=jsonJS.abonosc.abo_nban;
            numNdepoant=jsonJS.abonosc.abo_ndepo;
            numVdepoant=jsonJS.abonosc.abo_vdepo;
            selBan2ant=jsonJS.abonosc.abo_nban2;
            numNdepo2ant=jsonJS.abonosc.abo_ndepo2;
            numVdepo2ant=jsonJS.abonosc.abo_vdepo2;
            numTcam.value = jsonJS.abonosc.abo_tcam;
            txtCon.value = jsonJS.abonosc.abo_con;
            crTmone.value = jsonJS.abonosc.abo_tmone;
            crTmonea = jsonJS.abonosc.abo_tmone;
            numTcama = jsonJS.abonosc.abo_tcam;
            jsonJS.abo_detc.forEach(function(i){
              addRowDocp(i.abd_tipoc, i.abd_seriec, i.abd_numc, YMDToDMY(i.abd_feccd), i.abd_tcam, i.abd_sal, i.abd_abop);
            });  
            sumCaja();
            jsonJS.poli_det.forEach(function(i){
              addRowPol(i.pold_cta, i.pold_ctan, i.pold_debe, i.pold_haber);
            });
            sumPol();
            nuevo = false;
          }
          //(pressEnter) ? alClose() : alCloseFocus(txtNext);
          //pressEnter = false; 
          //alClose();
          //dtFec.focus();
        }
      }
    });
  }

  function guardarDocp(imprimir = false){
    if (restriccion()) {return};

      const pIva = <?php echo $_SESSION["pIva"]; ?>;

      if ($("#tblDocp tbody").children().length == 0) {
        alWarning({"msg":{"title":"NO HA REGISTRADO DOCUMENTOS","text":"Primero debe registrar documentos que va a abonar."}});
        return;
      }
      sumfpago=Number(numEfec.value)+Number(+numVtarj.value)+Number(numVch.value)+Number(numVdepo.value)+Number(numVdepo2.value);
      if (sumfpago!=$("#tblDocp #dataTotAbo").text()) { 
        alWarning({"msg":{"title":"SUMAS NO CUADRAN","text":"La suma de los abonos, no cuadra con la sumatoria de la forma de pago, revise."}});
        return;
      }

      if (crTmone.value == 'E') {
        var Qefec = round(Number(numEfec.value)*Number(numTcam.value),2);
        var Qvtarj = round(Number(numVtarj.value)*Number(numTcam.value),2);
        var Qvch = round(Number(numVch.value)*Number(numTcam.value),2);
      } else {
        var Qefec = Number(numEfec.value);
        var Qvtarj = Number(numVtarj.value);
        var Qvch = Number(numVch.value);
      } 
      var Qsub = Qefec;
      var Qiva = 0;
      if ($('#selTabo').find('option:selected').data('afe') == "S") {
        Qsub/=((pIva/100)+1);
        Qiva = (Qefec-Qsub);
      }

    const numDoc = numNum.value;

    colDocp = ["acciones","tipo", "serie", "numero", "fecha", "tcam", "saldo", "abono"];

    colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

    const parametros = new FormData();

    parametros.append("action", "guardar");

    parametros.append("nuevo", nuevo);
    parametros.append("numNum", numNum.value);
    parametros.append("selTabo", selTabo.value);
    parametros.append("dtFec", dtFec.value);
    parametros.append("txtCodp", txtCodp.value);
    parametros.append("txtCli", txtCli.value);
    parametros.append("nitcli", nitcli);
    parametros.append("ctacli", ctacli);
    parametros.append("numTcam", numTcam.value);
    parametros.append("crTmone", crTmone.value);
    parametros.append("numTcama", numTcama);
    parametros.append("crTmonea", crTmonea);
    parametros.append("txtCon", txtCon.value);
    parametros.append("numEfec", numEfec.value);
    parametros.append("txtNtarj", txtNtarj.value);
    parametros.append("numVtarj", numVtarj.value);
    parametros.append("numNch", numNch.value);
    parametros.append("txtBanch", txtBanch.value);
    parametros.append("numVch", numVch.value);
    parametros.append("selBan", selBan.value);
    parametros.append("BanCtac", $('#selBan').find('option:selected').data('ctac'));
    parametros.append("numNdepo", numNdepo.value);
    parametros.append("dtFdepo", dtFdepo.value);
    parametros.append("numVdepo", numVdepo.value);
    parametros.append("selBan2", selBan2.value);
    parametros.append("Ban2Ctac", $('#selBan2').find('option:selected').data('ctac'));
    parametros.append("numNdepo2", numNdepo2.value);
    parametros.append("dtFdepo2", dtFdepo2.value);
    parametros.append("numVdepo2", numVdepo2.value);
    parametros.append("selBanant", selBanant);
    parametros.append("numNdepoant", numNdepoant);
    parametros.append("numVdepoant", numVdepoant);
    parametros.append("selBan2ant", selBan2ant);
    parametros.append("numNdepo2ant", numNdepo2ant);
    parametros.append("numVdepo2ant", numVdepo2ant);
    parametros.append("Qefec", Qefec);
    parametros.append("Qvtarj", Qvtarj);
    parametros.append("Qvch", Qvch);
    parametros.append("Qsub", Qsub);
    parametros.append("Qiva", Qiva);
    parametros.append("taafe", $('#selTabo').find('option:selected').data('afe'));
    parametros.append("tatrela", $('#selTabo').find('option:selected').data('trela'));
    parametros.append("partsn", $('#selTabo').find('option:selected').data('partsn'));
    parametros.append("tblPol", tblToJson(colPol, "tblPol", 0));
    parametros.append("tblPolAnt", tblPolAnt);
    parametros.append("tblDocp", tblToJson(colDocp, "tblDocp", 0));
    parametros.append("tblDocpAnt", tblDocpAnt);

    numNum.focus();
    
    $.ajax({
      data:  parametros,
      url:   window.location.origin+window.location.pathname+"actions.php",
      type:  "post",
      contentType: false,
      processData: false,
      async: true,
      beforeSend: function () {
        alLoad("Cargando...")
      },
      success: function (jsonPhp) {
        console.log(jsonPhp);

        setTimeout(function () {

        const jsonJS = JSON.parse(jsonPhp);

        if(jsonJS.error==true){
          alError(jsonJS);
        } else {
          var snhacer = true;

          if (jsonJS.probpol1 != "X") {
            alError({"msg":{"type":"error","title":"PROBLEMA EN CUENTAS","text":"Alguna de las cuentas no esta asignada correctamente, verifique.", "ok":"Aceptar"}});
              var snhacer = false;
                     return true;
          }
          if (snhacer) {
            numNum.value = "";
            limpiar();
            tblClear("tblPol");
            sumPol();
            tblClear("tblDocp");
            sumCaja();
            tblClear("tblDocpLis");
            sumCajaLis();
            alSuccess(jsonJS);
            if (imprimir) {
              imprimirDocp(numDoc);
            }
          }  
        }

        }), 0;
      }
    });
  }

  function imprimirDocp(numDoc){

    colDocp = ["acciones","serie", "numero", "fecha", "tcam", "saldo", "abono"];

    colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

    const getTabo = "?selTabo="+selTabo.value;
    const getNum = "&numNum="+numDoc;
    const getTaboNom = "&selTaboNom="+$("#selTabo option:selected").text();
    const getFec = "&dtFec="+dtFec.value;
    const getCodp = "&txtCodp="+txtCodp.value;
    const getCli = "&txtCli="+txtCli.value;
    const getnitcli = "&nitprov="+nitcli;
    const getcrTmone = "&crTmone="+crTmone.value;
    const getEfec = "&numEfec="+numEfec.value;
    const getVtarj = "&numVtarj="+numVtarj.value;
    const getNtarj = "&txtNtarj="+txtNtarj.value;
    const getVch = "&numVch="+numVch.value;
    const getselBan = "&selBan="+selBan.value;
    const getselBanNom = "&selBanNom="+$("#selBan option:selected").text();
    const getNdepo = "&numNdepo="+numNdepo.value;
    const getVdepo = "&numVdepo="+numVdepo.value;
    const getselBan2 = "&selBan2="+selBan2.value;
    const getselBanNom2 = "&selBanNom2="+$("#selBan2 option:selected").text();
    const getNdepo2 = "&numNdepo2="+numNdepo2.value;
    const getVdepo2 = "&numVdepo2="+numVdepo2.value;

    const getTcam = "&numTcam="+numTcam.value;
    const getCon = "&txtCon="+txtCon.value;
    //const getDtGrabado = "&dtGrabado="+dtGrabado;
    const getTblPol = "&tblPol="+tblToJson(colPol, "tblPol", 0);
    const getTblDocp = "&tblDocp="+tblToJson(colDocp, "tblDocp", 0);

    var url = window.location.origin+window.location.pathname+"print.php"+getTabo+getNum+getTaboNom+getFec+getCodp+getCli+getnitcli+getcrTmone+getEfec+getVtarj+getNtarj+getVch+getselBan+getselBanNom+getNdepo+getVdepo+getselBan2+getselBanNom2+getNdepo2+getVdepo2+getTcam+getCon+getTblPol+getTblDocp;

    window.open(url, '_blank');
  }

  function limpiarModalPol(){
    txtCta.value = "";
    txtCtaNom.value = "";
    numDebe.value = "";
    numHaber.value = "";
  }

  function limpiar(todo = false){
    dtFec.value= '<?php echo $dtFec; ?>';    
    dtFdepo.value= '<?php echo $dtFec; ?>';    
    dtFdepo2.value= '<?php echo $dtFec; ?>';    
    numTcam.value = (1).toFixed(6);
    numEfec.value = (0).toFixed(2);
    txtNtarj.value = "";
    numVtarj.value = (0).toFixed(2);
    numNdepo.value = "";
    numVdepo.value = (0).toFixed(2);
    numNdepo2.value = "";
    numVdepo2.value = (0).toFixed(2);
    txtCon.value = "";
    crTmone.value = 'L';
    txtCodp.value = "";
    txtCli.value = "";
  }

  function limpiarModalDocp(){
      txtDserie.value = "";
      numDnum.value = "";
      txtDcod.value = "";
      txtDcli.value = "";
      numDabono.value = "";
  }

  function sumPol(){
    $("#tblPol #dataTotDebe").text(tblSumCol("tblPol", "dataDebe").toFixed(2));
    $("#tblPol #dataTotHaber").text(tblSumCol("tblPol", "dataHaber").toFixed(2));
  }


  $(document).ready(function() {
    $(this).find('select:visible:first').focus();
    document.thisform.dtFec.value = '<?php echo $dtFec; ?>';
    document.thisform.dtFdepo.value = '<?php echo $dtFec; ?>';
    document.thisform.dtFdepo2.value = '<?php echo $dtFec; ?>';

    selTabo.value = "030";
    numTcam.value = "1.000000";
    crTmone.value ="L";

    //dtFec.value = dateToday();

    // SHOW MODAL
    $('#modalPol, #modalDocp', '#modalLisDocp').on('shown.bs.modal', function() {
      if (!isMobile()) {
        $(this).find('input:visible:first').focus();
      }
    });

    // SUBMIT FORM
    $('form').submit(function() {
      return false;
    });

    // FOCUS NUMERO DE CHEQUE
    $("#numNum").focus(function() {

      limpiar();
      tblClear("tblPol");
      sumPol();
      tblClear("tblDocp");
      sumCaja();

      const parametros = new FormData();
      parametros.append("action", "consultarCorr");

      parametros.append("numNum", numNum.value);
      parametros.append("selTabo", selTabo.value);

      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        async: false,
        success: function (jsonPhp) {
          console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);
            if (isNullPer(jsonJS.tipoaboc)) {
            } else {
              partsn = jsonJS.tipoaboc.ta_partsn;
            }
            if (isNullPer(jsonJS.corrtaboc)) {
              numNum.value = 1;
            } else {
              numNum.value = jsonJS.corrtaboc.ctab_corr;
            }
          }
      });
    });

    // VALID NUMERO
    $("#numNum")
    .blur(function (){
      setTimeout(function(){
        if (!$('#selTabo').is(':focus') && $("#tblDocp tbody").children().length == 0) {
          consultarDocabo();
        }
      },0);
    })
    .change(function (){
      consultarDocabo();
    });

    // VALID FECHAS
    $("#dtFec")
    .blur(function (){
      if (restriccionCamposVacios()) {return};
        txtThis = dtFec;

        const parametros = new FormData();
        parametros.append("action", "mCerrado");
        parametros.append("dtFec", txtThis.value);

        $.ajax({
          data:  parametros,
          url:   window.location.origin+window.location.pathname+"actions.php",
          type:  "post",
          contentType: false,
          processData: false,
          async: false,
          success: function (jsonPhp) {
            const jsonJS = JSON.parse(jsonPhp);

            if(jsonJS.error == true){
              alError(jsonJS);
            } else {
              if (jsonJS.ciemes === null) {
                mesCerrado = false;
              } else {
                if (jsonJS.ciemes.ciem_stat == "C") {
                  mesCerrado = true;
                  setTimeout(function(){
                    if (!$('#numNum').is(':focus')) {
                      if ($('input, textarea').is(':focus')) {
                        restriccionMesCerrado();
                      }
                    }
                  },0);
                } else {
                  mesCerrado = false;
                }
              }
            }
          }
        });
    }); 

    // VALID CODIGO
    $("#txtCodp")
    .focus(function() {
      inputClien = $(this).attr('id');
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-1-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      const parametros = new FormData();
      parametros.append("action", "consultarClien");
      parametros.append("txtCodp", txtCodp.value);

      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        success: function (jsonPhp) {
          //console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
            nuevoClien = true;
          } else {
            if (isNullPer(jsonJS.cliencc)) {
              nuevoClien = true;
              txtCodp.focus();
              txtCli.value = "";
              ctacli="XXXX";
              nitcli="XXXX";
              alWarning({"msg":{"title":"No Existe","text":"Este Cliente no existe, debe registrarlo"}});
               return true;
            } else {
              txtCli.value = jsonJS.cliencc.cli_nom;
              ctacli = jsonJS.cliencc.cli_cta;
              nitcli = jsonJS.cliencc.cli_nit;
              nuevoClien = false;
            }
          }
        }
      });
    });

    // FOCUS FECHA
    $("#dtFec").focus(function (){
      if (restriccionCamposVacios()) {return};
    });

    // FOCUS VALOR CHEQUE, BENEFICIARIO, CONCEPTO
    $("#numTcam, #txtCon").focus(function (){
      if (restriccionCamposVacios()) {return};
      if (isNullPer(txtCodp.value)) {
        txtCodp.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CODIGO DEL CLIENTE"}});
        return true;
      }
    });

    // VALID CUENTA
    $("#txtCta")
    .focus(function() {
      inputCtaMov = $(this).attr('id');
    })
    .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-01-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      txtGetValue = document.getElementById("txtCtaNom");
      txtNext = document.getElementById("numDebe");

      $(txtThis).off("blur");
      if (restriccionCta()) {return};

      const parametros = new FormData();
      parametros.append("action", "consultarCta");
      parametros.append("txtCod", txtThis.value);

      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        beforeSend: function () {
          alLoad("Consultando...")
        },
        success: function (jsonPhp) {
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (jsonJS.cuentas === null) {
              txtGetValue.value = "";
              alErrorFocusTimer({"msg":{"type":"error","title":"No existe","text":"La cuenta "+txtThis.value+" no ha sido registrada", "ok":"Aceptar", "timer":timeOutErrorSm}}, txtThis);
            } else {
              if (jsonJS.cuentas.cta_con != "N") {
                txtGetValue.value = "";
                alErrorFocusTimer({"msg":{"type":"error","title":"No puede usar esta cuenta","text":"La cuenta "+txtThis.value+" no es de movimiento, no la puede usar", "ok":"Aceptar", "timer":timeOutErrorSm}}, txtThis);
              } else {
                txtGetValue.value = jsonJS.cuentas.cta_nom;
                (pressEnter) ? alClose() : alCloseFocus(txtNext);
              }
            }
            pressEnter = false;
            blurOn(txtThis, txtGetValue);
          }
        }
      });
    });

    $("#btnBusdocp").click(function (){
      if (isNullPer(txtCodp.value)) {
        txtCodp.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CODIGO DEL CLIENTE"}});
        return true;
      }
      if (crTmone.value=="E" && numTcam.value<1.01) {
        numTcam.focus();
        alWarning({"msg":{"title":"Tasa de Cambio","text":"Si la transaccion sera con moneda extranjera, debe definir una tasa de cambio"}});
        return true;
      }

      txtDcodlis.value = txtCodp.value;
      txtDclilis.value =  txtCli.value;
      tblClear("tblDocpLis");

      const parametros = new FormData();
      parametros.append("action", "consultarLisDocp");
      parametros.append("txtCod", txtCodp.value);

      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        success: function (jsonPhp) {
          //console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            jsonJS.doctoscc.forEach(function(i,index){
              if (crTmone.value=="L" && i.dc_tcam>1.00000) {
                temtcam=(1.000000).toFixed(6);
                temsal=(round(i.dc_sal*i.dc_tcam,2)).toFixed(2);
                addRowDocpLis(i.dc_tipo, i.dc_serie, i.dc_num, i.dc_fec, temtcam, temsal, i.dc_abop, index);
              }
              if (crTmone.value=="E" && i.dc_tcam<=1) {
                temsal=(round(i.dc_sal/numTcam.value,2)).toFixed(2);
                addRowDocpLis(i.dc_tipo, i.dc_serie, i.dc_num, i.dc_fec, numTcam.value, temsal, i.dc_abop, index);
              }
              if ((crTmone.value=="E" && i.dc_tcam>1) || (crTmone.value=="L" && i.dc_tcam==1)) {
                addRowDocpLis(i.dc_tipo, i.dc_serie, i.dc_num, i.dc_fec, i.dc_tcam, i.dc_sal, i.dc_abop, index);
              }
            });
            sumCajaLis();
            $('#modalLisDocp').modal('toggle');
          }
        }
      });
    });


    $("#btnContiLisDocp").click(function (){
      var tipodl = "";
      var seriedl = "";
      var numdl = "";
      var fedl = "";
      var tcamdl = 0;
      var saldodl =0;
      var abonodl =0;

      $("#tblDocpLis").find('tbody tr').each(function (i,index) {

        tipodl = $(this).find("td:eq(0)").text();
        seriedl = $(this).find("td:eq(1)").text();
        numdl = $(this).find("td:eq(2)").text();
        fecdl = $(this).find("td:eq(3)").text();
        tcamdl = $(this).find("td:eq(4)").text();
        saldodl = $(this).find("td:eq(5)").text();
        abonodl = $(this).find("td:eq(6)").text();

        if ($(this).find('td input[name="cblis"]').is(":checked")){
          addRowDocp(tipodl, seriedl, numdl, fecdl, tcamdl, saldodl, abonodl);
        }

      });

      $('#modalLisDocp').modal('toggle');

      sumCaja();
    });


  // CHANGE CAJA
  $("body").on("change", "input[name=cb]", function (){
    sumCaja();
  });

  // CHANGE CAJA
  $("body").on("change", "input[name=cblis]", function (){
    sumCajaLis();
  });


    // CLICK BORRAR
    $("#btnBorrar").click(function (){
      const numDoc = numNum.value;
      const codp = txtCodp.value;

      const fnT = function(){

        const pIva = <?php echo $_SESSION["pIva"]; ?>;

        sumfpago=Number(numEfec.value)+Number(+numVtarj.value)+Number(numVch.value)+Number(numVdepo.value)+Number(numVdepo2.value);

        if (crTmone.value == 'E') {
          var Qefec = round(Number(numEfec.value)*Number(numTcam.value),2);
          var Qvtarj = round(Number(numVtarj.value)*Number(numTcam.value),2);
          var Qvch = round(Number(numVch.value)*Number(numTcam.value),2);
        } else {
          var Qefec = Number(numEfec.value);
          var Qvtarj = Number(numVtarj.value);
          var Qvch = Number(numVch.value);
        } 
        var Qsub = Qefec;
        var Qiva = 0;
        if ($('#selTabo').find('option:selected').data('afe') == "S") {
          Qsub/=((pIva/100)+1);
          Qiva = (Qefec-Qsub);
        }

        colDocp = ["acciones","tipo", "serie", "numero", "fecha", "tcam", "saldo", "abono"];

        colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

        const parametros = new FormData();
        parametros.append("action", "borrar");
        parametros.append("selTabo", selTabo.value);
        parametros.append("numNum", numDoc);
        parametros.append("txtCodp", codp);
        parametros.append("dtFec", dtFec.value);
        parametros.append("txtCli", txtCli.value);
        parametros.append("nitcli", nitcli);
        parametros.append("ctacli", ctacli);
        parametros.append("numTcam", numTcam.value);
        parametros.append("crTmone", crTmone.value);
        parametros.append("numTcama", numTcama);
        parametros.append("crTmonea", crTmonea);
        parametros.append("txtCon", txtCon.value);
        parametros.append("numEfec", numEfec.value);
        parametros.append("txtNtarj", txtNtarj.value);
        parametros.append("numVtarj", numVtarj.value);
        parametros.append("numNch", numNch.value);
        parametros.append("txtBanch", txtBanch.value);
        parametros.append("numVch", numVch.value);
        parametros.append("selBan", selBan.value);
        parametros.append("BanCtac", $('#selBan').find('option:selected').data('ctac'));
        parametros.append("numNdepo", numNdepo.value);
        parametros.append("dtFdepo", dtFdepo.value);
        parametros.append("numVdepo", numVdepo.value);
        parametros.append("selBan2", selBan2.value);
        parametros.append("Ban2Ctac", $('#selBan2').find('option:selected').data('ctac'));
        parametros.append("numNdepo2", numNdepo2.value);
        parametros.append("dtFdepo2", dtFdepo2.value);
        parametros.append("numVdepo2", numVdepo2.value);
        parametros.append("selBanant", selBanant);
        parametros.append("numNdepoant", numNdepoant);
        parametros.append("numVdepoant", numVdepoant);
        parametros.append("selBan2ant", selBan2ant);
        parametros.append("numNdepo2ant", numNdepo2ant);
        parametros.append("numVdepo2ant", numVdepo2ant);
        parametros.append("Qefec", Qefec);
        parametros.append("Qvtarj", Qvtarj);
        parametros.append("Qvch", Qvch);
        parametros.append("Qsub", Qsub);
        parametros.append("Qiva", Qiva);
        parametros.append("taafe", $('#selTabo').find('option:selected').data('afe'));
        parametros.append("tatrela", $('#selTabo').find('option:selected').data('trela'));
        parametros.append("partsn", $('#selTabo').find('option:selected').data('partsn'));
        parametros.append("tblPol", tblToJson(colPol, "tblPol", 0));
        parametros.append("tblPolAnt", tblPolAnt);
        parametros.append("tblDocp", tblToJson(colDocp, "tblDocp", 0));
        parametros.append("tblDocpAnt", tblDocpAnt);

        numNum.focus();

        $.ajax({
          data:  parametros,
          url:   window.location.origin+window.location.pathname+"actions.php",
          type:  "post",
          contentType: false,
          processData: false,
          beforeSend: function () {
            alLoad("Cargando...")
          },
          success: function (jsonPhp) {
            console.log(jsonPhp);
            const jsonJS = JSON.parse(jsonPhp);

            if(jsonJS.error==true){
              alError(jsonJS);
            } else {
              numNum.value = "";
              limpiar();
              tblClear("tblPol");
              sumPol();
              tblClear("tblDocp");
              sumCaja();
              tblClear("tblDocpLis");
              sumCajaLis();
              alSuccess(jsonJS);
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

    // CLICK ANULAR
    $("#btnAnular").click(function (){
      const numDoc = numNum.value;
      const codp = txtCodp.value;

      const fnT = function(){

        const pIva = <?php echo $_SESSION["pIva"]; ?>;

        sumfpago=Number(numEfec.value)+Number(+numVtarj.value)+Number(numVch.value)+Number(numVdepo.value)+Number(numVdepo2.value);

        if (crTmone.value == 'E') {
          var Qefec = round(Number(numEfec.value)*Number(numTcam.value),2);
          var Qvtarj = round(Number(numVtarj.value)*Number(numTcam.value),2);
          var Qvch = round(Number(numVch.value)*Number(numTcam.value),2);
        } else {
          var Qefec = Number(numEfec.value);
          var Qvtarj = Number(numVtarj.value);
          var Qvch = Number(numVch.value);
        } 
        var Qsub = Qefec;
        var Qiva = 0;
        if ($('#selTabo').find('option:selected').data('afe') == "S") {
          Qsub/=((pIva/100)+1);
          Qiva = (Qefec-Qsub);
        }
        
        colDocp = ["acciones","tipo", "serie", "numero", "fecha", "tcam", "saldo", "abono"];

        colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

        const parametros = new FormData();
        parametros.append("action", "anular");
        parametros.append("selTabo", selTabo.value);
        parametros.append("numNum", numDoc);
        parametros.append("txtCodp", codp);
        parametros.append("dtFec", dtFec.value);
        parametros.append("txtCli", txtCli.value);
        parametros.append("nitcli", nitcli);
        parametros.append("ctacli", ctacli);
        parametros.append("numTcam", numTcam.value);
        parametros.append("crTmone", crTmone.value);
        parametros.append("numTcama", numTcama);
        parametros.append("crTmonea", crTmonea);
        parametros.append("txtCon", txtCon.value);
        parametros.append("numEfec", numEfec.value);
        parametros.append("txtNtarj", txtNtarj.value);
        parametros.append("numVtarj", numVtarj.value);
        parametros.append("numNch", numNch.value);
        parametros.append("txtBanch", txtBanch.value);
        parametros.append("numVch", numVch.value);
        parametros.append("selBan", selBan.value);
        parametros.append("BanCtac", $('#selBan').find('option:selected').data('ctac'));
        parametros.append("numNdepo", numNdepo.value);
        parametros.append("dtFdepo", dtFdepo.value);
        parametros.append("numVdepo", numVdepo.value);
        parametros.append("selBan2", selBan2.value);
        parametros.append("Ban2Ctac", $('#selBan2').find('option:selected').data('ctac'));
        parametros.append("numNdepo2", numNdepo2.value);
        parametros.append("dtFdepo2", dtFdepo2.value);
        parametros.append("numVdepo2", numVdepo2.value);
        parametros.append("selBanant", selBanant);
        parametros.append("numNdepoant", numNdepoant);
        parametros.append("numVdepoant", numVdepoant);
        parametros.append("selBan2ant", selBan2ant);
        parametros.append("numNdepo2ant", numNdepo2ant);
        parametros.append("numVdepo2ant", numVdepo2ant);
        parametros.append("Qefec", Qefec);
        parametros.append("Qvtarj", Qvtarj);
        parametros.append("Qvch", Qvch);
        parametros.append("Qsub", Qsub);
        parametros.append("Qiva", Qiva);
        parametros.append("taafe", $('#selTabo').find('option:selected').data('afe'));
        parametros.append("tatrela", $('#selTabo').find('option:selected').data('trela'));
        parametros.append("partsn", $('#selTabo').find('option:selected').data('partsn'));
        parametros.append("tblPol", tblToJson(colPol, "tblPol", 0));
        parametros.append("tblPolAnt", tblPolAnt);
        parametros.append("tblDocp", tblToJson(colDocp, "tblDocp", 0));
        parametros.append("tblDocpAnt", tblDocpAnt);

        numNum.focus();

        $.ajax({
          data:  parametros,
          url:   window.location.origin+window.location.pathname+"actions.php",
          type:  "post",
          contentType: false,
          processData: false,
          beforeSend: function () {
            alLoad("Cargando...")
          },
          success: function (jsonPhp) {
            //console.log(jsonPhp);
            const jsonJS = JSON.parse(jsonPhp);

            if(jsonJS.error==true){
              alError(jsonJS);
            } else {
              numNum.value = "";
              limpiar();
              tblClear("tblPol");
              sumPol();
              tblClear("tblDocp");
              sumCaja();
              tblClear("tblDocpLis");
              sumCajaLis();
              alSuccess(jsonJS);
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

    // CLICK GUARDAR
    $("#btnGuardar").click(function (){
      if (restriccionCamposVacios()) {return};
      if (condicionesobligatorias()) {return};
      if ($("#tblDocp tbody").children().length == 0) {
        alWarning({"msg":{"title":"NO HA REGISTRADO DOCUMENTOS","text":"Primero debe registrar documentos que va a abonar."}});
        return;
      }
      sumfpago=Number(numEfec.value)+Number(+numVtarj.value)+Number(numVch.value)+Number(numVdepo.value)+Number(numVdepo2.value);
      if (sumfpago!=$("#tblDocp #dataTotAbo").text()) { 
        alWarning({"msg":{"title":"SUMAS NO CUADRAN","text":"La suma de los abonos, no cuadra con la sumatoria de la forma de pago, revise."}});
        return;
      }
      var Qtot = round((sumfpago*numTcam.value),2)
      if (Number($("#dataTotDebe").text()) != Qtot && partsn == 'S' && numEfec.value!=0 && numVtarj.value!=0 && numVch.value!=0) {
        alWarning({"msg":{"title":"VALORES INCORRECTOS","text":"La partida no cuadra con la suma DE LOS ABONOS, verifique los valores"}});
        return true;
      }
      guardarDocp();
    });

    // CLICK GRABAR E IMPRIMIR
    $("#btnGuardarImprimir").click(function (){
      if (restriccionCamposVacios()) {return};
      if (condicionesobligatorias()) {return};
      if ($("#tblDocp tbody").children().length == 0) {
        alWarning({"msg":{"title":"NO HA REGISTRADO DOCUMENTOS","text":"Primero debe registrar documentos que va a abonar."}});
        return;
      }
      guardarDocp(true);
    });
    
    // CLICK AGREGAR
    $("#btnAgregar").click(function () {
      if (restriccionModal()) {return};
      addRowPol(txtCta.value, txtCtaNom.value, isNullNumber(numDebe.value).toFixed(2), isNullNumber(numHaber.value).toFixed(2));
      limpiarModalPol();
      sumPol();
      $("#btnAdd").focus();
    });
  });

  // CLICK ADD
  $("body").on("click", "#btnAdd", function () {
    if (restriccionCamposVacios()) {return};
    if (restriccionMesCerrado()) {return};
    if (condicionesobligatorias()) {return};
    if ($("#tblDocp tbody").children().length == 0) {
      alWarning({"msg":{"title":"NO HA REGISTRADO DOCUMENTOS","text":"Primero debe registrar documentos que va a abonar."}});
      return;
    }

    $('#modalPol').modal('toggle');
    $("#pills-00-tab").text("Agregar");
    $("#btnAgregar").show();
    $("#btnModificar").hide();
    limpiarModalPol();
  });

  // CLICK DEL
  $("body").on("click", "#btnDel", function() {
    const row = $(this).parents("tr");
    alDelete(function fn(){
      row.remove();
      sumPol();
    });
  });

  // CLICK EDIT
  $("body").on("click", "#btnEdit", function() {
    $('#pills-00-tab').text("Modificar");
    $('#btnAgregar').hide();
    $('#btnModificar').show();

    const dataCta = $(this).parents("tr").find("#dataCta");
    const dataCtaNom = $(this).parents("tr").find("#dataCtaNom");
    const dataDebe = $(this).parents("tr").find("#dataDebe");
    const dataHaber = $(this).parents("tr").find("#dataHaber");

    txtCta.value = dataCta.text();
    txtCtaNom.value = dataCtaNom.text();
    numDebe.value = dataDebe.text();
    numHaber.value = dataHaber.text();

    $("body").on("click", "#btnModificar", function() {
      if (restriccionModal()) {return};
      dataCta.text(txtCta.value);
      dataCtaNom.text(txtCtaNom.value);
      dataDebe.text(isNullNumber(numDebe.value).toFixed(2));
      dataHaber.text(isNullNumber(numHaber.value).toFixed(2));
      limpiarModalPol();
      sumPol();
    });
  });

  // MODALPOL HIDDEN
  $('#modalPol').on('hidden.bs.modal', function (e) {
    $("body").off("click", "#btnModificar");
  });

  // CLICK DEL DOCP
  $("body").on("click", "#btnDelDocp", function() {
    const row = $(this).parents("tr");
    alDelete(function fn(){
      row.remove();
      sumCaja();
    });
  });

  // CLICK EDIT DOCP
  $("body").on("click", "#btnEditDocp", function() {
    $('#pills-006-tab').text("Modificar Abono");
    $('#btnModificarDocp').show();

    const dataabono = $(this).parents("tr").find("#dataabono");
    const datasaldo = $(this).parents("tr").find("#datasaldo");
    const dataseried = $(this).parents("tr").find("#dataseried");
    const datanumd = $(this).parents("tr").find("#datanumd");

    txtDserie.value = dataseried.text();
    numDnum.value = datanumd.text();
    txtDcod.value = txtCodp.value;
    txtDcli.value = txtCli.value;
    numDabono.value = dataabono.text();
    numDsaldo.value = datasaldo.text();

    $("body").on("click", "#btnModificarDocp", function() {
      if (restriccionModalDocp(datasaldo.text())) {return};
      dataabono.text(isNullNumber(numDabono.value).toFixed(2));
      limpiarModalDocp();
      sumCaja();
    });
  });

  // MODALPOL HIDDEN
  $('#modalDocp').on('hidden.bs.modal', function (e) {
    $("body").off("click", "#btnModificarDocp");
  });


    // CLICK btnPartida
    $("#btnPartida").click(function (){
      if (restriccionCamposVacios()) {return};
      if (restriccionMesCerrado()) {return};
      if (condicionesobligatorias()) {return};
      if ($("#tblPol tbody").children().length != 0) {
        alWarning({"msg":{"title":"Ya existe partida","text":"La partida de este documento ya existe"}});
        return;
      }
      if ($("#tblDocp tbody").children().length == 0) {
        alWarning({"msg":{"title":"NO HA REGISTRADO DOCUMENTOS","text":"Primero debe registrar documentos que va a abonar."}});
        return;
      }
      if ($('#selTabo').find('option:selected').data('partsn') != "S") { 
        alWarning({"msg":{"title":"NO NECESITA PARTIDA","text":"A este tipo de documento no debe generarle partida."}});
        return;
      }
      if (numEfec.value==0 && numVtarj.value==0 && numVch.value==0) { 
        alWarning({"msg":{"title":"NO NECESITA PARTIDA","text":"No ha ingresado valores para generar partida, los depositos y las transferencias no generan partida en esta opcion."}});
        return;
      }
      sumfpago=Number(numEfec.value)+Number(+numVtarj.value)+Number(numVch.value)+Number(numVdepo.value)+Number(numVdepo2.value);
      if (sumfpago!=$("#tblDocp #dataTotAbo").text()) { 
        alWarning({"msg":{"title":"SUMAS NO CUADRAN","text":"La suma de los abonos, no cuadra con la sumatoria de la forma de pago, revise."}});
        return;
      }


      const pIva = <?php echo $_SESSION["pIva"]; ?>;

      if (crTmone.value == 'E') {
        var Qefec = round(Number(numEfec.value)*Number(numTcam.value),2);
        var Qvtarj = round(Number(numVtarj.value)*Number(numTcam.value),2);
        var Qvch = round(Number(numVch.value)*Number(numTcam.value),2);
      } else {
        var Qefec = Number(numEfec.value);
        var Qvtarj = Number(numVtarj.value);
        var Qvch = Number(numVch.value);
      } 
      var Qsub = Qefec;
      var Qiva = 0;
      if ($('#selTabo').find('option:selected').data('afe') == "S") {
        Qsub/=((pIva/100)+1);
        Qiva = (Qefec-Qsub);
      }

      const parametros = new FormData();
      parametros.append("action", "generarPartida");
      parametros.append("ctacli", ctacli);
      parametros.append("Qiva", Qiva);

      $('#btnAddEdit').focus();

      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        beforeSend: function () {
          alLoad("Generando...")
        },
        success: function (jsonPhp) {
          //console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            // Cuenta IVA
            if (Qiva != 0) {
              if (!isNullPer(jsonJS.ctaIva)) {
                addRowPol(jsonJS.ctaIva.cta, jsonJS.ctaIva.cta_nom, (Qiva).toFixed(2), "0.00");
              } else {
                addRowPol("XXXXXXX", "Ingrese cuenta de IVA", (Qiva).toFixed(2), "0.00");
              }
            }
            // Cuenta Subtotal
            if ((Qsub) != 0) {
              if (selTabo.value=='095') {
                if (!isNullPer(jsonJS.ctaVen)) {
                  addRowPol(jsonJS.ctaVen.cta, jsonJS.ctaVen.cta_nom, (Qsub).toFixed(2), "0.00");
                } else {
                addRowPol("XXXXXXX", "Ingrese cuenta", (Qsub).toFixed(2), "0.00");
                }
              } else {
                if (!isNullPer(jsonJS.ctaCaja)) {
                  addRowPol(jsonJS.ctaCaja.cta, jsonJS.ctaCaja.cta_nom, (Qsub).toFixed(2), "0.00");
                } else {
                addRowPol("XXXXXXX", "Ingrese cuenta", (Qsub).toFixed(2), "0.00");
                }
              }
            }
            // Cuenta Tarjeta
            if ((Qvtarj) != 0) {
              addRowPol("XXXXXXX", "Ingrese cuenta a Tarjeta Credito", (Qvtarj).toFixed(2), "0.00");
            }
            // Cuenta Tarjeta
            if ((Qvch) != 0) {
              addRowPol("XXXXXXX", "Ingrese cuenta cheque recibido", (Qvch).toFixed(2), "0.00");
            }
            // Cuenta Clientes
            if (!isNullPer(jsonJS.ctaCli)) {
              addRowPol(jsonJS.ctaCli.cta, jsonJS.ctaCli.cta_nom, "0.00",(Qefec+Qvtarj+Qvch).toFixed(2));
            } else {
              addRowPol("XXXXXXX", "Ingrese la cuenta de Clientes", "0.00",(Qefec+Qvtarj+Qvch).toFixed(2));
            }
            sumPol();
            alClose();
          }
        }
      });
    });


  // FOCUS PILL
  $('a[data-toggle="pill"]').on('shown.bs.tab', function (e) {
    if (!isMobile()) {
      const target = e.target.attributes.href.value;
      const relatedTarget = e.relatedTarget.attributes.href.value;

      if (target != "#pills-0") {
        $(target+' input:visible:first').focus();
      } else if (target == "#pills-0" && isNullPer(numNum.value)) {
        numNum.focus();
      } else {
        (relatedTarget == "#pills-1") ? txtCodp.focus() : 0;
      }
      //$(target+' input:visible:first').focus();
    }
  });

</script>
