<?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'];
$empNom = $_SESSION['empNom'];
$usuNom = $_SESSION['usuNom'];

# 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);
$mesCerrado = ($db->sFetchAssoc($sCiemes)["ciem_stat"] == "C") ? "true" : "false";
$anoTrab=date("Y");
$mesTrab=date("m");
$db->close();
?>
<?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 IVA -->
      <div class="modal fade" id="modalIva" tabindex="-1" role="dialog" aria-labelledby="modalIvaTitle" 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" id="pills-tab" role="tablist">
                <li class="nav-item">
                  <a class="nav-link active" id="pills-10-tab" data-toggle="pill" href="#pills-10" role="tab" aria-controls="pills-10" aria-selected="true">Registrar Facturas</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" id="pills-11-tab" data-toggle="pill" href="#pills-11" role="tab" aria-controls="pills-11" aria-selected="false">Buscar Proveedor</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" id="pills-12-tab" data-toggle="pill" href="#pills-12" role="tab" aria-controls="pills-12" aria-selected="false">Buscar Cuentas</a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-light" aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">

              <div class="tab-content bg-transparent border-0" id="pills-tabContent">
                <div class="tab-pane fade show active" id="pills-10" role="tabpanel" aria-labelledby="pills-10-tab">
                  <?php
                    include('indexi.php');
                  ?>
                </div>
                <div class="tab-pane fade" id="pills-11" role="tabpanel" aria-labelledby="pills-11-tab">
                  <?php
                    $a='10';
                    $b='11';
                    include('../busProvee/index.html');
                  ?>
                </div>
                <div class="tab-pane fade" id="pills-12" role="tabpanel" aria-labelledby="pills-12-tab">
                  <?php
                    $a='10';
                    $b='12';
                    include('../busCuentasMov2/index.html');
                  ?>
                </div>
              </div>

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

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

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

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

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

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

      <!-- MODAL Fecha Anula -->
      <div class="modal fade" id="modalfeca" tabindex="-1" role="dialog" aria-labelledby="modalfaTitle" 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">FECHA ANULACION</a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-light" aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">

              <div class="tab-content bg-transparent border-0" id="pills-tabContent">
                <div class="tab-pane fade show active" id="pills-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="dtFecAnu">Fecha Anulacion</label>
                          <input type="date" class="form-control form-control-sm form-control-as" id="dtFecAnu" placeholder="">
                        </div>
                      </div>
                      <div class="form-row">
                        <div class="col-md-12">
                          <label for="txtConAnu">Concepto anulacion</label>
                          <textarea class="form-control form-control-sm form-control-as" id="txtConAnu" rows="3"></textarea>
                        </div>
                      </div>
                    </div>

                    <button type="button" class="btn btn-success btn-block" id="btnContinuar">Proceder a la Anulacion</button>
                  </form>
                </div>
              </div>

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

      <!-- MODAL Poliza Anular -->
      <div class="modal fade" id="modalpolAnu" tabindex="-1" role="dialog" aria-labelledby="modalpaTitle" 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-001-tab" data-toggle="pill" href="#pills-001" role="tab" aria-controls="pills-001" aria-selected="true">POLIZA ANULACION</a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-black" 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-001" role="tabpanel" aria-labelledby="pills-001-tab">
                  
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">
                      <div class="form-row">
                        <div class="col-5">
                          <label for="anudtFec">Fecha</label>
                          <input type="date" class="form-control form-control-sm form-control-as" id="anudtFec" placeholder="" disabled>
                        </div>
                        <div class="col-md-7">
                          <label for="anuselTipo">Tipo de Poliza</label>
                          <select class="form-control form-control-sm form-control-as" name="anuselTipo" id="anuselTipo" disabled>
                            <option value="0">Seleccionar...</option>
                            <?php
                              while ($rec = $db->fetchAssoc($select['tipopol'])) {
                                echo  '<option value="'.$rec['tp_cod'].'">'.utf8_encode($rec['tp_nom']).'</option>';
                              }
                            ?>
                          </select>
                        </div>
                      </div>

                      <div class="form-row">

                        <div class="col-md-6">
                          <label for="anuselBan">Banco</label>
                          <select class="form-control form-control-sm form-control-as" name="anuselBan" id="anuselBan" disabled>
                            <option value="0">Sin Banco</option>
                            <?php
                              while ($recanu = $db->fetchAssoc($select['bancos2'])) {
                                echo  '<option value="'.$recanu['ban_num'].'">'.utf8_encode($recanu['ban_nom']).'</option>';
                              }
                            ?>
                          </select>
                        </div>

                        <div class="col-md-6">
                          <label for="anunumNum">No. Poliza</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="anunumNum" placeholder="0">
                        </div>
                      </div>

                      <div class="form-row">
                        <div class="col-12">
                          <label for="anutxtCon">Concepto</label>
                          <textarea class="form-control form-control-sm form-control-as" id="anutxtCon" rows="3"></textarea>
                        </div>
                      </div>
                    </div>

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

                    <div class="form-group">
                      <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="anutblPol">
                              <thead>
                                <tr>
                                  <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"></th>
                                <th scope="col" class="text-right">Totales</th>
                                <th scope="col" id="anudataTotDebe" class="text-right">0.00</th>
                                <th scope="col" id="anudataTotHaber" class="text-right">0.00</th>
                              </tfoot>
                            </table>
                          </div>
                        </div>
                      </div>
                    </div>
                    <button type="button" class="btn btn-success btn-block" id="anubtnGrabar">Grabar Poliza Reversion</button>
                  </form>
                </div>
              </div>

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


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

                <form action="" name="thisform" autocomplete="off" enctype="multipart/form-data">
                  <div class="form-row">
                    <div class="col-12 col-sm-10">
                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-md-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-3">
                            <label for="numNum">No. Cheque</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 Cheque</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 Cheque</label>
                            <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numTot" placeholder="0.00" min="0">
                          </div>
                          <div class="col-6 col-md-3">
                            <label for="numTcam">Tasa de Cambio</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numTcam">
                          </div>
                          <div class="col-6 col-md-3 text-center">
                            <div class="custom-control custom-switch">
                              <input type="checkbox" class="custom-control-input" name="cbNego" id="cbNego">
                              <label class="custom-control-label" for="cbNego">No negociable </label>
                            </div>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-12">
                            <label for="txtBene">Beneficiario</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtBene">
                          </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>
                        <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 d-none">0.00</th>
                                  <th scope="col" id="dataTotHaber" class="text-right d-none">0.00</th>
                                  <th scope="col" id="dataTotDebeShow" class="text-right">0.00</th>
                                  <th scope="col" id="dataTotHaberShow" class="text-right">0.00</th>
                                </tfoot>
                              </table>
                            </div>
                          </div>
                        </div>
                      </div>

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

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

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

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

              </div>

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

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

<script>
  var pressEnter = false;
  var nuevo = true;
  var totant = 0;
  var nuevoiva = true;
  var rfecAntI = "0000-00-00";
  var inputCheques = "numNum";
  var tblPolAnt;
  var mesCerrado = <?php echo $mesCerrado ?>;
  var mesCerradoI = <?php echo $mesCerrado ?>;
  var usuario = "<?php echo $usuNom ?>";
  var empnom = "<?php echo $empNom ?>";
  var btnAddEdit = "00";
  var nuevoProvee = true;
  var inputCtaMov = "txtCta";
  var inputProvee = "txtNit"
  var subb=0;
  var subs=0;
  var subpe=0;
  var subco=0;
  var subve=0;
  var subi=0;
  var subir=0;
  var subna=0;
  var subme=0;

  var deduTot=0;
  var tot=0;
  var sub=0;
  var iva=0;
  var ret=0;
  var reti=0;

  var sumcta=0;
  var falcta=0;


  const numNum = document.thisform.numNum;
  const selBan = document.thisform.selBan;
  const dtFec = document.thisform.dtFec;
  const numTot = document.thisform.numTot;
  const numTcam = document.thisform.numTcam;
  const cbNego = document.thisform.cbNego;
  const txtBene = document.thisform.txtBene;
  const txtCon = document.thisform.txtCon;

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

  const dtFecAnu = document.getElementById("dtFecAnu");
  const txtConAnu = document.getElementById("txtConAnu");

  const txtSerieI = document.thisformfac.txtSerieI;
  const numNumI = document.thisformfac.numNumI;
  const txtNitI = document.thisformfac.txtNitI;
  const selTipoI = document.thisformfac.selTipoI;
  const txtProvI = document.thisformfac.txtProvI;
  const dtFecI = document.thisformfac.dtFecI;
  const selMesI = document.thisformfac.selMesI;
  const numAnoI = document.thisformfac.numAnoI;

  const crRetI = document.thisformfac.crRetI;
  const crRetiI = document.thisformfac.crRetiI;
  const crCajaI = document.thisformfac.crCajaI;
  const crAfeI = document.thisformfac.crAfeI;
  const numBienI = document.thisformfac.numBienI;
  const numServI = document.thisformfac.numServI;
  const numPequeI = document.thisformfac.numPequeI;
  const numPeque2I = document.thisformfac.numPeque2I;
  const numImpI = document.thisformfac.numImpI;
  const numImpreI = document.thisformfac.numImpreI;
  const numTasamI = document.thisformfac.numTasamI;
  const numMediI = document.thisformfac.numMediI;
  const numNoafeI = document.thisformfac.numNoafeI;
  const numVehiI = document.thisformfac.numVehiI;
  const numVehiaI = document.thisformfac.numVehiaI;
  const crTvehiI = document.thisformfac.crTvehiI;
  const numTfacomI = document.thisformfac.numTfacomI;
  const numGalosI = document.thisformfac.numGalosI;
  const numGalorI = document.thisformfac.numGalorI;
  const numGalodI = document.thisformfac.numGalodI;
  const txtConI = document.thisformfac.txtConI;
  const txtCta1g = document.thisformfac.txtCta1g;
  const txtCta1gNom = document.thisformfac.txtCta1gNom;
  const numCta1gV = document.thisformfac.numCta1gV;
  const txtCta2g = document.thisformfac.txtCta2g;
  const txtCta2gNom = document.thisformfac.txtCta2gNom;
  const numCta2gV = document.thisformfac.numCta2gV;
  const txtCta3g = document.thisformfac.txtCta3g;
  const txtCta3gNom = document.thisformfac.txtCta3gNom;
  const numCta3gV = document.thisformfac.numCta3gV;
  const txtCta4g = document.thisformfac.txtCta4g;
  const txtCta4gNom = document.thisformfac.txtCta4gNom;
  const numCta4gV = document.thisformfac.numCta4gV;

  // TOTALES
  const numRetI = document.thisformfac.numRetI;
  const numRetiI = document.thisformfac.numRetiI;
  const numSubI = document.thisformfac.numSubI;
  const numIvaI = document.thisformfac.numIvaI;
  const numTotI = document.thisformfac.numTotI;

  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 CHEQUE"}});
        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(4)").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 debitar en la cuenta de banco NO COINCIDE CON EL VALOR DEL CHEQUE, verifique."}});
        return true;
      }
    } else {
      if (isNullPer(selBan.value) || isNullPer(numNum.value)) {
        return true;
      }
    }
    return false;
  }

  function restriccioniva(consultari = false){
    if (!consultari) {
      if (isNullPer(txtSerieI.value)) {
        txtSerieI.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar la SERIE"}});
        return true;
      }
      if (isNullPer(numNumI.value)) {
        numNumI.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NÚMERO"}});
        return true;
      }
      if (isNullPer(txtNitI.value)) {
        txtNitI.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NIT"}});
        return true;
      }
      if (mesCerradoI) {
        restriccionMesCerradoI();
        return true;
      } 
    } else {
      if (isNullPer(txtSerieI.value) || isNullPer(numNumI.value) || isNullPer(txtNitI.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 CHEQUE"}});
      return true;
    }
    return false;
  }

  function restriccionCamposVaciosiva(incluyeNit = true) {
    if (isNullPer(txtSerieI.value)) {
      txtSerieI.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar la SERIE"}});
      return true;
    }
    if (isNullPer(numNumI.value)) {
      numNumI.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NÚMERO"}});
      return true;
    }
    if (incluyeNit) {
      if (isNullPer(txtNitI.value)) {
        txtNitI.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NIT"}});
        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 anurestriccionMesCerrado() {
    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 restriccionMesCerradoI() {
    if (mesCerradoI) {
      alError({"msg":{"type":"error","title":"Mes Cerrado","text":"No puede trabajar con este mes porque ya fue cerrado", "ok":"Aceptar"}});
      return true;
    }
    return false;
  }

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

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

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

  function 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 num d-none'>"+debe+"</td>"
                +"<td id='dataHaber' class='text-right num d-none'>"+haber+"</td>"
                +"<td id='dataDebeShow' class='text-right num'>"+numberFormatNotSymbolGTQ(debe)+"</td>"
                +"<td id='dataHaberShow' class='text-right num'>"+numberFormatNotSymbolGTQ(haber)+"</td>"
                +"</tr>";
    $("#tblPol tbody").append(row);
  }

  function addRowAnuPol(cta, ctaNom, debe, haber){
    const row = "<tr>"
                +"<td id='anudataCta'>"+cta+"</td>"
                +"<td id='anudataCtaNom'>"+ctaNom+"</td>"
                +"<td id='anudataDebe' class='text-right'>"+debe+"</td>"
                +"<td id='anudataHaber' class='text-right'>"+haber+"</td>"
                +"</tr>";
    $("#anutblPol tbody").append(row);
  }

  function consultarCheques(){
    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,
      success: function (jsonPhp) {
        console.log(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.cheques === null) {
            nuevo = true;
            totant = 0;
          } else {
            dtFec.value = jsonJS.cheques.ch_fec;
            numTot.value = jsonJS.cheques.ch_tot;
            numTcam.value = jsonJS.cheques.ch_tcam;
            txtBene.value = jsonJS.bene;
            txtCon.value = jsonJS.cheques.ch_con;
            cbNego.checked = (jsonJS.cheques.ch_nego == "N") ? 1 : 0;
            chmod = jsonJS.cheques.ch_mod;
            jsonJS.poli_det.forEach(function(i){
              addRowPol(i.pold_cta, i.pold_ctan, i.pold_debe, i.pold_haber);
            });
            sumPol();
            totant = jsonJS.cheques.ch_tot;            
            nuevo = false;
          }
          //(pressEnter) ? alClose() : alCloseFocus(txtNext);
          //pressEnter = false; 
          //alClose();
          //dtFec.focus();
        }
      }
    });
  }

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

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

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

    parametros.append("nuevo", nuevo);
    parametros.append("totant", totant);    
    parametros.append("numNum", numNum.value);
    parametros.append("selBanCod", selBan.value);
    parametros.append("dtFec", dtFec.value);
    parametros.append("numTot", numTot.value);
    parametros.append("numTcam", numTcam.value);
    parametros.append("cbNego", cbNego.checked);
    parametros.append("txtBene", txtBene.value);
    parametros.append("txtCon", txtCon.value);
    parametros.append("tblPol", tblToJson(colPol, "tblPol", 0));
    parametros.append("tblPolAnt", tblPolAnt);

    var p = "";


    switch ($('#selBan').find('option:selected').data('forma')){
      case 1:
        p = 'ban1010';
        break;
      case 2:
        p = 'ban1011';
        break;
      case 3:
        p = 'ban1012';
        break;
      case 4:
        p = 'ban1013';
        break;
      case 5:
        p = 'ban1014';
        break;
      case 6:
        p = 'ban1015';
        break;
      case 7:
        p = 'ban1016';
        break;
      default:
        p = 'ban1010';
        break;
    }

    tblClear("tblPolPrint", true);
    fecha = new Date(parametros.get("dtFec").replace(/-/g, '\/'));
    var options = { year: 'numeric', month: 'long', day: 'numeric' };

    // Para la parte del voucher
    $("."+p+" #printBlanco").text('   ');

    $("."+p+" #printFec").text(fecha.toLocaleDateString("es-ES", options));
    $("."+p+" #printTot").text(formatNumber(Number(parametros.get("numTot")), 2));
    $("."+p+" #printBene").text(parametros.get("txtBene"));
    $("."+p+" #printTotl").text(numeroALetras(parametros.get("numTot"), 2).toUpperCase());
    $("."+p+" #printNego").text((parametros.get("cbNego") == 'true') ? "NO NEGOCIABLE" : "");
    $("."+p+" #printCon").text(parametros.get("txtCon"));
    $("."+p+" #printNumch").text(parametros.get("numNum"));
    $("."+p+" #printBanNom").text($("#selBan option:selected").text());
    $("."+p+" #printUsunom").text(usuario);
    $("."+p+" #printEmpnom").text(empnom);
    $("."+p+" #printBanCtab").text($('#selBan').find('option:selected').data('ctab'));
    $("."+p+" #tblPolPrint tbody").append($('#tblPol tbody').clone().find(".ignore").remove().end().html());
    $("."+p+" #tblPolPrint tfoot").append($('#tblPol tfoot').clone().find(".ignore").remove().end().html());

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

        const jsonJS = JSON.parse(jsonPhp);

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

          if (jsonJS.probpol1 != "X") {
            alError({"msg":{"type":"error","title":"PROBLEMA EN CUENTAS","text":"Alguna de las cuentas no esta asignada correctamente, verifique.", "ok":"Aceptar"}});
              var snhacer = false;
                     return true;
          }
          /*if (jsonJS.probpol2 != "X") {
            alError({"msg":{"type":"error","title":"CUENTA DEL BANCO","text":"No tiene asignada la cuenta del banco correctamente, verifique.", "ok":"Aceptar"}});
              var snhacer = false;
                     return true;
          }
          if (jsonJS.probpol3 != "X") {
            alError({"msg":{"type":"error","title":"VALOR CUENTA DEL BANCO","text":"Lo que quiere debitar en la cuenta de banco NO COINCIDE CON EL VALOR DEL CHEQUE, verifique.", "ok":"Aceptar"}});
              var snhacer = false;
                     return true;
          }*/
          if (snhacer) {
            numNum.value = "";
            limpiar();
            tblClear("tblPol");
            sumPol();
            alSuccess(jsonJS);
            if (imprimir) {
              $('.'+p).printThis({
                importCSS: false,
                loadCSS: bootstrapPrint,
              });
            }
          }  
        }

        }), 0;
      }
    });
  }

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

  function limpiar(todo = false){
    dtFec.value= '<?php echo $dtFec; ?>';    
  //  numTcam.value = (1).toFixed(5);
    cbNego.checked = 1;
    numTot.value = (0).toFixed(2);
    txtBene.value = "";
    txtCon.value = "";
  }

  function sumPol(){
    const sumDebe = tblSumCol("tblPol", "dataDebe");
    const sumHaber = tblSumCol("tblPol", "dataHaber");
    $("#tblPol #dataTotDebe").text(sumDebe.toFixed(2));
    $("#tblPol #dataTotHaber").text(sumHaber.toFixed(2));
    $("#tblPol #dataTotDebeShow").text(numberFormatNotSymbolGTQ(sumDebe));
    $("#tblPol #dataTotHaberShow").text(numberFormatNotSymbolGTQ(sumHaber));
  }

  function sumAnuPol(){
    $("#anudataTotDebe").text(tblSumCol("anutblPol", "anudataDebe").toFixed(2));
    $("#anudataTotHaber").text(tblSumCol("anutblPol", "anudataHaber").toFixed(2));
  }

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

    dtFecI.value = dateToday();
    selMesI.value = <?php echo $mesTrab; ?>;
    numAnoI.value = <?php echo $anoTrab; ?>;
    crRetI.value = "N";
    crRetiI.value = "N";
    crCajaI.value = "N";
    crAfeI.value = "S";

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

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

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

    // FOCUS NUMERO DE CHEQUE
    $("#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,
        async: false,
        success: function (jsonPhp) {
          const jsonJS = JSON.parse(jsonPhp);
            if (jsonJS.bancos === null) {
            } else {
              if (jsonJS.bancos.ban_mon == 1) {
                numTcam.value = (1).toFixed(5);
                numTcam.disabled = true;
              } else {
                numTcam.value = '<?php echo $_SESSION["empTasa"] ?>';
                numTcam.disabled = false;
              }
              numNum.value = jsonJS.bancos.ban_corr;
            }
          }
      });
    });

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

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

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

    // FOCUS VALOR CHEQUE, BENEFICIARIO, CONCEPTO
    $("#numTot, #txtBene, #txtCon").focus(function (){
      if (restriccionCamposVacios()) {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-01-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      txtGetValue = document.getElementById("txtCtaNom");
      txtNext = document.getElementById("numDebe");

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

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

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

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

    // CLICK BORRAR
    $("#btnBorrar").click(function (){
      if (restriccion()) {return};
      if (chmod == 'cxp') {
        numNum.focus();
        alWarning({"msg":{"title":"GRABADO EN OTRO MODULO","text":"Este cheque fue registrado en Cuentas por Pagar, solo puede borrarlo desde ese modulo"}});
        return true;
      }
      const fnT = function(){
        colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

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

        parametros.append("selBanCod", selBan.value);
        parametros.append("numNum", numNum.value);
        parametros.append("dtFec", dtFec.value);
        parametros.append("tblPolAnt", tblPolAnt);
        
        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) {
            const jsonJS = JSON.parse(jsonPhp);

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

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

    // CLICK ANULAR
    $("#btnAnular").click(function (){
     // if (restriccion()) {return};
      if (chmod == 'cxp') {
        numNum.focus();
        alWarning({"msg":{"title":"GRABADO EN OTRO MODULO","text":"Este cheque fue registrado en Cuentas por Pagar, solo puede anularlo desde ese modulo"}});
        return true;
      }

      const fnT = function(){
        dtFecAnu.value = dateToday();
        txtConAnu.value = "ANULACION DE CHEQUE No. "+numNum.value;
        $('#modalfeca').modal('toggle');

      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

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

    // CLICK GUARDAR POLIZA DE ANULACION
    $("#anubtnGrabar").click(function (){
      anugrabarPoliza();
    });

    // CLICK GRABAR E IMPRIMIR
    $("#btnGuardarImprimir").click(function (){
      guardarPoliza(true);
    });
    
    // CLICK AGREGAR
    $("#btnAgregar").click(function () {
      if (restriccionModal()) {return};
      addRowPol(txtCta.value, txtCtaNom.value, isNullNumber(numDebe.value).toFixed(2), isNullNumber(numHaber.value).toFixed(2));
      limpiarModalPol();
      sumPol();
      $("#btnAdd").focus();
    });
  });

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

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

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

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

    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));
      dataDebeShow.text(numberFormatNotSymbolGTQ(numDebe.value));
      dataHaberShow.text(numberFormatNotSymbolGTQ(numHaber.value));
      limpiarModalPol();
      sumPol();
    });
  });

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


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

      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("selBanCod", selBan.value);
      parametros.append("numChequei", numNum.value);

      parametros.append("cta", $('#selBan').find('option:selected').data('ctac'));
      parametros.append("ctadif", $('#selBan').find('option:selected').data('ctadif'));

      $('#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 {
            if (jsonJS.hayFac=="S") {
              // Cuentas de gastos
              jsonJS.ctaGasto.forEach(function(i){
                addRowPol(i.cta, i.cta_nom, Number(i.cta_valor).toFixed(2), "0.00");
              });
              // Cuenta del Iva
              if (Number(jsonJS.ctaIva.cta_valor)>0) {
                addRowPol(jsonJS.ctaIva.cta, jsonJS.ctaIva.cta_nom, Number(jsonJS.ctaIva.cta_valor).toFixed(2), "0.00");
              }
              // Cuenta del IDP
              if (Number(jsonJS.ctaComb.cta_valor)>0) {
                addRowPol(jsonJS.ctaComb.cta, jsonJS.ctaComb.cta_nom, Number(jsonJS.ctaComb.cta_valor).toFixed(2), "0.00");
              }
              // Cuenta del Retencion ISR
              if (Number(jsonJS.ctaRisr.cta_valor)>0) {
                addRowPol(jsonJS.ctaRisr.cta, jsonJS.ctaRisr.cta_nom, "0.00", Number(jsonJS.ctaRisr.cta_valor).toFixed(2));
              }
              // Cuenta del Retencion IVA
              if (Number(jsonJS.ctaRiva.cta_valor)>0) {
                addRowPol(jsonJS.ctaRiva.cta, jsonJS.ctaRiva.cta_nom, "0.00", Number(jsonJS.ctaRiva.cta_valor).toFixed(2));
              }
            } else {
              addRowPol("XXXXXXX", "Ingrese cuenta de gastos", totQ.toFixed(2), "0.00");
            }  
/*            if (!isNullPer(jsonJS.ctaProv)) {
              addRowPol(jsonJS.ctaProv.cta, jsonJS.ctaProv.cta_nom, totQ.toFixed(2), "0.00");
            } else {
              addRowPol("XXXXXXX", "Ingrese cuenta de Gastos", totQ.toFixed(2), "0.00");
            }  */

            // Cuenta BANCOS
            if (!isNullPer(jsonJS.ctaBanc)) {
              addRowPol(jsonJS.ctaBanc.cta, jsonJS.ctaBanc.cta_nom, "0.00", valch.toFixed(2));
            } else {
              addRowPol("XXXXXXX", "Ingrese cuenta de Bancos", "0.00", valch.toFixed(2));
            }
            if (totdif>0) {
              if (!isNullPer(jsonJS.ctaBandif)) {
                addRowPol(jsonJS.ctaBandif.cta, jsonJS.ctaBandif.cta_nom, "0.00",totdif.toFixed(2));
                } else {
                addRowPol("XXXXXXX", "Ingrese cuenta del Diferencial", "0.00",totdif.toFixed(2));
              }
            }
            sumPol();
            alClose();
          }
        }
      });
    });


  // CLICK CONTINUAR
  $("#btnContinuar").click(function () {

    txtThis = dtFecAnu;

    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,
      success: function (jsonPhp) {
        const jsonJS = JSON.parse(jsonPhp);

        if(jsonJS.error == true){
          alError(jsonJS);
        } else {
          if (jsonJS.ciemes === null) {
            mesCerrado = false;
            anuContinuar();
          } else { 
            if (jsonJS.ciemes.ciem_stat == "C") {
              mesCerrado = true;
              restriccionMesCerrado();
              $('#modalfeca').modal('toggle');
              numNum.focus();
            } else {
              mesCerrado = false;
              anuContinuar();
            } 
          }
        }
      }
    });

  });

  function anuContinuar() {
    anuselTipo.value="005";
    // Para vefificar correlativo de polizas
    const parametros = new FormData();
    parametros.append("action", "consultarCorrPol");

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

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

    //const parametros = new FormData();

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

    parametros.append("totant", totant);
    parametros.append("selBanCod", selBan.value);
    parametros.append("numNum", numNum.value);
    parametros.append("dtFec", dtFec.value);
    parametros.append("dtFecAnu", dtFecAnu.value);
    parametros.append("txtConAnu", txtConAnu.value);
    parametros.append("tblPolAnt", tblPolAnt);
    
    //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) {
        const jsonJS = JSON.parse(jsonPhp);

        if(jsonJS.error==true){
          alError(jsonJS);
        } else {
          alSuccess(jsonJS);
          // Para que pregunte fecha de anulacion
          $('#modalfeca').modal('toggle');
          //
          // Para que genere la poliza de reversion cuando es otro mes
          if (jsonJS.otromes) {
            anuselTipo.value="005";
            anudtFec.value=dtFecAnu.value;
            anutxtCon.value=txtConAnu.value;
            JSON.parse(tblPolAnt).forEach(function(i){
              addRowAnuPol(i.pold_cta, i.pold_ctan, i.pold_haber, i.pold_debe);
            });
            sumAnuPol();
            $('#modalpolAnu').modal('toggle');
          }                
          //
          numNum.value = "";
          limpiar();
          tblClear("tblPol");
          sumPol();
          numNum.focus();
        }
      }
    });
  }

  function anugrabarPoliza() {
    if (restriccion()) {return};

    colanuPol = ["cta", "ctaNom", "debe", "haber"];

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

    //parametros.append("nuevo", nuevo);
    parametros.append("anunumNum", anunumNum.value);
    parametros.append("anuselTipoCod", anuselTipo.value);
    parametros.append("anuselBanCod", anuselBan.value);
    parametros.append("anudtFec", anudtFec.value);
    parametros.append("anutxtCon", anutxtCon.value);
    parametros.append("anutblPol", tblToJson(colanuPol, "anutblPol", 5));

    //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) {
        const jsonJS = JSON.parse(jsonPhp);

        if(jsonJS.error==true){
          alError(jsonJS);
        } else {
          if (jsonJS.msgWarning.error) {
            alWarning(jsonJS.msgWarning);
            alSuccess(jsonJS);
            numNum.value = "";
            limpiar();
            tblClear("anutblPol");
            sumAnuPol();
            $('#modalpolAnu').modal('toggle');
            numNum.focus();
          } else {
            alWarning(jsonJS.msgWarning);
          }
        }
      }
    }); 
  }


  function guardarCompra(imprimir = false){
    if (restriccioniva()) {return};

    calcular();

    const serieI = txtSerieI.value;
    const numI = numNumI.value;
    const nitI = txtNitI.value;

    const parametros = new FormData();
    parametros.append("actioniva", "guardari");
    parametros.append("nuevoiva", nuevoiva);
    parametros.append("nuevoProvee", nuevoProvee);
    parametros.append("txtSerieI", serieI);
    parametros.append("numNumI", numI);
    parametros.append("txtNitI", nitI);
    parametros.append("selTipoCodI", selTipoI.value);
    parametros.append("txtProvI", txtProvI.value);
    parametros.append("dtFecI", dtFecI.value);
    parametros.append("selMesCodI", selMesI.value);
    parametros.append("numAnoI", numAnoI.value);
    parametros.append("rfecAntI", rfecAntI);
    parametros.append("selBanCod", selBan.value);
    parametros.append("numChequeI", numNum.value);
    parametros.append("crRetI", crRetI.value);
    parametros.append("crRetiI", crRetiI.value);
    parametros.append("crCajaI", crCajaI.value);
    parametros.append("crAfeI", crAfeI.value);
    parametros.append("numBienI", numBienI.value);
    parametros.append("numServI", numServI.value);
    parametros.append("numPequeI", numPequeI.value);
    parametros.append("numPeque2I", numPeque2I.value);
    parametros.append("numImpI", numImpI.value);
    parametros.append("numImpreI", numImpreI.value);
    parametros.append("numTasamI", numTasamI.value);
    parametros.append("numMediI", numMediI.value);
    parametros.append("numNoafeI", numNoafeI.value);
    parametros.append("numVehiI", numVehiI.value);
    parametros.append("numVehiaI", numVehiaI.value);
    parametros.append("crTvehiI", crTvehiI.value);
    parametros.append("numTfacomI", numTfacomI.value);
    parametros.append("deduTot", deduTot);
    parametros.append("numGalosI", numGalosI.value);
    parametros.append("numGalorI", numGalorI.value);
    parametros.append("numGalodI", numGalodI.value);
    parametros.append("numCombI", numCombI.value);
    parametros.append("txtConI", txtConI.value);
    parametros.append("txtCta1g", txtCta1g.value);
    parametros.append("txtCta2g", txtCta2g.value);
    parametros.append("txtCta3g", txtCta3g.value);
    parametros.append("txtCta4g", txtCta4g.value);
    parametros.append("numCta1gV", numCta1gV.value);
    parametros.append("numCta2gV", numCta2gV.value);
    parametros.append("numCta3gV", numCta3gV.value);
    parametros.append("numCta4gV", numCta4gV.value);
    parametros.append("numFalCta", numFalCta.value);

    parametros.append("subb", subb);
    parametros.append("subs", subs);
    parametros.append("subpe", subpe);
    parametros.append("subco", subco);
    parametros.append("subve", subve);
    parametros.append("subi", subi);
    parametros.append("subir", subir);
    parametros.append("subna", subna);
    parametros.append("subme", subme);

    parametros.append("numRetI", numRetI.value);
    parametros.append("numRetiI", numRetiI.value);
    parametros.append("numSubI", numSubI.value);
    parametros.append("numIvaI", numIvaI.value);
    parametros.append("numTotI", numTotI.value);
    parametros.append("numSumCta", numSumCta.value);
    parametros.append("numFalCta", numFalCta.value);


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

        if(jsonJS.error==true){
          alError(jsonJS);
        } else {
          var snhacer = true;
          if (jsonJS.txtflag == 1) {
            alError({"msg":{"type":"error","title":"CUENTAS DE GASTOS","text":"La suma de los valores de las cuentas de gastos, no cuadra con el sub-total, verifique.", "ok":"Aceptar"}});
              var snhacer = false;
                     return true;
          }
          if (jsonJS.txtflag == 2) {
            alError({"msg":{"type":"error","title":"CUENTAS DE GASTOS","text":"No ha asignado ninguna cuenta de gasto, verifique.", "ok":"Aceptar"}});
              var snhacer = false;
                     return true;
          }
          if (snhacer) {
            alSuccess(jsonJS);
          }          
        }
      }
    });
  }

  function limpiari() {
    subb=0;
    subs=0;
    subpe=0;
    subco=0;
    subve=0;
    subi=0;
    subir=0;
    subna=0;
    subme=0;

    deduTot=0;
    tot=0;
    sub=0;
    iva=0;
    ret=0;
    reti=0;

    $('.limpiari').val("");

    dtFecI.value = dateToday();
    selMesI.value = <?php echo $mesTrab; ?>;
    numAnoI.value = <?php echo $anoTrab; ?>;
    //selBanI.value = 0;
    crRetI.value = "N";
    crRetiI.value = "N";
    crCajaI.value = "N";
    crAfeI.value = "S";
    crTvehi1I.checked = false;
    crTvehi2I.checked = false;
    txtCta1g.value="";
    txtCta2g.value="";
    txtCta3g.value="";
    txtCta4g.value="";
    txtCta1gNom.value="";
    txtCta2gNom.value="";
    txtCta3gNom.value="";
    txtCta4gNom.value="";
  }

  function calculoDedu(){
    if (!isNullPer(numTfacomI.value)) {
      deduSuper=round(numGalosI.value*<?php echo $_SESSION["pSuper"] ?>, 2);
      deduRegu=round(numGalorI.value*<?php echo $_SESSION["pRegu"] ?>, 2);
      deduDiesel=round(numGalodI.value*<?php echo $_SESSION["pDiesel"] ?>, 2);

      deduTot=deduSuper+deduRegu+deduDiesel;
    } else {
      deduTot=0;
    }
  }

  function calcular(){
    const pIva = <?php echo $_SESSION["pIva"]; ?>;

    // CALCULO COMBUSTIBLE
    calculoDedu();
    var comb = numTfacomI.value-deduTot;

    // RESTRINGIR EL DOCUMENTO YA SEA EN NEGATIVO O EN POSITIVO
    pone = ($('#selTipoI').find('option:selected').data('pone')=="N") ? -1 : 1;
    const bien=(numBienI.value)*(pone*(Math.sign(numBienI.value)));
    const serv=(numServI.value)*(pone*(Math.sign(numServI.value)));
    const peque=(numPequeI.value)*(pone*(Math.sign(numPequeI.value)));
    const peque2=(numPeque2I.value)*(pone*(Math.sign(numPeque2I.value)));
    const imp=(numImpI.value)*(pone*(Math.sign(numImpI.value)));
    const impre=(numImpreI.value)*(pone*(Math.sign(numImpreI.value)));
    const tasam=(numTasamI.value)*(pone*(Math.sign(numTasamI.value)));
    const medi=(numMediI.value)*(pone*(Math.sign(numMediI.value)));
    const noafe=(numNoafeI.value)*(pone*(Math.sign(numNoafeI.value)));
    const vehi=(numVehiI.value)*(pone*(Math.sign(numVehiI.value)));
    comb*=pone*(Math.sign(comb));
    const cta1gv=(numCta1gV.value)*(Math.sign(numCta1gV.value));
    const cta2gv=(numCta2gV.value)*(Math.sign(numCta2gV.value));
    const cta3gv=(numCta3gV.value)*(Math.sign(numCta3gV.value));
    const cta4gv=(numCta4gV.value)*(Math.sign(numCta4gV.value));

    // SUBTOTALES
    subb=bien;
    subs=serv;
    subpe=peque+peque2;
    subco=comb;
    subve=vehi;
    subi=imp;
    subir=impre;
    subna=noafe;
    subme=medi;
    

    // CALCULO VEHICULO
    var ivaVehi=0;
    if (numVehiaI.value<4 && numVehiaI.value>1 && crTvehiI.value=="C") {
      ivaVehi=1000;
    } else if (numVehiaI.value<4 && numVehiaI.value>1 && crTvehiI.value=="M") {
      ivaVehi=300;
    } else if (numVehiaI.value>3 && crTvehiI.value=="C") {
      ivaVehi=500;
    } else if (numVehiaI.value>3 && crTvehiI.value=="M") {
      ivaVehi=200;
    } else if (numVehiaI.value<2 && (crTvehiI.value=="C" || crTvehiI.value=="M")) {
      subve=vehi/((pIva/100)+1);
      ivaVehi=0;
    }

    // IVA, SUBTOTAL Y TOTAL
    tot=bien+serv+imp+impre+peque+peque2+medi+vehi+noafe+comb+tasam;
    sub=subb+subs+subi+subir+subpe+subme+subve+subna+subco+tasam;
    iva=0;
    if ('<?php echo $_SESSION["empExensn"]; ?>' != 'S') {
      if ($('#selTipoI').find('option:selected').data('impues')=="N") {
        subb/=((pIva/100)+1);
        subs/=((pIva/100)+1);
        subco/=((pIva/100)+1);

        sub=subb+subs+subi+subir+subpe+subme+subve+subna+subco+tasam;
        iva=tot-sub;
        iva+=subi*(pIva/100);
        iva+=subir*(pIva/100);
        iva+=ivaVehi;
        tot=sub+iva;
      }

      // RETENCIÓN ISR
      ret = 0;
      if (crRetI.value=="S" && sub>=2500) {
        if (sub><?php echo $_SESSION["pBaseisr"]; ?>) {
          sub1 = <?php echo $_SESSION["pBaseisr"]; ?>;
          sub2 = sub-<?php echo $_SESSION["pBaseisr"]; ?>;
        } else {
          sub1 = sub;
          sub2 = 0;
        }
        ret1=(sub1*<?php echo $_SESSION["pIsr"]; ?>)/100;
        ret2=(sub2*<?php echo $_SESSION["pIsr2"]; ?>)/100;
        ret=ret1+ret2;
      }

      // RETENCIÓN IVA
      reti = 0;
      if (crRetiI.value=="S") {
        reti=(iva*<?php echo $_SESSION["pRiva"]; ?>)/100;
      }
    }

    // SUMATORIA DE CUENTAS Y FALTANTE
    sumcta = cta1gv+cta2gv+cta3gv+cta4gv;
    falcta = sub - sumcta;

    numBienI.value = numberFixedEmpty(bien);
    numServI.value = numberFixedEmpty(serv);
    numPequeI.value = numberFixedEmpty(peque);
    numPeque2I.value = numberFixedEmpty(peque2);
    numImpI.value = numberFixedEmpty(imp);
    numImpreI.value = numberFixedEmpty(impre);
    numTasamI.value = numberFixedEmpty(tasam);
    numMediI.value = numberFixedEmpty(medi);
    numNoafeI.value = numberFixedEmpty(noafe);
    numVehiI.value = numberFixedEmpty(vehi);
    numCombI.value = numberFixedEmpty(comb);
    numTfacomI.value = numberFixedEmpty(Number(numTfacomI.value));
    numGalosI.value = numberFixedEmpty(Number(numGalosI.value), 3);
    numGalorI.value = numberFixedEmpty(Number(numGalorI.value), 3);
    numGalodI.value = numberFixedEmpty(Number(numGalodI.value), 3);
    numSumCta.value = numberFixedEmpty(Number(sumcta));
    numFalCta.value = numberFixedEmpty(Number(falcta)); 
  }

    // FOCUS SERIE, NUM, NIT
    $("#txtSerieI, #numNumI").focus(function (){
      numNumI.value = "";
      txtNitI.value = "";
      txtProvI.value = "";
      limpiari();
    });

    $("#selTipoI, #txtProvI, #dtFecI, #selMesI, #numAnoI, .limpiari").focus(function (){
      restriccionCamposVaciosiva();
    });

    $("#numCta1gV, #numCta2gV, #numCta3gV, #numCta4gV").blur(function (){
      calcular();
    });

    
    // VALID NIT
    $("#txtNitI")
    .focus(function() {
      inputProvee = $(this).attr('id');
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-11-tab").click(); }
    })
    .change(function (){
      const parametros = new FormData();
      parametros.append("actioniva", "consultarProvee");
      parametros.append("txtNitI", txtNitI.value);

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

          if(jsonJS.error == true){
            alError(jsonJS);
            nuevoProvee = true;
          } else {
            if (jsonJS.provee === null) {
              nuevoProvee = true;
              txtProvI.value = "";
            } else {
              txtProvI.value = jsonJS.provee.pro_nom;
              nuevoProvee = false;
            }
          }
        }
      });
    });

    // VALID SERIE, NUMERO, NIT
    $("#txtSerieI, #numNumI, #txtNitI")
    .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })
    .change(function (){
      if (restriccioniva(true)) {return};
      //setTimeout(function(){
        txtNext = selTipoI;

        const parametros = new FormData();
        parametros.append("actioniva", "consultari");

        parametros.append("txtSerieI", txtSerieI.value);
        parametros.append("numNumI", numNumI.value);
        parametros.append("txtNitI", txtNitI.value);

        $.ajax({
          data:  parametros,
          url:   window.location.origin+window.location.pathname+"actionsi.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 {
              limpiari();

              if (jsonJS.iva_comp === null) {
                mesCerradoI = false;
              } else {
                if (jsonJS.iva_comp.ciem_stat === "C") {
                  mesCerradoI = true;
                } else {
                  mesCerradoI = false;
                }
              }
              
              if (jsonJS.iva_comp === null) {
                nuevoiva = true;
                rfecAntI = "0000-00-00";
              } else {
                selTipoI.value = jsonJS.iva_comp.iva_tipo;
                txtProvI.value = jsonJS.iva_comp.iva_prov;
                dtFecI.value = jsonJS.iva_comp.iva_fec;

                // FECHA A REPORTAR
                const d = YMDToDate(jsonJS.iva_comp.iva_rfec);
                selMesI.value = d.getMonth()+1;
                numAnoI.value = d.getFullYear();
                rfecAntI = jsonJS.iva_comp.iva_rfec;

                //selBanI.value = jsonJS.iva_comp.iva_ban;
                //numChequeI.value = jsonJS.iva_comp.iva_cheque;

                crRetI.value = jsonJS.iva_comp.iva_retsn;
                crRetiI.value = jsonJS.iva_comp.iva_retisn;
                crCajaI.value = jsonJS.iva_comp.iva_caja;
                crAfeI.value = jsonJS.iva_comp.iva_afe;
                numBienI.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_bien));
                numServI.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_serv));
                numPequeI.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_peque));
                numPeque2I.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_peque2));
                numImpI.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_imp));
                numImpreI.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_impre));
                numTasamI.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_tasam));
                numMediI.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_medi));
                numNoafeI.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_noafe));
                numVehiI.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_vehi));
                numVehiaI.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_vehia));
                crTvehiI.value = jsonJS.iva_comp.iva_tvehi;
                numTfacomI.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_tfacom));
                numGalosI.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_galos), 3);
                numGalorI.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_galor), 3);
                numGalodI.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_galod), 3);
                numCombI.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_comb));
                txtConI.value = jsonJS.iva_comp.iva_con;
                txtCta1g.value = jsonJS.iva_comp.iva_cta1;
                txtCta2g.value = jsonJS.iva_comp.iva_cta2;
                txtCta3g.value = jsonJS.iva_comp.iva_cta3;
                txtCta4g.value = jsonJS.iva_comp.iva_cta4;
                txtCta1gNom.value = jsonJS.iva_comp.iva_cta1gnom;
                txtCta2gNom.value = jsonJS.iva_comp.iva_cta2gnom;
                txtCta3gNom.value = jsonJS.iva_comp.iva_cta3gnom;
                txtCta4gNom.value = jsonJS.iva_comp.iva_cta4gnom;
                numCta1gV.value = jsonJS.iva_comp.iva_ctav1;
                numCta2gV.value = jsonJS.iva_comp.iva_ctav2;
                numCta3gV.value = jsonJS.iva_comp.iva_ctav3;
                numCta4gV.value = jsonJS.iva_comp.iva_ctav4;
                ctav1 = Number(jsonJS.iva_comp.iva_ctav1);
                ctav2 = Number(jsonJS.iva_comp.iva_ctav2);
                ctav3 = Number(jsonJS.iva_comp.iva_ctav3);
                ctav4 = Number(jsonJS.iva_comp.iva_ctav4);
                sumcta = ctav1+ctav2+ctav3+ctav4;

                calculoDedu();
                tot=Number(jsonJS.iva_comp.iva_tot);
                sub=Number(jsonJS.iva_comp.iva_sub);
                iva=Number(jsonJS.iva_comp.iva_iva);
                ret=Number(jsonJS.iva_comp.iva_ret);
                reti=Number(jsonJS.iva_comp.iva_reti);

                falcta = sub - sumcta;
                numSumCta.value = sumcta.toFixed(2);
                numFalCta.value = falcta.toFixed(2);                

                // TOTALES
                numRetI.value=ret.toFixed(2);
                numRetiI.value=reti.toFixed(2);
                numSubI.value=sub.toFixed(2);
                numIvaI.value=iva.toFixed(2);
                numTotI.value=tot.toFixed(2);

                nuevoiva = false;
              }
              (pressEnter) ? alClose() : alCloseFocus(txtNext);
              pressEnter = false;
            }
          }
        });
      //},0);
    });

    // VALID FECHA
    $("#dtFecI").blur(function (){
      const d = new Date(dtFecI.value);
      selMesI.value = d.getMonth()+1;
      $("#selMesI").trigger("change");
    });

    // VALID MES FACTURAS IVA
    $("#selMesI").change(function (){
      const parametros = new FormData();
      parametros.append("actioniva", "consultarCiemes");
      parametros.append("numAno", numAnoI.value);
      parametros.append("selMesCod", selMesI.value);

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

          if (jsonJS.ciemes === null) {
            mesCerradoI = false;
          } else {
            if (jsonJS.ciemes.ciem_stat === "C") {
              mesCerradoI = true;
            } else {
              mesCerradoI = false;
            }
          }
          restriccionMesCerradoI();
        }
      });
    });

    $(".calcular").change(function (){
      calcular();
      numRetI.value=ret.toFixed(2);
      numRetiI.value=reti.toFixed(2);
      numSubI.value=sub.toFixed(2);
      numIvaI.value=iva.toFixed(2);
      numTotI.value=tot.toFixed(2);
      numSumCta.value=sumcta.toFixed(2);
      numFalCta.value=falcta.toFixed(2);
    });

    // VALID CUENTAS
    $("input[id*='txtCta']:not(#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-12-tab").click(); }
    })
    .change(function (){
      var inputs = $(this).closest('form').find(':input');

      txtThis = this;
      txtGetValue = document.getElementById($(this).attr('id')+"Nom");
      txtNext = inputs.eq(inputs.index(this)+2);

      $(txtThis).off("blur");
      if (restriccionCtaCod()) {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
    $("#btnGuardarI").click(function (){
      guardarCompra();
    });

    // CLICK GUARDAR
    $("#btnRegresar").click(function (){
      $('#modalIva').modal('toggle');
      return false;
    });
/*
    // FOCUS INPUT
    $("form[name='thisformfac'] input, select, textarea").focus(function (){
      if (!($("input:visible:first").is(":focus")) && !($("#numNumI").is(":focus")) && !($("#txtNitI").is(":focus"))) {
        if (restriccionCamposVaciosiva()) {return};
      }
    });
*/

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

      if (target == "#pills-11" && (isNullPer(txtSerieI.value) || isNullPer(numNumI.value))) {
        if(restriccionCamposVaciosiva(false)) {return false}
      } else if (target == "#pills-12" && (isNullPer(txtSerieI.value) || isNullPer(numNumI.value) || isNullPer(txtNitI.value))) {
        if(restriccionCamposVaciosiva()) {return false}
      }
  });

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

      if ((target == "#pills-0" && isNullPer(numNum.value)) || target != "#pills-0") {
        if (target == "#pills-10" && isNullPer(txtSerieI.value)) { txtSerieI.focus();
        } else if (target == "#pills-10" && isNullPer(numNumI.value)) { numNumI.focus();
        } else if (target == "#pills-10" && isNullPer(txtNitI.value)) { txtNitI.focus();
        } else if (relatedTarget == "#pills-12") { $("#"+inputCtaMov).focus();
        } else {
          ($(target+' select:visible:first').length) ? $(target+' select:visible:first').focus() : $(target+' input:visible:first').focus();
        }
      } else {
        (target == "#pills-2") ? dtFec.focus() : 0;
      }
    }
  });
</script>

<?php include('../banPrint/ban1010.php'); ?>
<?php include('../banPrint1/ban1011.php'); ?>
<?php include('../banPrint2/ban1012.php'); ?>
<?php include('../banPrint3/ban1013.php'); ?>
<?php include('../banPrint4/ban1014.php'); ?>
<?php include('../banPrint5/ban1015.php'); ?>
<?php include('../banPrint6/ban1016.php'); ?>
