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

# QUERYS
$sTipoc = "SELECT * FROM tipoc";
$sMeses = "SELECT * FROM meses";
$sBancos = "SELECT * FROM bancos WHERE ban_emp='".$_SESSION['empCod']."'";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["tipoc"] = $db->query($sTipoc);
$select["meses"] = $db->query($sMeses);
$select["bancos"] = $db->query($sBancos);
$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 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-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="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">
                      <div class="form-row">
                        <div class="col-md-4">
                          <label for="txtCta">Cuenta</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtCta" placeholder="">
                        </div>
                        <div class="col-md-8">
                          <label for="txtCtaNom">Nombre Cuenta</label>
                          <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtaNom" placeholder="" disabled>
                        </div>
                      </div>
                      <div class="form-row">
                        <div class="col-md-6">
                          <label for="numDebe">Debe</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numDebe" placeholder="0.00">
                        </div>
                        <div class="col-md-6">
                          <label for="numHaber">Haber</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numHaber" placeholder="0.00">
                        </div>
                      </div>
                    </div>

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

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

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

      <div class="container-as">
        <div class="row">
          <div class="col">
            <ul class="nav nav-pills mb-1" id="pills-tab" role="tablist">
              <li class="nav-item">
                <a class="nav-link active" id="pills-0-tab" data-toggle="pill" href="#pills-0" role="tab" aria-controls="pills-0" aria-selected="true">Mantenimiento</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" id="pills-1-tab" data-toggle="pill" href="#pills-1" role="tab" aria-controls="pills-1" aria-selected="true">Buscar Proveedor</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-9">
                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-12 col-sm-6 col-md-3">
                            <label for="txtSerie">Serie</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtSerie" maxlength="20">
                          </div>
                          <div class="col-12 col-sm-6 col-md-3">
                            <label for="numNum">Número</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numNum" placeholder="0" oninput="numberInt(this, 20, event);" min="1">
                          </div>
                          <div class="col-12 col-sm-6 col-md-3">
                            <label for="txtNit">Nit</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtNit" maxlength="20">
                          </div>
                          <div class="col-12 col-sm-6 col-md-3">
                            <label for="selTipo">Tipo</label>
                            <select class="form-control form-control-sm form-control-as calcular" name="selTipo" id="selTipo">
                              <?php
                                while ($rec = $db->fetchAssoc($select['tipoc'])) {
                                  echo  '<option value="'.$rec['tc_cod'].'" data-impues="'.$rec['tc_impues'].'" data-pone="'.$rec['tc_pone'].'">'.utf8_encode($rec['tc_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                        </div>

                        <div class="form-row">
                          <div class="col-12">
                            <label for="txtProv">Proveedor</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtProv">
                          </div>
                        </div>

                        <div class="form-row">
                          <div class="col-md-2.5">
                            <label for="dtFec">Fecha del Documento</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFec" placeholder="">
                          </div>
                          <div class="col-2.5">
                            <label for="selMes">Mes a Reportar</label>
                            <select class="form-control form-control-sm form-control-as" name="selMes" id="selMes">
                              <?php
                                while ($rec = $db->fetchAssoc($select['meses'])) {
                                  echo  '<option value="'.$rec['mes_cod'].'">'.utf8_encode($rec['mes_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-2">
                            <label for="numAno">Año a Reportar</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numAno" placeholder="AAAA">
                          </div>
                          <div class="col-3">
                            <label for="selBan">Banco</label>
                            <select class="form-control form-control-sm form-control-as" name="selBan" id="selBan">
                              <option value="0">Sin Banco</option>
                              <?php
                                while ($rec = $db->fetchAssoc($select['bancos'])) {
                                  echo  '<option value="'.$rec['ban_num'].'">'.utf8_encode($rec['ban_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-2.1">
                            <label for="numCheque">CH/ND</label>
                            <input type="number" class="form-control form-control-sm form-control-as limpiar" id="numCheque" placeholder="0" oninput="numberInt(this, 20, event);" min="1">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-3">
                            <label class="pr-1">Retención ISR</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crRet1" name="crRet" class="custom-control-input calcular" value="S">
                              <label class="custom-control-label" for="crRet1">Si</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crRet2" name="crRet" class="custom-control-input calcular" value="N">
                              <label class="custom-control-label" for="crRet2">No</label>
                            </div>
                          </div>
                          <div class="col-3">
                            <label class="pr-1">Retención IVA</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crReti1" name="crReti" class="custom-control-input calcular" value="S">
                              <label class="custom-control-label" for="crReti1">Si</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crReti2" name="crReti" class="custom-control-input calcular" value="N">
                              <label class="custom-control-label" for="crReti2">No</label>
                            </div>
                          </div>
                          <div class="col-3">
                            <label class="pr-1">Caja Chica</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crCaja1" name="crCaja" class="custom-control-input" value="S">
                              <label class="custom-control-label" for="crCaja1">Si</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crCaja2" name="crCaja" class="custom-control-input" value="N">
                              <label class="custom-control-label" for="crCaja2">No</label>
                            </div>
                          </div>
                          <div class="col-3">
                            <label class="pr-1">Incluir en el Libro</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crAfe1" name="crAfe" class="custom-control-input" value="S">
                              <label class="custom-control-label" for="crAfe1">Si</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crAfe2" name="crAfe" class="custom-control-input" value="N">
                              <label class="custom-control-label" for="crAfe2">No</label>
                            </div>
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-6 col-sm-3">
                            <label for="numBien">Compras</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numBien" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0">
                          </div>
                          <div class="col-6 col-sm-3">
                            <label for="numServ">Servicios</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numServ" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0">
                          </div>
                          <div class="col-6 col-sm-3">
                            <label for="numPeque">Pequeño Contribuyente Bienes</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numPeque" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0">
                          </div>
                          <div class="col-6 col-sm-3">
                            <label for="numPeque2">Pequeño Contribuyente Servicios</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numPeque2" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0">
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-6 col-sm-3">
                            <label for="numImp">Importa. Centro América</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numImp" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0">
                          </div>
                          <div class="col-6 col-sm-3">
                            <label for="numImpre">Importa. Resto del Mundo</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numImpre" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0">
                          </div>
                          <div class="col-6 col-sm-3">
                            <label for="numTasam">Tasa Municipal</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numTasam" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0">
                          </div>
                          <div class="col-6 col-sm-3">
                            <label for="numMedi">Medicamentos</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numMedi" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0">
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-6 col-sm-3">
                            <label for="numNoafe">No Afecto Decreto 29-89</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numNoafe" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0">
                          </div>
                          <div class="col-6 col-sm-3">
                            <label for="numVehi">Valor Vehículo</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numVehi" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0">
                          </div>
                          <div class="col-5 col-sm-3">
                            <label for="numVehia">Antigüedad Vehículo</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numVehia" placeholder="0" oninput="numberInt(this, 2, event);" min="0">
                          </div>
                          <div class="col-7 col-sm-3 text-center">
                            <label class="pr-1">Tipo de Vehículo</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crTvehi1" name="crTvehi" class="custom-control-input calcular" value="C">
                              <label class="custom-control-label" for="crTvehi1">Carro</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crTvehi2" name="crTvehi" class="custom-control-input calcular" value="M">
                              <label class="custom-control-label" for="crTvehi2">Moto</label>
                            </div>
                          </div>
                        </div>
                      </div>

                      <div class="form-group">
                        <h3 class="text-light">Combustible</h3>

                        <div class="form-row align-items-end">
                          <div class="col-6 col-sm-3">
                            <label for="numTfacom">Total de Factura Combustible</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numTfacom" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0">
                          </div>
                          <div class="col-6 col-sm-3">
                            <label for="numGalos">Galones Super</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numGalos" placeholder="0.000" oninput="numberDec(this, 14, 2);" min="0">
                          </div>
                          <div class="col-6 col-sm-3">
                            <label for="numGalor">Galones Regular</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numGalor" placeholder="0.000" oninput="numberDec(this, 14, 2);" min="0">
                          </div>
                          <div class="col-6 col-sm-3">
                            <label for="numGalod">Galones Diesel</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numGalod" placeholder="0.000" oninput="numberDec(this, 14, 2);" min="0">
                          </div>
                        </div>

                        <div class="form-row">
                          <div class="col-12 text-center">
                            <label for="numComb">Valor Afecto Combustible</label>
                            <input type="number" class="form-control form-control-sm form-control-as form-info text-center limpiar" id="numComb" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0" disabled>
                          </div>
                        </div>
                      </div>

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

                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-12">
                            <label for="txtCon">Concepto</label>
                            <textarea class="form-control form-control-sm form-control-as limpiar" id="txtCon" rows="3"></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" 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"></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>
                    <div class="col-12 col-sm-3">
                      <div class="form-group position-fixed-sm">

                        <h3 class="text-light">Impuestos y Totales</h3>
                        <div class="form-row align-items-center ml-2">
                          <div class="col-6">
                            <label for="numRet">Ret. ISR</label>
                          </div>
                          <div class="col-6">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar text-right" id="numRet" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0" disabled>
                          </div>
                          <div class="col-6">
                            <label for="numReti">Ret. IVA</label>
                          </div>
                          <div class="col-6">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar text-right" id="numReti" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0" disabled>
                          </div>
                          <div class="col-6">
                            <label for="numSub">Subtotal</label>
                          </div>
                          <div class="col-6">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar text-right" id="numSub" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0" disabled>
                          </div>
                          <div class="col-6">
                            <label for="numIva">IVA</label>
                          </div>
                          <div class="col-6">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar text-right" id="numIva" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0" disabled>
                          </div>
                          <div class="col-6">
                            <label for="numTot">Total</label>
                          </div>
                          <div class="col-6">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar text-right" id="numTot" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0" disabled>
                          </div>
                          <div class="col-6">
                            <label for="numDedu">Imp. Combust.</label>
                          </div>
                          <div class="col-6">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar text-right" id="numDedu" placeholder="0.00" oninput="numberDec(this, 14, 2);" min="0" disabled>
                          </div>
                        </div>

                        <div class="form-row">
                          <div class="col-12 mt-2">
                            <button class="btn btn-info btn-block" id="btnGuardarImprimir" type="button">Guardar / Imprimir</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="btnBorrar" type="button">Borrar</button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </form>

              </div>

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

<script>
  var pressEnter = false;
  var nuevo = true;
  var nuevoProvee = true;
  var tblPolAnt;
  var rfecAnt = "0000-00-00";
  var mesCerrado = false;
  var btnAddEdit = "00";
  var inputCtaMov = "txtCta";
  var inputProvee = "txtNit"
  var proco ="";
  var mod = "";

  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;

  const txtSerie = document.thisform.txtSerie;
  const numNum = document.thisform.numNum;
  const txtNit = document.thisform.txtNit;
  const selTipo = document.thisform.selTipo;
  const txtProv = document.thisform.txtProv;
  const dtFec = document.thisform.dtFec;
  const selMes = document.thisform.selMes;
  const numAno = document.thisform.numAno;

  const crRet = document.thisform.crRet;
  const crReti = document.thisform.crReti;
  const crCaja = document.thisform.crCaja;
  const crAfe = document.thisform.crAfe;
  const numBien = document.thisform.numBien;
  const numServ = document.thisform.numServ;
  const numPeque = document.thisform.numPeque;
  const numPeque2 = document.thisform.numPeque2;
  const numImp = document.thisform.numImp;
  const numImpre = document.thisform.numImpre;
  const numTasam = document.thisform.numTasam;
  const numMedi = document.thisform.numMedi;
  const numNoafe = document.thisform.numNoafe;
  const numVehi = document.thisform.numVehi;
  const numVehia = document.thisform.numVehia;
  const crTvehi = document.thisform.crTvehi;
  const numTfacom = document.thisform.numTfacom;
  const numGalos = document.thisform.numGalos;
  const numGalor = document.thisform.numGalor;
  const numGalod = document.thisform.numGalod;
  const txtCon = document.thisform.txtCon;

  // TOTALES
  const numRet = document.thisform.numRet;
  const numReti = document.thisform.numReti;
  const numSub = document.thisform.numSub;
  const numIva = document.thisform.numIva;
  const numTot = document.thisform.numTot;

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

  function restriccion(consultar = false, mes = true){
    if (!consultar) {
      if (isNullPer(txtSerie.value)) {
        txtSerie.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar la SERIE"}});
        return true;
      }
      if (isNullPer(numNum.value)) {
        numNum.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NÚMERO"}});
        return true;
      }
      if (isNullPer(txtNit.value)) {
        txtNit.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NIT"}});
        return true;
      }
      if (mes) {
        if (restriccionMesCerrado()) {
          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 NO DEFINIDA
      var ctaInc = false;
      $("#tblPol tbody tr").each(function(){
        if ($(this).find("td:eq(1)").text().includes("XXXX")) {
          ctaInc = true;
          return false;
        }
      });
      if (ctaInc) {
        alWarning({"msg":{"title":"Cuenta Incorrecta","text":"Alguna cuenta de la partida no está asignada correctamente, verifique"}});
        return true;
      }
    } else {
      if (isNullPer(txtSerie.value) || isNullPer(numNum.value) || isNullPer(txtNit.value)) {
        return true;
      }
    }
    return false;
  }

  function restriccionCamposVacios() {
    if (isNullPer(txtSerie.value)) {
      txtSerie.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar la SERIE"}});
      return true;
    }
    if (isNullPer(numNum.value)) {
      numNum.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NÚMERO"}});
      return true;
    }
    if (isNullPer(txtNit.value)) {
      txtNit.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 restriccionCta() {
    if (isNullPer(txtCta.value)) {
      txtCtaNom.value = "";
      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'>"
                  +"<div class='btn-group btn-group-sm' role='group' aria-label='Third group'>"
                    +"<button type='button' class='btn btn-danger btn-sm btn-actions' id='btnDel'><i class='fas fa-trash-alt'></i></button>"
                    +"<button type='button' class='btn btn-primary btn-sm btn-actions' id='btnEdit' data-toggle='modal' data-target='#modalPol'><i class='fas fa-edit'></i></button>"
                  +"</div>"
                +"</td>"
                +"<td id='dataCta'>"+cta+"</td>"
                +"<td id='dataCtaNom'>"+ctaNom+"</td>"
                +"<td id='dataDebe' class='text-right'>"+debe+"</td>"
                +"<td id='dataHaber' class='text-right'>"+haber+"</td>"
                +"</tr>";
    $("#tblPol tbody").append(row);
  }

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

    calcular();

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

    const serie = txtSerie.value;
    const num = numNum.value;
    const nit = txtNit.value;

    const parametros = new FormData();
    parametros.append("action", "guardar");
    parametros.append("nuevo", nuevo);
    parametros.append("nuevoProvee", nuevoProvee);
    parametros.append("txtSerie", serie);
    parametros.append("numNum", num);
    parametros.append("txtNit", nit);
    parametros.append("selTipoCod", selTipo.value);
    parametros.append("txtProv", txtProv.value);
    parametros.append("dtFec", dtFec.value);
    parametros.append("selMesCod", selMes.value);
    parametros.append("numAno", numAno.value);
    parametros.append("rfecAnt", rfecAnt);
    parametros.append("selBanCod", selBan.value);
    parametros.append("numCheque", numCheque.value);
    parametros.append("crRet", crRet.value);
    parametros.append("crReti", crReti.value);
    parametros.append("crCaja", crCaja.value);
    parametros.append("crAfe", crAfe.value);
    parametros.append("numBien", numBien.value);
    parametros.append("numServ", numServ.value);
    parametros.append("numPeque", numPeque.value);
    parametros.append("numPeque2", numPeque2.value);
    parametros.append("numImp", numImp.value);
    parametros.append("numImpre", numImpre.value);
    parametros.append("numTasam", numTasam.value);
    parametros.append("numMedi", numMedi.value);
    parametros.append("numNoafe", numNoafe.value);
    parametros.append("numVehi", numVehi.value);
    parametros.append("numVehia", numVehia.value);
    parametros.append("crTvehi", crTvehi.value);
    parametros.append("numTfacom", numTfacom.value);
    parametros.append("numGalos", numGalos.value);
    parametros.append("numGalor", numGalor.value);
    parametros.append("numGalod", numGalod.value);
    parametros.append("numComb", numComb.value);
    parametros.append("txtCon", txtCon.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("deduTot", deduTot);


    parametros.append("numRet", numRet.value);
    parametros.append("numReti", numReti.value);
    parametros.append("numSub", numSub.value);
    parametros.append("numIva", numIva.value);
    parametros.append("numTot", numTot.value);

    parametros.append("tblPol", tblToJson(colPol, "tblPol", 0));
    parametros.append("tblPolAnt", tblPolAnt);
    parametros.append("mod", mod);
    parametros.append("proco", proco);


    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 {
          if (imprimir) {
            imprimirCompra(serie, num, nit);
          }
          alSuccess(jsonJS);
        }
      }
    });
  }

  function imprimirCompra(serie, num, nit){
    colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

    const getSerie = "?txtSerie="+serie;
    const getNum = "&numNum="+num;
    const getNit = "&txtNit="+nit;
    var url = window.location.origin+window.location.pathname+"print.php"+getSerie+getNum+getNit;

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

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

  function limpiar() {
    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;

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

    dtFec.value = dateToday();
    //selMes.value = <?php echo $mesTrab; ?>;
    //numAno.value = <?php echo $anoTrab; ?>;
    selBan.value = 0;
    numCheque.value = 0;
    //var fec = new Date(dtFec.value);
    //var m = fec.getMonth() + 1;
    //selMes.value=m;

   /* numBien.value=0;
    numServ.value=0;
    numPeque.value=0;
    numPeque2.value=0;
    numImp.value=0;
    numImpre.value=0;
    numTasam.value=0;
    numMedi.value=0;
    numNoafe.value=0;
    numVehi.value=0;
    numVehia.value=0;
    numTfacom.value=0;
    numGalos.value=0;
    numGalor.value=0;
    numGalod.value=0;
    numComb.value=0; */
    txtCon.value="";
    crRet.value = "N";
    crReti.value = "N";
    crCaja.value = "N";
    crAfe.value = "S";
    crTvehi1.checked = false;
    crTvehi2.checked = false;

    tblClear("tblPol");
    sumPol();
  }

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

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

      deduTot=deduSuper+deduRegu+deduDiesel;
    } else {
      deduTot=0;
    }
    numDedu.value=deduTot.toFixed(2);
  }

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

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

    // RESTRINGIR EL DOCUMENTO YA SEA EN NEGATIVO O EN POSITIVO
    pone = ($('#selTipo').find('option:selected').data('pone')=="N") ? -1 : 1;
    const bien=(numBien.value)*(pone*(Math.sign(numBien.value)));
    const serv=(numServ.value)*(pone*(Math.sign(numServ.value)));
    const peque=(numPeque.value)*(pone*(Math.sign(numPeque.value)));
    const peque2=(numPeque2.value)*(pone*(Math.sign(numPeque2.value)));
    const imp=(numImp.value)*(pone*(Math.sign(numImp.value)));
    const impre=(numImpre.value)*(pone*(Math.sign(numImpre.value)));
    const tasam=(numTasam.value)*(pone*(Math.sign(numTasam.value)));
    const medi=(numMedi.value)*(pone*(Math.sign(numMedi.value)));
    const noafe=(numNoafe.value)*(pone*(Math.sign(numNoafe.value)));
    const vehi=(numVehi.value)*(pone*(Math.sign(numVehi.value)));
    comb*=pone*(Math.sign(comb));

    // 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 (numVehia.value<4 && numVehia.value>1 && crTvehi.value=="C") {
      ivaVehi=1000;
    } else if (numVehia.value<4 && numVehia.value>1 && crTvehi.value=="M") {
      ivaVehi=300;
    } else if (numVehia.value>3 && crTvehi.value=="C") {
      ivaVehi=500;
    } else if (numVehia.value>3 && crTvehi.value=="M") {
      ivaVehi=200;
    } else if (numVehia.value<2 && (crTvehi.value=="C" || crTvehi.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 ($('#selTipo').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 (crRet.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 (crReti.value=="S") {
        reti=(iva*<?php echo $_SESSION["pRiva"]; ?>)/100;
      }
    }

    numBien.value = numberFixedEmpty(bien);
    numServ.value = numberFixedEmpty(serv);
    numPeque.value = numberFixedEmpty(peque);
    numPeque2.value = numberFixedEmpty(peque2);
    numImp.value = numberFixedEmpty(imp);
    numImpre.value = numberFixedEmpty(impre);
    numTasam.value = numberFixedEmpty(tasam);
    numMedi.value = numberFixedEmpty(medi);
    numNoafe.value = numberFixedEmpty(noafe);
    numVehi.value = numberFixedEmpty(vehi);
    numComb.value = numberFixedEmpty(comb);
    numTfacom.value = numberFixedEmpty(Number(numTfacom.value));
    numGalos.value = numberFixedEmpty(Number(numGalos.value), 3);
    numGalor.value = numberFixedEmpty(Number(numGalor.value), 3);
    numGalod.value = numberFixedEmpty(Number(numGalod.value), 3);
  }

  $(document).ready(function() {
    $(this).find('input:visible:first').focus();
    dtFec.value = dateToday();
    //selMes.value = <?php echo $mesTrab; ?>;
    numAno.value = <?php echo $anoTrab; ?>;
    var fec = new Date(dtFec.value);
    var m = fec.getMonth() + 1;
    selMes.value=m;
    
    selBan.value = 0;
    numCheque.value = 0;
    /*numBien.value=0;
    numServ.value=0;
    numPeque.value=0;
    numPeque2.value=0;
    numImp.value=0;
    numImpre.value=0;
    numTasam.value=0;
    numMedi.value=0;
    numNoafe.value=0;
    numVehi.value=0;
    numVehia.value=0;
    numTfacom.value=0;
    numGalos.value=0;
    numGalor.value=0;
    numGalod.value=0;
    numComb.value=0; */
    txtCon.value="";
    crRet.value = "N";
    crReti.value = "N";
    crCaja.value = "N";
    crAfe.value = "S";
    crTvehi1.checked = false;
    crTvehi2.checked = false;


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

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

    // CLICK PILLS-2
    $('#pills-1-tab').click(function (){
      console.log("asdf")
      if (isNullPer(txtSerie.value)) {
        document.getElementById('pills-0-tab').click();
        txtSerie.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar la SERIE"}});
        return true;
      }
      if (isNullPer(numNum.value)) {
        numNum.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NÚMERO"}});
        return true;
      }
    });

    // VALID SERIE, NUM
    $("#txtSerie, #numNum").focus(function (){
      numNum.value = "";
      txtNit.value = "";
      txtProv.value = "";
      limpiar();
    });

    // VALID NIT
    $("#txtNit")
    .focus(function() {
      inputProvee = $(this).attr('id');
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-1-tab").click(); }
    })
    .change(function (){
      const parametros = new FormData();
      parametros.append("action", "consultarProvee");
      parametros.append("txtNit", txtNit.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);
            nuevoProvee = true;
          } else {
            if (jsonJS.provee === null) {
              nuevoProvee = true;
              txtProv.value = "";
            } else {
              txtProv.value = jsonJS.provee.pro_nom;
              nuevoProvee = false;
            }
          }
        }
      });
    });

    // VALID SERIE, NUMERO, NIT
    $("#txtSerie, #numNum, #txtNit")
    .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })
    .change(function (){
      if (restriccion(true)) {return};
      //setTimeout(function(){
        txtNext = selTipo;

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

        parametros.append("txtSerie", txtSerie.value);
        parametros.append("numNum", numNum.value);
        parametros.append("txtNit", txtNit.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) {
            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.iva_comp === null) {
                mesCerrado = false;
              } else {
                if (jsonJS.iva_comp.ciem_stat === "C") {
                  mesCerrado = true;
                } else {
                  mesCerrado = false;
                }
              }
              
              if (jsonJS.iva_comp === null) {
                nuevo = true;
                rfecAnt = "0000-00-00";
                proco = "";
                mod = "";
              } else {
                selTipo.value = jsonJS.iva_comp.iva_tipo;
                txtProv.value = jsonJS.iva_comp.iva_prov;
                dtFec.value = jsonJS.iva_comp.iva_fec;
                proco = jsonJS.iva_comp.iva_proco;
                mod = jsonJS.iva_comp.iva_mod;

                // FECHA A REPORTAR
                const d = YMDToDate(jsonJS.iva_comp.iva_rfec);
                selMes.value = d.getMonth()+1;
                numAno.value = d.getFullYear();
                rfecAnt = jsonJS.iva_comp.iva_rfec;

                selBan.value = jsonJS.iva_comp.iva_ban;
                numCheque.value = jsonJS.iva_comp.iva_cheque;

                crRet.value = jsonJS.iva_comp.iva_retsn;
                crReti.value = jsonJS.iva_comp.iva_retisn;
                crCaja.value = jsonJS.iva_comp.iva_caja;
                crAfe.value = jsonJS.iva_comp.iva_afe;
                numBien.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_bien));
                numServ.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_serv));
                numPeque.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_peque));
                numPeque2.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_peque2));
                numImp.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_imp));
                numImpre.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_impre));
                numTasam.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_tasam));
                numMedi.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_medi));
                numNoafe.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_noafe));
                numVehi.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_vehi));
                numVehia.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_vehia));
                crTvehi.value = jsonJS.iva_comp.iva_tvehi;
                numTfacom.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_tfacom));
                numGalos.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_galos), 3);
                numGalor.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_galor), 3);
                numGalod.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_galod), 3);
                numComb.value = numberFixedEmpty(Number(jsonJS.iva_comp.iva_comb));
                txtCon.value = jsonJS.iva_comp.iva_con;

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

                // TOTALES
                numRet.value=ret.toFixed(2);
                numReti.value=reti.toFixed(2);
                numSub.value=sub.toFixed(2);
                numIva.value=iva.toFixed(2);
                numTot.value=tot.toFixed(2);

                jsonJS.poli_det.forEach(function(i){
                  addRowPol(i.pold_cta, i.pold_ctan, i.pold_debe, i.pold_haber);
                });
                sumPol();
                nuevo = false;
              }
              (pressEnter) ? alClose() : alCloseFocus(txtNext);
              pressEnter = false;
            }
          }
        });
      //},0);
    });

    // VALID MES
    $("#selMes, #numAno").change(function (){
      const parametros = new FormData();
      parametros.append("action", "consultarCiemes");
      parametros.append("numAno", numAno.value);
      parametros.append("selMesCod", selMes.value);

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

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

    $(".calcular").change(function (){
      calcular();
      numRet.value=ret.toFixed(2);
      numReti.value=reti.toFixed(2);
      numSub.value=sub.toFixed(2);
      numIva.value=iva.toFixed(2);
      numTot.value=tot.toFixed(2);
    });

    // FOCUS INPUT
    $("form[name='thisform'] input, select, textarea, #btnPartida").focus(function (){
      if (!($("input:visible:first").is(":focus")) && !($("#numNum").is(":focus")) && !($("#txtNit").is(":focus"))) {
        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};
      const fnT = function(){
        colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

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

        parametros.append("txtSerie", txtSerie.value);
        parametros.append("numNum", numNum.value);
        parametros.append("txtNit", txtNit.value);
        parametros.append("selBanCod", selBan.value);
        parametros.append("rfecAnt", rfecAnt);
        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();
              $("#btnBorrar").focus(function (){
                numNum.focus();
              });
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

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

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

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

      parametros.append("numIva", numIva.value);
      parametros.append("deduTot", deduTot);
      parametros.append("numRet", numRet.value);
      parametros.append("numReti", numReti.value);

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            tblClear("tblPol");
            sumPol();
            
            if ($('#selTipo').find('option:selected').data('pone')!="N") {
              addRowPol("XXXXXXX", "Ingrese cuenta de gastos", numSub.value, "0.00");

              // Cuenta IVA
              if (numIva.value != 0) {
                if (!isNullPer(jsonJS.ctaIva)) {
                  addRowPol(jsonJS.ctaIva.cta, jsonJS.ctaIva.cta_nom, numIva.value, "0.00");
                } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta de IVA", numIva.value, "0.00");
                }
              }

              // Cuenta Impuesto Combustible
              if (deduTot != 0) {
                if (!isNullPer(jsonJS.ctaComb)) {
                  addRowPol(jsonJS.ctaComb.cta, jsonJS.ctaComb.cta_nom, deduTot.toFixed(2), "0.00");
                } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta Imp. Combustible", deduTot.toFixed(2), "0.00");
                }
              }

              // Cuenta Retención de ISR
              if (numRet.value != 0) {
                if (!isNullPer(jsonJS.ctaRet)) {
                  addRowPol(jsonJS.ctaRet.cta, jsonJS.ctaRet.cta_nom, "0.00", numRet.value);
                } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta de Retención de ISR", "0.00", numRet.value);
                }
              }

              // Cuenta Retención de IVA
              if (numReti.value != 0) {
                if (!isNullPer(jsonJS.ctaReti)) {
                  addRowPol(jsonJS.ctaReti.cta, jsonJS.ctaReti.cta_nom, "0.00", numReti.value);
                } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta de Retención de IVA", "0.00", numReti.value);
                }
              }

              // Cuenta Caja
              if (!isNullPer(jsonJS.ctaCaj)) {
                addRowPol(jsonJS.ctaCaj.cta, jsonJS.ctaCaj.cta_nom, "0.00", ((tot+deduTot)-(Number(ret.toFixed(2))+Number(reti.toFixed(2)))).toFixed(2));
              } else {
                addRowPol("XXXXXXX", "Cuenta no definida", "0.00", ((tot+deduTot)-(Number(ret.toFixed(2))+Number(reti.toFixed(2)))).toFixed(2));
              }
            } else {
              // Cuenta Caja
              if (!isNullPer(jsonJS.ctaCaj)) {
                addRowPol(jsonJS.ctaCaj.cta, jsonJS.ctaCaj.cta_nom, ((tot+deduTot)*-1).toFixed(2), "0.00");
              } else {
                addRowPol("XXXXXXX", "Cuenta no definida", ((tot+deduTot)*-1).toFixed(2)), "0.00";
              }

              // Cuenta IVA
              if (numIva.value != 0) {
                if (!isNullPer(jsonJS.ctaIva)) {
                  addRowPol(jsonJS.ctaIva.cta, jsonJS.ctaIva.cta_nom, "0.00", (numIva.value*-1).toFixed(2));
                } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta de IVA", "0.00", (numIva.value*-1).toFixed(2));
                }
              }

              addRowPol("XXXXXXX", "Ingrese cuenta de gastos", "0.00", (numSub.value*-1).toFixed(2));
            }
            sumPol();
            alClose();
          }
        }
      });
    });

    // CLICK IMPRIMIR
    $("#btnGuardarImprimir").click(function (){
      guardarCompra(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};
    $('#modalPol').modal('toggle');
    $("#pills-00-tab").text("Agregar");
    $("#btnAgregar").show();
    $("#btnModificar").hide();
    limpiarModalPol();
  });

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

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

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

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

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

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

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

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

</script>