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

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

$empCod = $_SESSION['empCod'];

# QUERYS
$sTipoc = "SELECT * FROM tipoc";
$sMeses = "SELECT * FROM meses";
$sTipopol = "SELECT * FROM tipopol";
$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'";
$sCiemes = "SELECT ciem_stat FROM ciemes WHERE ciem_emp='$empCod' AND ciem_ano=$nAnio AND ciem_mes=$nMes";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["tipoc"] = $db->query($sTipoc);
$select["meses"] = $db->query($sMeses);
$select["tipopol"] = $db->query($sTipopol);
$select["bancos"] = $db->query($sBancos);
$select["bancos2"] = $db->query($sBancos);
$select["bancos3"] = $db->query($sBancos);
$mesCerrado = ($db->sFetchAssoc($sCiemes)["ciem_stat"] == "C") ? "true" : "false";
$db->close();
$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 DEPOSITO -->
      <div class="modal fade" id="modalDepo" tabindex="-1" role="dialog" aria-labelledby="modalDepoTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl" role="document">
          <div class="modal-content bg-dark">
            <div class="modal-header">
              <ul class="nav nav-pills mb-1" 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">Registrar Deposito</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-00" role="tabpanel" aria-labelledby="pills-00-tab">

                  <form action="" name="thisformDepo" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-row">
                      <div class="col-12 col-lg-9 col-xl-10">
                        <div class="form-group">
                          <div class="form-row">
                            <div class="col-md-6">
                              <label for="selBan">Banco</label>
                              <select class="form-control form-control-sm form-control-as font-size-lg" 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-ctadif="'.$rec['ban_ctadif'].'" data-forma="'.$rec['ban_forma'].'">'.utf8_encode($rec['ban_nom']).'</option>';
                                  }
                                ?>
                              </select>
                            </div>
                            <div class="col-md-4 col-12">
                              <label for="numNum">No. Deposito</label>
                              <input type="number" class="form-control form-control-sm form-control-as font-size-lg" id="numNum" placeholder="0">
                            </div>
                          </div>

                          <div class="form-row align-items-end">
                            <div class="col-6 col-md-3">
                              <label for="dtFec">Fecha Deposito</label>
                              <input type="date" class="form-control form-control-sm form-control-as" id="dtFec" placeholder="">
                            </div>
                            <div class="col-6 col-md-3">
                              <label for="numTot">Valor del Deposito</label>
                              <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numTot" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0">
                            </div>
                            <div class="col-6 col-md-2">
                              <label for="numTcam">Tasa de Cambio</label>
                              <input type="number" class="form-control form-control-sm form-control-as" id="numTcam">
                            </div>
                          </div>
                          <div class="form-row">
                          </div>
                          <div class="form-row">
                            <div class="col-12">
                              <label for="txtCon">Concepto</label>
                              <textarea class="form-control form-control-sm form-control-as" id="txtCon" rows="2"></textarea>
                            </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>
                          <h3 class="text-light"></h3>
                          <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-lg-3 col-xl-2 text-left mt-5">
                        <div class="form-group position-fixed-lg w-lg-3 w-xl-2">
                          <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>
                          <div class="form-row">
                            <div class="col-12 mt-2">
                              <button class="btn btn-success btn-block" id="btnGuardar" type="button">Guardar</button>
                            </div>
                          </div>

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

                </div>

              </div>

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


      <!-- MODAL TRANSFERENCIA -->
      <div class="modal fade" id="modalMovi" tabindex="-1" role="dialog" aria-labelledby="modalMvTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl" role="document">
          <div class="modal-content bg-dark">
            <div class="modal-header">
              <ul class="nav nav-pills mb-1" id="pills-tab" role="tablist">
                <li class="nav-item">
                  <a class="nav-link active" id="pills-01-tab" data-toggle="pill" href="#pills-01" role="tab" aria-controls="pills-01" aria-selected="true">Grabar Transferencia</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-00" role="tabpanel" aria-labelledby="pills-00-tab">

                  <form action="" name="thisformMov" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-row">
                      <div class="col-12 col-lg-9 col-xl-10">
                        <div class="form-group">
                          <div class="form-row">
                            <div class="col-md-6">
                              <label for="selBant">Banco</label>
                              <select class="form-control form-control-sm form-control-as font-size-lg" name="selBant" id="selBant">
                                <?php
                                  while ($rec = $db->fetchAssoc($select['bancos3'])) {
                                    echo  '<option value="'.$rec['ban_num'].'" data-ctab="'.$rec['ban_ctab'].'" data-ctac="'.$rec['ban_ctac'].'" data-ctadif="'.$rec['ban_ctadif'].'" data-forma="'.$rec['ban_forma'].'">'.utf8_encode($rec['ban_nom']).'</option>';
                                  }
                                ?>
                              </select>
                            </div>
                            <div class="col-md-4 col-12">
                              <label for="numNumt">No. Transfrerencia</label>
                              <input type="number" class="form-control form-control-sm form-control-as font-size-lg" id="numNumt" placeholder="0">
                            </div>
                          </div>

                          <div class="form-row align-items-end">
                            <div class="col-6 col-md-3">
                              <label for="dtFect">Fecha Transferencia</label>
                              <input type="date" class="form-control form-control-sm form-control-as" id="dtFect" placeholder="">
                            </div>
                            <div class="col-6 col-md-3">
                              <label for="numTott">Valor de la Transferencia</label>
                              <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numTott" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0">
                            </div>
                            <div class="col-6 col-md-2">
                              <label for="numTcamt">Tasa de Cambio</label>
                              <input type="number" class="form-control form-control-sm form-control-as" id="numTcamt">
                            </div>
                          </div>
                          <div class="form-row">
                          </div>
                          <div class="form-row">
                            <div class="col-12">
                              <label for="txtCont">Concepto</label>
                              <textarea class="form-control form-control-sm form-control-as" id="txtCont" rows="2"></textarea>
                            </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="btnAddt">
                                <i class="fas fa-plus-circle"></i> Agregar
                              </button>
                            </div>
                            <div class="col-7 text-right">
                              <button class="btn btn-primary" id="btnPartidat" type="button"><i class="fas fa-poll-h"></i> Generar Partida</button>
                            </div>
                          </div>
                          <h3 class="text-light"></h3>
                          <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="tblPolt">
                                  <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="dataTotDebet" class="text-right">0.00</th>
                                    <th scope="col" id="dataTotHabert" 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-lg-3 col-xl-2 text-left mt-5">
                      <div class="form-group position-fixed-lg w-lg-3 w-xl-2">
                          <div class="form-row">
                            <div class="col-12 mt-2">
                              <button class="btn btn-info btn-block" id="btnGuardarImprimirt" type="button">Imprimir / Guardar</button>
                            </div>
                          </div>
                          <div class="form-row">
                            <div class="col-12 mt-2">
                              <button class="btn btn-success btn-block" id="btnGuardart" type="button">Guardar</button>
                            </div>
                          </div>

                        </div>
                      </div>
                    </div>
                  </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-000-tab" data-toggle="pill" href="#pills-000" role="tab" aria-controls="pills-000" aria-selected="true"></a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" id="pills-001-tab" data-toggle="pill" href="#pills-001" role="tab" aria-controls="pills-001" aria-selected="false">Buscar Cuentas</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-000" role="tabpanel" aria-labelledby="pills-000-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-001" role="tabpanel" aria-labelledby="pills-001-tab">
                  <?php
                    $a='000';
                    $b='001';
                    include('../busCuentasMov/index.html')
                  ?>
                </div>
              </div>

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

      <!-- MODAL POLIZA TRANSF-->
      <div class="modal fade" id="modalPolTr" tabindex="-1" role="dialog" aria-labelledby="modalPolTrTitle" 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-003-tab" data-toggle="pill" href="#pills-003" role="tab" aria-controls="pills-003" aria-selected="true"></a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" id="pills-004-tab" data-toggle="pill" href="#pills-004" role="tab" aria-controls="pills-004" aria-selected="false">Buscar Cuentas</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-003" role="tabpanel" aria-labelledby="pills-003-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="txtCtat">Cuenta</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtCtat" placeholder="">
                        </div>
                        <div class="col-md-8">
                          <label for="txtCtatNom">Nombre Cuenta</label>
                          <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtatNom" placeholder="" disabled>
                        </div>
                      </div>
                      <div class="form-row">
                        <div class="col-md-6">
                          <label for="numDebet">Debe</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numDebet" placeholder="0.00">
                        </div>
                        <div class="col-md-6">
                          <label for="numHabert">Haber</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numHabert" placeholder="0.00">
                        </div>
                      </div>
                    </div>

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

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

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

      <!-- 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" 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>
                <li class="nav-item">
                  <a class="nav-link" id="pills-008-tab" data-toggle="pill" href="#pills-008" role="tab" aria-controls="pills-008" aria-selected="true">Buscar Clientes</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"  maxlength="20">
                        </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="100">SERIE</th>
                                  <th scope="col" class="text-center" width="100">NÚMERO</th>
                                  <th scope="col" class="text-center" width="35">FEC/DOCTO.</th>
                                  <th scope="col" class="text-center" width="60">T/CAMBIO</th>
                                  <th scope="col" class="text-center" width="90">SALDO</th>
                                  <th scope="col" class="text-center" width="90">ABONO</th>
                                  <th scope="col" class="text-center" width="40">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 class="tab-pane fade" id="pills-008" role="tabpanel" aria-labelledby="pills-008-tab">
                  <?php
                    $a='007';
                    $b='008';
                    include('../busCliencc/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">Generar Deposito/Transferencias</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-12 col-sm-6 col-md-3">
                            <label>   </label>
                          </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> SELECCIONAR DOCUMENTOS
                            </button>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-12 col-sm-6 col-md-3">
                            <label>   </label>
                          </div>
                        </div>

                        <div class="form-row">
                          <div class="col-12 text-right mb-2">
                            <div class="custom-control custom-checkbox">
                              <input type="checkbox" class="custom-control-input" id="cbTodos" name="cb">
                              <label class="custom-control-label mt-0" for="cbTodos">Seleccionar Todos</label>
                            </div>
                          </div>
                          <div class="col-md-12">
                            <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="80">CLIENTE</th>
                                    <th scope="col" class="text-center" width="80">SERIE</th>
                                    <th scope="col" class="text-center" width="80">NÚMERO</th>
                                    <th scope="col" class="text-center" width="35">FEC/DOCTO.</th>
                                    <th scope="col" class="text-center" width="200">CONCEPTO</th>
                                    <th scope="col" class="text-center" width="80">SALDO</th>
                                    <th scope="col" class="text-center" width="80">ABONO</th>
                                    <th scope="col" class="text-center" width="30">INCLUIR</th>
                                  </tr>
                                </thead>
                                <tbody>
                                </tbody>
                                <tfoot>
                                  <th scope="col"></th>
                                  <th scope="col"></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>
                    </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-danger btn-block" id="btnEmitirDepo" type="button">Registrar Deposito</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-primary btn-block" id="btnGrabarTrasfer" type="button">Grabar Transferencia</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-success btn-md btn-block" id="btnListado" type="button">Imprime Listado</button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </form>

              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var totant = 0;
  var nuevoClien = true;
  var tblDocpAnt;
  var tblPolAnt;
  var rfecAnt = "0000-00-00";
  var mesCerrado = false;
  var btnAddEdit = "00";
  var inputCtaMov = "txtCta";
  var inputClien = "txtNit"
  var inputDepo = "numNum";
  var lcont = 0;

  const numNum = document.thisformDepo.numNum;
  const selBan = document.thisformDepo.selBan;
  const dtFec = document.thisformDepo.dtFec;
  const numTot = document.thisformDepo.numTot;
  const numTcam = document.thisformDepo.numTcam;
  const txtCon = document.thisformDepo.txtCon;

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

  const numNumt = document.thisformMov.numNumt;
  const selBant = document.thisformMov.selBant;
  const dtFect = document.thisformMov.dtFect;
  const numTott = document.thisformMov.numTott;
  const numTcamt = document.thisformMov.numTcamt;
  const txtCont = document.thisformMov.txtCont;

  const txtCtat = document.getElementById("txtCtat");
  const txtCtatNom = document.getElementById("txtCtatNom");
  const numDebet = document.getElementById("numDebet");
  const numHabert = document.getElementById("numHabert");

  function addRowDocp(codpd, cliend, ctad, tipod, seried, numd, fecd, tcamd, concep, saldo, abono,l){
    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-primary btn-sm btn-actions' id='btnEditDocp' data-toggle='modal' data-target='#modalDocp'><i class='fas fa-edit'></i></button>"
                  +"</div>"
                +"</td>"
                  +"<td id='datacodpd' class='text-left'>"+codpd+"</td>"
                  +"<td id='datacliend' class='text-left d-none'>"+cliend+"</td>"
                  +"<td id='datactad' class='text-left d-none'>"+ctad+"</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' class='text-center'>"+fecd+"</td>"
                  +"<td id='datatcamd' class='text-right d-none'>"+tcamd+"</td>"
                  +"<td id='dataconcep' class='text-left'>"+concep+"</td>"
                  +"<td id='datasaldo' class='text-right'>"+saldo+"</td>"
                  +"<td id='dataabono' class='text-right'>"+abono+"</td>"
                  +"<td class='text-center'>"
                    +"<div class='custom-control custom-checkbox'>"
                    +"<input type='checkbox' class='custom-control-input' id='dataCheckdocp"+l+"' name='cb' checked>"
                    +"<label class='custom-control-label mt-0' for='dataCheckdocp"+l+"'></label>"
                    +"</div>"
                  +"</td>"
                +"</tr>";
    $("#tblDocp tbody").append(row);
  }

  sumCaja();

  function addRowDocpLis(codpdlis, cliendlis, ctalis, tipodlis, seriedlis, numdlis, fecdlis, tcamlis, condlis, saldolis, abonolis,l){
    const row = "<tr>"
                  +"<td id='datacodpdlis' class='text-left d-none'>"+codpdlis+"</td>"
                  +"<td id='datacliendlis' class='text-left d-none'>"+cliendlis+"</td>"
                  +"<td id='datactalis' class='text-left d-none'>"+ctalis+"</td>"
                  +"<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' class='text-center'>"+YMDToDMY(fecdlis)+"</td>"
                  +"<td id='datatcamlis' class='text-right'>"+tcamlis+"</td>"
                  +"<td id='datacondlis' class='text-left d-none'>"+condlis+"</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);
  }

  sumCaja();

  sumCajaLis();

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

    $("#tblDocp").find('tbody tr').each(function () {
      if ($(this).find('td input[name="cb"]').is(":checked")){
        if (parseFloat($(this).find('#dataabono').text()) == "0.00") {
           $(this).find('#dataabono').text($(this).find('#datasaldo').text());
        }
        acuma += parseFloat($(this).find('#dataabono').text());
      } else {
        $(this).find('#dataabono').text("0.00");
      } 
      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));
  }

    $("#btnEmitirDepo").click(function (){
      var tdvacia = true;
      var concepas="";
      var tlinea=0;
      $("#tblDocp tbody tr").each(function(){
        if ($(this).find('td input[name="cb"]').is(":checked")){
           tdvacia = false;
           if (tlinea==0) {
            concepas=concepas+$(this).find('#datanumd').text();
            tlinea=1;
          } else {
            concepas=concepas+", "+$(this).find('#datanumd').text();
          }
        }
      });
      if (tdvacia) {
        alWarning({"msg":{"title":"Falta Seleccionar","text":"Aun no ha seleccionado ningun documento para abonar."}});
        return true;
      }

      numTot.value =  $("#tblDocp #dataTotAbo").text();
      txtCon.value = "Documentos Abonados con este Deposito: "+concepas;
      //+txtClien.value;
      $('#modalDepo').modal('toggle');
    });

    $("#btnGrabarTrasfer").click(function (){
      var tdvacia = true;
      var concepas="";
      var tlinea=0;
      $("#tblDocp tbody tr").each(function(){
        if ($(this).find('td input[name="cb"]').is(":checked")){
           tdvacia = false;
           if (tlinea==0) {
            concepas=concepas+$(this).find('#datanumd').text();
            tlinea=1;
          } else {
            concepas=concepas+", "+$(this).find('#datanumd').text();
          }
        }
      });
      if (tdvacia) {
        alWarning({"msg":{"title":"Falta Seleccionar","text":"Aun no ha seleccionado ningun documento para abonar."}});
        return true;
      }
      numTott.value =  $("#tblDocp #dataTotAbo").text();
      txtCont.value = "Documentos Abonados con esta Transferencia: "+concepas;
      //+txtClien.value;
      $('#modalMovi').modal('toggle');
    });

    $("#btnListado").click(function (){

      colDocp = ["acciones", "codp", "clienp", "ctap", "tipo", "serie", "numero", "fecha", "tipocam", "concep", "saldo", "abono", "check"];

      const getTblDocp = "?tblDocp="+tblToJsonCbSkip(colDocp, "tblDocp", 0, 12);
       
      var url = window.location.origin+window.location.pathname+"print.php"+getTblDocp;

      window.open(url, '_blank');

    });

    // VALID CODIGO
    $("#txtDcodlis")
    .focus(function() {
      txtDcodlis.value = "";
      txtDclilis.value = "";
      tblClear("tblDocpLis");
      sumCajaLis();

      inputClien = $(this).attr('id');
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-008-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      const parametros = new FormData();
      parametros.append("action", "consultarClien");
      parametros.append("txtCodp", txtDcodlis.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 (jsonJS.cliencc === null) {
              nuevoClien = true;
              txtDcodlis.focus();
              txtDclilis.value = "";
              ctacli="XXXX";
              nitcli="XXXX";
              alWarning({"msg":{"title":"No Existe","text":"Este Cliente no existe, debe registrarlo"}});
               return true;
            } else {
              txtDclilis.value = jsonJS.cliencc.cli_nom;
              ctacli = jsonJS.cliencc.cli_cta;
              nitcli = jsonJS.cliencc.cli_nit;

              jsonJS.doctoscc.forEach(function(i,index){
                addRowDocpLis(i.dc_codp, i.dc_clien, i.cli_cta, i.dc_tipo, i.dc_serie, i.dc_num, i.dc_fec, i.dc_tcam, i.dc_con, i.dc_sal, i.dc_abop,index);
              });  
              sumCajaLis();
              nuevoClien = false;
            }
          }
        }
      });
    });


  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(selBan.value)) {
        selBan.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Banco"}});
        return true;
      }
      if (isNullPer(numNum.value)  || numNum.value == 0) {
        numNum.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE DEPOSITO"}});
        return true;
      }
      if ($("#dataTotDebe").text() != $("#dataTotHaber").text()) {
        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) {
        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;
      $("#tblPol tbody tr").each(function(){
        if ($(this).find("td:eq(1)").text().includes('XXXX')) { ctaInc = true }
        if ($(this).find("td:eq(1)").text() == $('#selBan').find('option:selected').data('ctac').toString()) {
          ctaIncBan = false;
          if ($(this).find("td:eq(3)").text() != numTot.value) {
            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 Acreditar en la cuenta de banco NO COINCIDE CON EL VALOR DEL DEPOSITO, verifique."}});
        return true;
      }
    } else {
      if (isNullPer(selBan.value) || isNullPer(numNum.value)) {
        return true;
      }
    }
    return false;
  }

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

  function restriccionTr(consultar = false){
    if (!consultar) {
      if (isNullPer(selBant.value)) {
        selBant.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Banco"}});
        return true;
      }
      if (isNullPer(numNumt.value)  || numNumt.value == 0) {
        numNumt.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE TRANSFERENCIA"}});
        return true;
      }
      if ($("#dataTotDebet").text() != $("#dataTotHabert").text()) {
        alWarning({"msg":{"title":"Valores Incorrectos","text":"La partida no cuadra, verifique los valores"}});
        return true;
      }
      // PARA VER SI LA PARTIDA ESTÁ VACÍA
      if ($("#tblPolt tbody").children().length == 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;
      $("#tblPolt tbody tr").each(function(){
        if ($(this).find("td:eq(1)").text().includes('XXXX')) { ctaInc = true }
        if ($(this).find("td:eq(1)").text() == $('#selBant').find('option:selected').data('ctac').toString()) {
          ctaIncBan = false;
          if ($(this).find("td:eq(3)").text() != numTott.value) {
            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 Acreditar en la cuenta de banco NO COINCIDE CON EL VALOR DE LA TRANSFERENCIA, verifique."}});
        return true;
      }
    } else {
      if (isNullPer(selBant.value) || isNullPer(numNumt.value)) {
        return true;
      }
    }
    return false;
  }

  function restriccionCamposVaciosTr() {
    if (isNullPer(selBant.value)) {
      selBant.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el BANCO"}});
      return true;
    }
    if (isNullPer(numNumt.value)) {
      numNumt.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE TRANSFERENCIA"}});
      return true;
    }
    return false;
  }

  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 restriccionCtaTr() {
    if (isNullPer(txtCtat.value)) {
      txtCtatNom.value = "";
      return true;
    }
    return false;
  }

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

  function restriccionCtaCodTr() {
    if (isNullPer($("#"+inputCtaMov+"t").val())) {
      $("#"+inputCtaMov+"Nomt").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 restriccionModalTr() {
    if (restriccionCtaTr()) {
      txtCtat.focus();
      alWarningTimer({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar la CUENTA","timer":timeOutWarningSm}});
      return true;
    }
    $('#modalPolTr').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' contenteditable='true'>"+debe+"</td>"
                +"<td id='dataHaber' class='text-right' contenteditable='true'>"+haber+"</td>"
                +"</tr>";
    $("#tblPol tbody").append(row);
  }

  function addRowPolTr(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='btnDelt'><i class='fas fa-trash-alt'></i></button>"
                    +"<button type='button' class='btn btn-primary btn-sm btn-actions' id='btnEditt' data-toggle='modal' data-target='#modalPolTr'><i class='fas fa-edit'></i></button>"
                  +"</div>"
                +"</td>"
                +"<td id='dataCtat'>"+cta+"</td>"
                +"<td id='dataCtatNom'>"+ctaNom+"</td>"
                +"<td id='dataDebet' class='text-right' contenteditable='true'>"+debe+"</td>"
                +"<td id='dataHabert' class='text-right' contenteditable='true'>"+haber+"</td>"
                +"</tr>";
    $("#tblPolt tbody").append(row);
  }

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

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

    parametros.append("numNum", numNum.value);
    parametros.append("selBanCod", selBan.value);

    //txtNext.focus()

    $.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);
        tblPolAnt = JSON.stringify(jsonJS.poli_det);

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

         
          if (jsonJS.movi === null) {
            nuevo = true;
            totant = 0;
          } else {
            dtFec.value = jsonJS.movi.mov_fec;
            numTot.value = jsonJS.movi.mov_tot;
            numTcam.value = jsonJS.movi.mov_tcam;
            txtCon.value = jsonJS.movi.mov_con;
            jsonJS.poli_det.forEach(function(i){
              addRowPol(i.pold_cta, i.pold_ctan, i.pold_debe, i.pold_haber);
            });
            sumPol();
            nuevo = false;
            totant = jsonJS.movi.mov_tot;
          }
          //(pressEnter) ? alClose() : alCloseFocus(txtNext);
          //pressEnter = false; 
          //alClose();
          //dtFec.focus();
        }
      }
    });
  }

  function consultarTransf(){
    if (restriccionTr(true)) {return};
    
    //txtNext = dtFec;

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

    parametros.append("numNum", numNumt.value);
    parametros.append("selBanCod", selBant.value);

    //txtNext.focus()

    $.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);
        tblPolAntTr = JSON.stringify(jsonJS.poli_det);

        if(jsonJS.error == true){
          alError(jsonJS);
        } else {
          limpiarTr();
          tblClear("tblPolt");
          sumPolTr();

         
          if (jsonJS.movi === null) {
            nuevo = true;
            totant = 0;
          } else {
            dtFect.value = jsonJS.movi.mov_fec;
            numTott.value = jsonJS.movi.mov_tot;
            numTcamt.value = jsonJS.movi.mov_tcam;
            txtCont.value = jsonJS.movi.mov_con;
            jsonJS.poli_det.forEach(function(i){
              addRowPolTr(i.pold_cta, i.pold_ctan, i.pold_debe, i.pold_haber);
            });
            sumPolTr();
            nuevo = false;
            totant = jsonJS.movi.mov_tot;
          }
          //(pressEnter) ? alClose() : alCloseFocus(txtNext);
          //pressEnter = false; 
          //alClose();
          //dtFec.focus();
        }
      }
    });
  }


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

    colDocp = ["acciones", "codp", "clienp", "ctap", "tipo", "serie", "numero", "fecha", "tipocam", "concep", "saldo", "abono", "check"];

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

    const parametros = new FormData();
    const numDoc = numNum.value;    
    parametros.append("action", "guardar");

    parametros.append("nuevo", nuevo);
    parametros.append("numNum", numNum.value);
    parametros.append("selBanCod", selBan.value);
    parametros.append("dtFec", dtFec.value);
    parametros.append("numTot", numTot.value);
    parametros.append("totant", totant);
    parametros.append("numTcam", numTcam.value);
    parametros.append("txtCon", txtCon.value);
    //parametros.append("txtCodp", txtCodp.value);
    //parametros.append("ctacli", ctacli);
    //parametros.append("nitcli", nitcli);
    parametros.append("tblPol", tblToJson(["acciones", "cta", "ctaNom", "debe", "haber"], "tblPol", 0));
    parametros.append("tblPolAnt", tblPolAnt);
    parametros.append("tblDocp", tblToJsonCbSkip(colDocp, "tblDocp", 0, 12));

    //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 {
          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) {
            if (imprimir) {
              imprimirPoliza(true, jsonJS.dtGrabado, numDoc);
            }
            tblClear("tblPol");
            sumPol();
            tblClear("tblDocp");
            //jsonJS.doctoscc.forEach(function(i, index){
            //  addRowDocp(i.dc_serie, i.dc_num, i.dc_fec, i.dc_tcam, i.dc_con, i.dc_sal, i.dc_abop, index);
            //});
            //tblAllChecked("tblCaja", "cb", "cbTodos");
            sumCaja();
            $('#modalDepo').modal('toggle');
            numNum.value = "";
            limpiar();
            tblClear("tblPol");
            sumPol();
            alSuccess(JSON.parse('{"msg":'+decode_utf8(JSON.stringify(jsonJS.msg))+"}"));
          }
        }
      } 
    });
  }

  function guardarPolizaTr(imprimir = false){
    if (restriccionTr()) {return};

    colDocp = ["acciones", "codp", "clienp", "ctap", "tipo", "serie", "numero", "fecha", "tipocam", "concep", "saldo", "abono", "check"];

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

    const parametros = new FormData();
    const numDoc = numNumt.value;    
    parametros.append("action", "guardarTr");

    parametros.append("nuevo", nuevo);
    parametros.append("numNum", numNumt.value);
    parametros.append("selBanCod", selBant.value);
    parametros.append("dtFec", dtFect.value);
    parametros.append("numTot", numTott.value);
    parametros.append("totant", totant);
    parametros.append("numTcam", numTcamt.value);
    parametros.append("txtCon", txtCont.value);
    //parametros.append("txtCodp", txtCodp.value);
    //parametros.append("ctacli", ctacli);
    //parametros.append("nitcli", nitcli);
    parametros.append("tblPol", tblToJson(["acciones", "cta", "ctaNom", "debe", "haber"], "tblPolt", 0));
    parametros.append("tblPolAnt", tblPolAntTr);
    parametros.append("tblDocp", tblToJsonCbSkip(colDocp, "tblDocp", 0, 12));

    //numNumt.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 {
          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) {
            if (imprimir) {
              imprimirPolizaTr(true, jsonJS.dtGrabado, numDoc);
            }
            tblClear("tblPolt");
            sumPolTr();
            tblClear("tblDocp");
            //jsonJS.doctoscc.forEach(function(i, index){
            //  addRowDocp(i.dc_serie, i.dc_num, i.dc_fec, i.dc_con, i.dc_sal, i.dc_abop,index);
            //});
            //tblAllChecked("tblCaja", "cb", "cbTodos");
            sumCaja();
            $('#modalMovi').modal('toggle');
            numNumt.value = "";
            limpiarTr();
            tblClear("tblPolt");
            sumPolTr();
            alSuccess(JSON.parse('{"msg":'+decode_utf8(JSON.stringify(jsonJS.msg))+"}"));
          }
        }
      } 
    });
  }

  function imprimirPoliza(guardar = true, dtGrabado = "", numDoc){
    //if (restriccion(false, false)) {return};
    tipop="002.01";
    colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

    const getBanCod = "?selBanCod="+selBan.value;
    const getBanNom = "&selBanNom="+$("#selBan option:selected").text();
    const getNum = "&numNum="+numDoc;
    const getFec = "&dtFec="+dtFec.value;
    const getTot = "&numTot="+numTot.value;
    const getTcam = "&numTcam="+numTcam.value;
    const getCon = "&txtCon="+txtCon.value;
    const getTipoCod = "&tipop="+tipop;
    //const getDtGrabado = "&dtGrabado="+dtGrabado;
    const getTblPol = "&tblPol="+tblToJson(colPol, "tblPol", 0);
    //const getBtn = (guardar) ? "&btn=Fecha y hora de Impresión y Grabado:" : "&btn=Fecha y hora de Impresión:";
    var url = window.location.origin+window.location.pathname+"printdoc.php"+getBanCod+getBanNom+getNum+getFec+getTot+getTcam+getCon+getTblPol+getTipoCod;

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

  function imprimirPolizaTr(guardar = true, dtGrabado = "", numDoc){
    //if (restriccion(false, false)) {return};
    tipop="003.01";    
    colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

    const getBanCod = "?selBanCodt="+selBant.value;
    const getBanNom = "&selBanNomt="+$("#selBant option:selected").text();
    const getNum = "&numNumt="+numDoc;
    const getFec = "&dtFect="+dtFect.value;
    const getTot = "&numTott="+numTott.value;
    const getTcam = "&numTcamt="+numTcamt.value;
    const getCon = "&txtCont="+txtCont.value;
    const getTipoCod = "&tipop="+tipop;
    //const getDtGrabado = "&dtGrabado="+dtGrabado;
    const getTblPol = "&tblPolt="+tblToJson(colPol, "tblPolt", 0);
    //const getBtn = (guardar) ? "&btn=Fecha y hora de Impresión y Grabado:" : "&btn=Fecha y hora de Impresión:";
    var url = window.location.origin+window.location.pathname+"printdoc.php"+getBanCod+getBanNom+getNum+getFec+getTot+getTcam+getCon+getTblPol+getTipoCod;

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

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

  function limpiarModalPolTr(){
    txtCtat.value = "";
    txtCtatNom.value = "";
    numDebet.value = "";
    numHabert.value = "";
  }

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

  function limpiar(todo = false){
    dtFec.value= dateToday();
    //numTcam.value = (1).toFixed(6);
    //cbNego.checked = 1;
    //numTot.value = (0).toFixed(2);
    //txtBene.value = "";
    //txtCon.value = "";
  }

  function limpiarTr(todo = false){
    dtFect.value= dateToday();
    //numTcamt.value = (1).toFixed(6);
    //txtCont.value = "";
  }

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

  function sumPolTr(){
    $("#tblPolt #dataTotDebet").text(tblSumCol("tblPolt", "dataDebet").toFixed(2));
    $("#tblPolt #dataTotHabert").text(tblSumCol("tblPolt", "dataHabert").toFixed(2));
  }

  $(document).ready(function() {
    //tblAllChecked("tblDocp", "cb", "cbTodos");
    $(this).find('button:visible:first').focus();
    document.thisformDepo.dtFec.value = '<?php echo $dtFec; ?>';
    selBan.value = 1;

    document.thisformMov.dtFect.value = '<?php echo $dtFec; ?>';
    selBant.value = 1;


    // SHOW MODAL
    $('#modalLisDocp').on('shown.bs.modal', function() {
      if (!isMobile()) {
        $(this).find('input:visible:first').focus();
      } else {
        limpiar();
        tblClear("tblDocpLis");
        sumCajaLis();
      }
    });

    // SHOW MODAL
    $('#modalDepo').on('shown.bs.modal', function() {
      if (!isMobile()) {
        $(this).find('select:visible:first').focus();
      } else {
        limpiar();
        tblClear("tblPol");
        sumPol();
      }
    });

    // SHOW MODAL TRANSF
    $('#modalMovi').on('shown.bs.modal', function() {
      if (!isMobile()) {
        $(this).find('select:visible:first').focus();
      } else {
        limpiarTr();
        tblClear("tblPolt");
        sumPolTr();
      }
    });

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

    // FOCUS NUMERO DE DEPOSITO
    $("#selBan").focus(function() {
      limpiar();
      tblClear("tblPol");
      sumPol();
    });

    // FOCUS NUMERO DE TRANSFERENCIA
    $("#selBant").focus(function() {
      limpiarTr();
      tblClear("tblPolt");
      sumPolTr();
    });

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

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

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

      parametros.append("numNum", numNum.value);
      parametros.append("selBanCod", selBan.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.bancos === null) {
            } else {
              if (jsonJS.bancos.ban_mon == 1) {
                numTcam.value = (1).toFixed(6);
                numTcam.disabled = true;
              } else {
                numTcam.value = '<?php echo $_SESSION["empTasa"] ?>';
                numTcam.disabled = false;
              }
            }
          }
      });
    });

    // FOCUS NUMERO DE TRANSFERENCIA
    $("#numNumt").focus(function() {
      numNumt.value="";
      limpiarTr();
      tblClear("tblPolt");
      sumPolTr();

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

      parametros.append("numNum", numNumt.value);
      parametros.append("selBanCod", selBant.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.bancos === null) {
            } else {
              if (jsonJS.bancos.ban_mon == 1) {
                numTcamt.value = (1).toFixed(6);
                numTcamt.disabled = true;
              } else {
                numTcamt.value = '<?php echo $_SESSION["empTasa"] ?>';
                numTcamt.disabled = false;
              }
            }
          }
      });
    });


    // VALID NUMERO
    $("#numNum")
    .blur(function (){
      setTimeout(function(){
        if (!$('#selBan').is(':focus') && $("#tblPol tbody").children().length == 0) {
          consultarDepo();
        }
      },0);
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-2-tab").click(); }
    })
    .change(function (){
      consultarDepo();
    });

    // 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') && !$('#selBan').is(':focus')) {
                    if ($('input, textarea').is(':focus')) {
                      restriccionMesCerrado();
                    }
                  }
                },0);
              } else {
                mesCerrado = false;
              }
            }
          }
        }
      });
    });

    // VALID NUMERO
    $("#numNumt")
    .blur(function (){
      setTimeout(function(){
        if (!$('#selBant').is(':focus') && $("#tblPolt tbody").children().length == 0) {
          consultarTransf();
        }
      },0);
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-2-tab").click(); }
    })
    .change(function (){
      consultarTransf();
    });

    // VALID FECHAS TRANSF
    $("#dtFect")
    .blur(function (){
      if (restriccionCamposVaciosTr()) {return};
        txtThis = dtFect;

        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 (!$('#numNumt').is(':focus') && !$('#selBant').is(':focus')) {
                    if ($('input, textarea').is(':focus')) {
                      restriccionMesCerrado();
                    }
                  }
                },0);
              } else {
                mesCerrado = false;
              }
            }
          }
        }
      });
    });

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

    // FOCUS VALOR DEPOSITO, BENEFICIARIO, CONCEPTO
    $("#numTot, #txtCon").focus(function (){
      if (restriccionCamposVacios()) {return};
    });

    // FOCUS FECHA TRANSF
    $("#dtFect").focus(function (){
      if (restriccionCamposVaciosTr()) {return};
    });

    // FOCUS VALOR TRANSFERENCIA, CONCEPTO
    $("#numTott, #txtCont").focus(function (){
      if (restriccionCamposVaciosTr()) {return};
    });

    // 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-001-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);
          }
        }
      });
    });

    // VALID CUENTA
    $("#txtCtat")
    .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-004-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      txtGetValue = document.getElementById("txtCtatNom");
      txtNext = document.getElementById("numDebet");

      $(txtThis).off("blur");
      if (restriccionCtaTr()) {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);
          }
        }
      });
    });


    // CLICK GUARDAR
    $("#btnGuardar").click(function (){
      guardarPoliza();
    });

    // CLICK GUARDAR Trans
    $("#btnGuardart").click(function (){
      guardarPolizaTr();
    });

    // CLICK GRABAR E IMPRIMIR
    $("#btnGuardarImprimir").click(function (){
      guardarPoliza(true);
    });

    // CLICK GRABAR E IMPRIMIR Trans
    $("#btnGuardarImprimirt").click(function (){
      guardarPolizaTr(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 AGREGAR Trans
    $("#btnAgregart").click(function () {
      if (restriccionModalTr()) {return};
      addRowPolTr(txtCtat.value, txtCtatNom.value, isNullNumber(numDebet.value).toFixed(2), isNullNumber(numHabert.value).toFixed(2));
      limpiarModalPolTr();
      sumPolTr();
      $("#btnAddt").focus();
    });

  });

    $("#btnBusdocp").click(function (){
      txtDcodlis.value = "";
      txtDclilis.value =  "";
      tblClear("tblDocpLis");
      sumCajaLis();
      $('#modalLisDocp').modal('toggle');
      $('#modalLisDocp').find('input:visible:first').focus();
    });


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


      $("#tblDocpLis").find('tbody tr').each(function (i,index) {
        codpl = $(this).find("td:eq(0)").text();
        cliendl = $(this).find("td:eq(1)").text();
        ctal = $(this).find("td:eq(2)").text();
        tipodl = $(this).find("td:eq(3)").text();
        seriedl = $(this).find("td:eq(4)").text();
        numdl = $(this).find("td:eq(5)").text();
        fecdl = $(this).find("td:eq(6)").text();
        tcamdl = $(this).find("td:eq(7)").text();
        condl = $(this).find("td:eq(8)").text();
        saldodl = $(this).find("td:eq(9)").text();
        abonodl = $(this).find("td:eq(10)").text();

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

      });

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

      sumCaja();
    });

  // CHANGE CAJA
  $("body").on("change", "input[name=cb]", function (){
    /*if ($(this).find('td input[name="cb"]').is(":checked")) {
      sal = parseFloat($(this).find('#datasaldo').text());
      dataabono.text(isNullNumber(sal).toFixed(2));

    } else {
    dataabono.text() = 0;    
    } */   
    sumCaja();
  });

  // CHANGE CAJA
  $("body").on("change", "input[name=cblis]", function (){
    /*if ($(this).find('td input[name="cb"]').is(":checked")) {
      sal = parseFloat($(this).find('#datasaldo').text());
      dataabono.text(isNullNumber(sal).toFixed(2));

    } else {
    dataabono.text() = 0;    
    } */   
    sumCajaLis();
  });

  // CLICK ADD
  $("body").on("click", "#btnAdd", function () {
    if (restriccionCamposVacios()) {return};
    if (restriccionMesCerrado()) {return};
    inputCtaMov = "txtCta";
    $('#modalPol').modal('toggle');
    $("#pills-000-tab").text("Agregar");
    $("#btnAgregar").show();
    $("#btnModificar").hide();
    limpiarModalPol();
  });

  // CLICK ADD Trans
  $("body").on("click", "#btnAddt", function () {
    if (restriccionCamposVaciosTr()) {return};
    if (restriccionMesCerrado()) {return};
    inputCtaMov = "txtCtat";
    $('#modalPolTr').modal('toggle');
    $("#pills-003-tab").text("Agregar");
    $("#btnAgregart").show();
    $("#btnModificart").hide();
    limpiarModalPol();
  });

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

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

  // CLICK EDIT
  $("body").on("click", "#btnEdit", function() {
    $('#pills-000-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();
    });
  });

  // 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 datacodpd = $(this).parents("tr").find("#datacodpd");
    const datacliend = $(this).parents("tr").find("#datacliend");
    const dataseried = $(this).parents("tr").find("#dataseried");
    const datanumd = $(this).parents("tr").find("#datanumd");

    txtDserie.value = dataseried.text();
    numDnum.value = datanumd.text();
    txtDcod.value = datacodpd.text();
    txtDcli.value = datacliend.text();
    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();
    });
  });

  $('#cbTodos').click(function () {
    cbAllChecked("tblDocp", "cb", "cbTodos");
    sumCaja();
  });

  // CLICK EDIT Trans
  $("body").on("click", "#btnEditt", function() {
    $('#pills-003-tab').text("Modificar");
    $('#btnAgregart').hide();
    $('#btnModificart').show();

    const dataCtat = $(this).parents("tr").find("#dataCtat");
    const dataCtatNom = $(this).parents("tr").find("#dataCtatNom");
    const dataDebet = $(this).parents("tr").find("#dataDebet");
    const dataHabert = $(this).parents("tr").find("#dataHabert");

    txtCtat.value = dataCtat.text();
    txtCtatNom.value = dataCtatNom.text();
    numDebet.value = dataDebet.text();
    numHabert.value = dataHabert.text();

    $("body").on("click", "#btnModificart", function() {
      if (restriccionModalTr()) {return};
      dataCtat.text(txtCtat.value);
      dataCtatNom.text(txtCtatNom.value);
      dataDebet.text(isNullNumber(numDebet.value).toFixed(2));
      dataHabert.text(isNullNumber(numHabert.value).toFixed(2));
      limpiarModalPolTr();
      sumPolTr();
    });
  });

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

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

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

  // CLICK btnPartida
    $("#btnPartida").click(function (){
      if (restriccionCamposVacios()) {return};
      if (restriccionMesCerrado()) {return};
      if ($("#tblPol tbody").children().length != 0) {
        alWarning({"msg":{"title":"Ya existe partida","text":"La partida de este documento ya existe"}});
        return;
      }

      colDocp = ["acciones", "codp", "clienp", "ctap", "tipo", "serie", "numero", "fecha", "tipocam", "concep", "saldo", "abono", "check"];

      var totQ = round(numTot.value*numTcam.value,2);
      var valch = Number(numTot.value);
      var totdif = round((totQ-Number(numTot.value)),2);

      const parametros = new FormData();
      parametros.append("action", "generarPartida");
      parametros.append("cta", $('#selBan').find('option:selected').data('ctac'));
      parametros.append("ctadif", $('#selBan').find('option:selected').data('ctadif'));
      //parametros.append("ctacli", ctacli);
      parametros.append("tblDocp", tblToJsonCbSkip(colDocp, "tblDocp", 0, 12));

      $('#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 BANCOS
            if (!isNullPer(jsonJS.ctaBanc)) {
              addRowPol(jsonJS.ctaBanc.cta, jsonJS.ctaBanc.cta_nom, valch.toFixed(2), "0.00");
            } else {
              addRowPol("XXXXXXX", "Ingrese cuenta de Bancos", valch.toFixed(2), "0.00");
            }
            if (totdif>0) {
              if (!isNullPer(jsonJS.ctaBandif)) {
                addRowPol(jsonJS.ctaBandif.cta, jsonJS.ctaBandif.cta_nom,totdif.toFixed(2), "0.00");
                } else {
                addRowPol("XXXXXXX", "Ingrese cuenta del Diferencial",totdif.toFixed(2), "0.00");
              }
            }
            // Cuenta CLientes
            jsonJS.ctaCli.forEach(function(i){
              addRowPol(i.cta, i.cta_nom, "0.00", Number(i.cta_abono*numTcam.value).toFixed(2));
            });

            //if (!isNullPer(jsonJS.ctaCli)) {
            //  addRowPol(jsonJS.ctaCli.cta, jsonJS.ctaCli.cta_nom, "0.00", totQ.toFixed(2));
            //} else {
            //  addRowPol("XXXXXXX", "Cuenta no definida", "0.00", totQ.toFixed(2));
            //}
            sumPol();
            alClose();
          }
        }
      });
    });


  // CLICK btnPartida Transf
    $("#btnPartidat").click(function (){
      if (restriccionCamposVaciosTr()) {return};
      if (restriccionMesCerrado()) {return};
      if ($("#tblPolt tbody").children().length != 0) {
        alWarning({"msg":{"title":"Ya existe partida","text":"La partida de este documento ya existe"}});
        return;
      }

      colDocp = ["acciones", "codp", "clienp", "ctap", "tipo", "serie", "numero", "fecha", "tipocam", "concep", "saldo", "abono", "check"];

      var totQ = round(numTott.value*numTcamt.value,2);
      var valch = Number(numTott.value);
      var totdif = round((totQ-Number(numTott.value)),2);

      const parametros = new FormData();
      parametros.append("action", "generarPartidat");
      parametros.append("cta", $('#selBant').find('option:selected').data('ctac'));
      parametros.append("ctadif", $('#selBant').find('option:selected').data('ctadif'));
      //parametros.append("ctacli", ctacli);
      parametros.append("tblDocp", tblToJsonCbSkip(colDocp, "tblDocp", 0, 12));

      $('#btnAddEditt').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 BANCOS
            if (!isNullPer(jsonJS.ctaBanc)) {
              addRowPolTr(jsonJS.ctaBanc.cta, jsonJS.ctaBanc.cta_nom, valch.toFixed(2), "0.00");
            } else {
              addRowPolTr("XXXXXXX", "Ingrese cuenta de Bancos", valch.toFixed(2), "0.00");
            }
            if (totdif>0) {
              if (!isNullPer(jsonJS.ctaBandif)) {
                addRowPolTr(jsonJS.ctaBandif.cta, jsonJS.ctaBandif.cta_nom,totdif.toFixed(2), "0.00");
                } else {
                addRowPolTr("XXXXXXX", "Ingrese cuenta del Diferencial",totdif.toFixed(2), "0.00");
              }
            }
            // Cuenta CLientes
            jsonJS.ctaCli.forEach(function(i){
              addRowPolTr(i.cta, i.cta_nom, "0.00", Number(i.cta_abono*numTcamt.value).toFixed(2));
            });
            sumPolTr();
            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-007") {
        $(target+' input:visible:first').focus();
      }
    }
  });
</script>

