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

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

# EJECUCION DE QUERYS
$db = new dbExec();
$select["tipov"] = $db->query($sTipov);
$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 Cliente</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 Serie</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-md-7">
                            <div class="form-row">
                              <div class="col-12 col-sm-6">
                                <label for="selTipo">Tipo</label>
                                <select class="form-control form-control-sm form-control-as" name="selTipo" id="selTipo">
                                  <?php
                                    while ($rec = $db->fetchAssoc($select['tipov'])) {
                                      echo  '<option value="'.$rec['tv_cod'].'" data-impues="'.$rec['tv_impues'].'" data-pone="'.$rec['tv_pone'].'" data-librosn="'.$rec['tv_librosn'].'" data-seriesn="'.$rec['tv_seriesn'].'" data-abrev="'.$rec['tv_abrev'].'">'.utf8_encode($rec['tv_nom']).'</option>';
                                    }
                                  ?>
                                </select>
                              </div>
                              <div class="col-12 col-sm-6">
                                <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">
                                <label for="numNum">Número</label>
                                <input type="number" class="form-control form-control-sm form-control-as dec-0" id="numNum" placeholder="0" min="1">
                              </div>
                              <div class="col-12 col-sm-6" id="venRango">
                                <label for="numNumf">Al número</label>
                                <input type="number" class="form-control form-control-sm form-control-as dec-0" id="numNumf" placeholder="0" min="1">
                              </div>
                              <div class="col-12 col-sm-6">
                                <label for="txtNit">Nit</label>
                                <input type="text" class="form-control form-control-sm form-control-as limpiar" id="txtNit" maxlength="20">
                              </div>
                            </div>
                          </div>
                          <div class="col-md-5 text-center">
                            <div class="row">
                              <div class="col-12">
                                <label class="pr-1">Venta por rango</label><br>
                                <div class="custom-control custom-radio custom-control-inline">
                                  <input type="radio" id="crVenRango1" name="crVenRango" class="custom-control-input" value="S">
                                  <label class="custom-control-label" for="crVenRango1">Si</label>
                                </div>
                                <div class="custom-control custom-radio custom-control-inline">
                                  <input type="radio" id="crVenRango2" name="crVenRango" class="custom-control-input" value="N">
                                  <label class="custom-control-label" for="crVenRango2">No</label>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>

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

                        <div class="form-row align-items-center text-center">
                          <div class="col-6 col-md-3 text-left">
                            <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-6 col-md-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-6 col-md-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-6 col-md-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">Ventas</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numBien" placeholder="0.00" 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" min="0">
                          </div>
                          <div class="col-6 col-sm-3">
                            <label for="numExen">Ventas Exentas</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numExen" placeholder="0.00" min="0">
                          </div>
                          <div class="col-6 col-sm-3">
                            <label for="numExp">Exportación Centro América</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numExp" placeholder="0.00" min="0">
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-6 col-sm-3">
                            <label for="numExpre">Exportación Resto del Mundo</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numExpre" placeholder="0.00" 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" min="0">
                          </div>
                          <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" 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" min="0">
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <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="numTfaco">Total de Factura Combustible</label>
                            <input type="number" class="form-control form-control-sm form-control-as calcular limpiar" id="numTfaco" placeholder="0.00" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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('../busClien/index.html')
                ?>
              </div>
              <div class="tab-pane fade" id="pills-2" role="tabpanel" aria-labelledby="pills-2-tab">
                <?php
                  $a='0';
                  $b='2';
                  include('../busTipov/index.html')
                ?>
              </div>

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

<script>
  var pressEnter = false;
  var nuevo = true;
  var nuevoClien = true;
  var tblPolAnt;
  var fecAnt = "0000-00-00";
  var mesCerrado = false;
  var btnAddEdit = "00";
  var inputCtaMov = "txtCta";
  var inputClien = "txtNit"
  var inputTipov = "selTipo"

  var subb=0;
  var subs=0;
  var subex=0;
  var subco=0;
  var subve=0;
  var sube=0;
  var suber=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 txtClin = document.thisform.txtClin;
  const dtFec = document.thisform.dtFec;

  const crRet = document.thisform.crRet;
  const crReti = document.thisform.crReti;
  const crAfe = document.thisform.crAfe;
  const numBien = document.thisform.numBien;
  const numServ = document.thisform.numServ;
  const numExen = document.thisform.numExen;
  const numExp = document.thisform.numExp;
  const numExpre = document.thisform.numExpre;
  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 numTfaco = document.thisform.numTfaco;
  const numGalos = document.thisform.numGalos;
  const numGalor = document.thisform.numGalor;
  const numGalod = document.thisform.numGalod;
  const txtCon = document.thisform.txtCon;

  const crVenRango = document.thisform.crVenRango;

  // 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(selTipo.value)) {
        selTipo.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el TIPO"}});
        return true;
      }
      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 (numNumf.value=="") {
        numNumf.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 && ('<?php echo $_SESSION["empPequesn"]; ?>' != 'S')) {
        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)) {
        return true;
      }
    }
    return false;
  }

  function restriccionCamposVacios() {
    if (isNullPer(selTipo.value)) {
      selTipo.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el TIPO"}});
      return true;
    }
    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 (numNumf.value=="") {
      numNumf.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NÚMERO"}});
      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 guardarVenta(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("nuevoClien", nuevoClien);
    parametros.append("selTipoCod", selTipo.value);
    parametros.append("txtSerie", serie);
    parametros.append("numNum", num);
    parametros.append("numNumf", numNumf.value);
    parametros.append("crVenRango", crVenRango.value);
    parametros.append("txtNit", nit);
    parametros.append("txtClin", txtClin.value);
    parametros.append("dtFec", dtFec.value);
    parametros.append("fecAnt", fecAnt);
    parametros.append("crRet", crRet.value);
    parametros.append("crReti", crReti.value);
    parametros.append("crAfe", crAfe.value);
    parametros.append("numBien", numBien.value);
    parametros.append("numServ", numServ.value);
    parametros.append("numExen", numExen.value);
    parametros.append("numExp", numExp.value);
    parametros.append("numExpre", numExpre.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("numTfaco", numTfaco.value);
    parametros.append("numGalos", numGalos.value);
    parametros.append("numGalor", numGalor.value);
    parametros.append("numGalod", numGalod.value);
    parametros.append("numComb", numComb.value);
    parametros.append("deduTot", deduTot);
    parametros.append("txtCon", txtCon.value);

    parametros.append("subb", subb);
    parametros.append("subs", subs);
    parametros.append("subex", subex);
    parametros.append("subco", subco);
    parametros.append("subve", subve);
    parametros.append("sube", sube);
    parametros.append("suber", suber);
    parametros.append("subna", subna);
    parametros.append("subme", subme);

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

    numNum.value = Number(numNum.value)+1;
    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) {
            imprimirVenta(serie, num);
          }
          alSuccess(jsonJS);
        }
      }
    });
  }

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

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

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

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

  function limpiar() {
    subb=0;
    subs=0;
    subex=0;
    subco=0;
    subve=0;
    sube=0;
    suber=0;
    subna=0;
    subme=0;

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

    numNumf.value=0;

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

    dtFec.value = dateToday();
    crRet.value = "N";
    crReti.value = "N";
    crAfe.value = "S";
    crTvehi1.checked = false;
    crTvehi2.checked = false;
    $("#crVenRango2").click();

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

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

  function calculoDedu(){
    if (!isNullPer(numTfaco.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;
    }
  }

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

    // CALCULO COMBUSTIBLE
    calculoDedu();
    var comb = numTfaco.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 exen=(numExen.value)*(pone*(Math.sign(numExen.value)));
    const exp=(numExp.value)*(pone*(Math.sign(numExp.value)));
    const expre=(numExpre.value)*(pone*(Math.sign(numExpre.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;
    subex=exen;
    subco=comb;
    subve=vehi;
    sube=exp;
    suber=expre;
    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+exp+expre+exen+medi+vehi+noafe+comb;
    sub=subb+subs+sube+suber+subex+subme+subve+subna+subco;
    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+sube+suber+subex+subme+subve+subna+subco;
        iva=tot-sub;
        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;
      }
    }

    //
    // Cuando la empresa es pequeño contribuyente
    if ('<?php echo $_SESSION["empPequesn"]; ?>' == 'S') {
        subb=bien;
        subs=serv;
        subco=comb;

        sub=tot;
        iva=round((tot*pIva/100),2);
        iva+=ivaVehi;
    }

    numBien.value = numberFixedEmpty(bien);
    numServ.value = numberFixedEmpty(serv);
    numExen.value = numberFixedEmpty(exen);
    numExp.value = numberFixedEmpty(exp);
    numExpre.value = numberFixedEmpty(expre);
    numMedi.value = numberFixedEmpty(medi);
    numNoafe.value = numberFixedEmpty(noafe);
    numVehi.value = numberFixedEmpty(vehi);
    numComb.value = numberFixedEmpty(comb);
    numTfaco.value = numberFixedEmpty(Number(numTfaco.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('select:visible:first').focus();
    dtFec.value = dateToday();
    crRet.value = "N";
    crReti.value = "N";
    crAfe.value = "S";
    $('#crVenRango2').click();
    $('#venRango').hide();
    numNumf.value=0;

    // 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 (){
      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 SELTIPO
    $("#selTipo")
    .focus(function() {
      inputTipov = $(this).attr('id');
      console.log(inputTipov);
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-2-tab").click(); }
    })
    .change(function (){
      if (($('#selTipo').find('option:selected').data('seriesn')!="N")) {
        txtSerie.disabled = false;
        txtSerie.value = "";
      } else {
        txtSerie.disabled = true
        txtSerie.value = $('#selTipo').find('option:selected').data('abrev');
      }
      console.log("A "+selTipo.value);
      const parametros = new FormData();
      parametros.append("action", "consultarTipov");
      parametros.append("selTipo", selTipo.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.tiopov === null) {
            } else {
              selTipo.value = jsonJS.tipov.tv_cod;
              if (($('#selTipo').find('option:selected').data('seriesn')=="N")) {
                txtSerie.value = jsonJS.tipov.tv_nom;
              }
            }
          }
        }
      });
    });

    // VALID TIPOV
 /*
    $("#selTipo").blur(function (){
      if (($('#selTipo').find('option:selected').data('seriesn')!="N")) {
        txtSerie.disabled = false;
        txtSerie.value = "";
      } else {
        txtSerie.disabled = true
        txtSerie.value = $('#selTipo').find('option:selected').data('abrev');
      }
    });
*/
    // VALID SERIE, NUM
    $("#numNum").focus(function (){
      limpiar();
    });
    $("#selTipo, #txtSerie").focus(function (){
      limpiar();
    });

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

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

        const parametros = new FormData();
        parametros.append("action", "consultar");
        parametros.append("selTipoCod", selTipo.value);
        parametros.append("txtSerie", txtSerie.value);
        parametros.append("numNum", numNum.value);

        txtNext.focus();

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

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

              if (isNullPer(jsonJS.iva_ven)) {
                mesCerrado = false;
              } else {
                if (jsonJS.iva_ven.ciem_stat === "C") {
                  mesCerrado = true;
                } else {
                  mesCerrado = false;
                }
              }
              
              if (isNullPer(jsonJS.iva_ven)) {
                nuevo = true;
                fecAnt = "0000-00-00";
              } else {
                txtNit.value = jsonJS.iva_ven.ivav_nit;
                txtClin.value = jsonJS.iva_ven.ivav_clin;
                dtFec.value = jsonJS.iva_ven.ivav_fec;
                fecAnt = jsonJS.iva_ven.ivav_fec;

                crRet.value = jsonJS.iva_ven.ivav_retsn;
                crReti.value = jsonJS.iva_ven.ivav_retisn;
                crAfe.value = jsonJS.iva_ven.ivav_afe;
                numBien.value = numberFixedEmpty(Number(jsonJS.iva_ven.ivav_bien));
                numServ.value = numberFixedEmpty(Number(jsonJS.iva_ven.ivav_serv));
                numExen.value = numberFixedEmpty(Number(jsonJS.iva_ven.ivav_exen));
                numExp.value = numberFixedEmpty(Number(jsonJS.iva_ven.ivav_exp));
                numExpre.value = numberFixedEmpty(Number(jsonJS.iva_ven.ivav_expre));
                numMedi.value = numberFixedEmpty(Number(jsonJS.iva_ven.ivav_medi));
                numNoafe.value = numberFixedEmpty(Number(jsonJS.iva_ven.ivav_noafe));
                numVehi.value = numberFixedEmpty(Number(jsonJS.iva_ven.ivav_vehi));
                numVehia.value = numberFixedEmpty(Number(jsonJS.iva_ven.ivav_vehia));
                crTvehi.value = jsonJS.iva_ven.ivav_tvehi;
                numTfaco.value = numberFixedEmpty(Number(jsonJS.iva_ven.ivav_tfaco));
                numGalos.value = numberFixedEmpty(Number(jsonJS.iva_ven.ivav_galos), 3);
                numGalor.value = numberFixedEmpty(Number(jsonJS.iva_ven.ivav_galor), 3);
                numGalod.value = numberFixedEmpty(Number(jsonJS.iva_ven.ivav_galod), 3);
                numComb.value = numberFixedEmpty(Number(jsonJS.iva_ven.ivav_comb));
                txtCon.value = jsonJS.iva_ven.ivav_con;

                (jsonJS.iva_ven.ivav_venrango == 'S') ? $("#crVenRango1").click() : $("#crVenRango2").click();
                numNumf.value = jsonJS.iva_ven.ivav_numf;

                calculoDedu();
                tot=Number(jsonJS.iva_ven.ivav_tot);
                sub=Number(jsonJS.iva_ven.ivav_sub);
                iva=Number(jsonJS.iva_ven.ivav_iva);
                ret=Number(jsonJS.iva_ven.ivav_ret);
                reti=Number(jsonJS.iva_ven.ivav_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);
              alCloseFocus(txtNext);
              pressEnter = false;
            }
          }
        });
      //},0);
    });

    // VALID FECHA
    $("#dtFec").blur(function (){
      const d = new Date(dtFec.value);
      const numAno = d.getFullYear();
      const numMes = d.getMonth()+1;

      const parametros = new FormData();
      parametros.append("action", "consultarCiemes");
      parametros.append("numAno", numAno);
      parametros.append("selMesCod", numMes);

      $.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.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);
    });

    // VALID FACTURAR POR RANGO
    $("input[name=crVenRango]").change(function (){
      if (this.value=='S') {
        $('#venRango').show(500);
        $('label[for=numNum]').text("Del número");
        numNumf.value="";
      } else {
        $('label[for=numNum]').text("Número");
        $('#venRango').hide(500);
        numNumf.value=0;
        numNum.focus();
      }
    });

    // FOCUS INPUT
    $("form[name='thisform'] input, select, textarea, #btnPartida").focus(function (){
      if (!($("input:visible:first").is(":focus")) && !($("#numNum").is(":focus")) && !($("#numNumf").is(":focus")) && !($("#txtNit").is(":focus")) && !($("#selTipo").is(":focus")) && !($("#crVenRango1").is(":focus")) && !($("#crVenRango2").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("fecAnt", fecAnt);
        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) {
            console.log(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();
                  location.reload(true);
              });
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

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

    // CLICK PARTIDA
    $("#btnPartida").click(function (){
      if ($("#tblPol tbody").children().length != 0) {
        alWarning({"msg":{"title":"Ya existe partida","text":"La partida de este documento ya existe"}});
        return;
      }
      if ('<?php echo $_SESSION["empPequesn"]; ?>' == 'S') {
        alWarning({"msg":{"title":"No necesita Partida","text":"No necesita generar Partida, porque esta registrado como Pequeño Contribuyente"}});
        return true;
      }

      var vventas = sub-(subs+numExp.value+numExpre.value);
      var vexporta = (numExp.value+numExpre.value);

      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);
      parametros.append("numVen", vventas);
      parametros.append("numServ", subs);
      parametros.append("numExport", vexporta);

      $('#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") {
              // Cuenta Caja
              if (!isNullPer(jsonJS.ctaCaj)) {
                addRowPol(jsonJS.ctaCaj.cta, jsonJS.ctaCaj.cta_nom, ((tot+deduTot)-(Number(ret.toFixed(2))+Number(reti.toFixed(2)))).toFixed(2), "0.00");
              } else {
                addRowPol("XXXXXXX", "Cuenta no definida", ((tot+deduTot)-(Number(ret.toFixed(2))+Number(reti.toFixed(2)))).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, numRet.value, "0.00");
                } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta de Retención de ISR", numRet.value, "0.00");
                }
              }

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

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

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

              // Cuenta de ventas
              if (vventas != 0) {
                if (!isNullPer(jsonJS.ctaVen)) {
                  addRowPol(jsonJS.ctaVen.cta, jsonJS.ctaVen.cta_nom, "0.00", vventas.toFixed(2));
                } else {
                addRowPol("XXXXXXX", "Ingrese cuenta de ventas", "0.00", vventas.toFixed(2));
                }
              }

              // Cuenta Servicios
              if (subs != 0) {
                if (!isNullPer(jsonJS.ctaServ)) {
                  addRowPol(jsonJS.ctaServ.cta, jsonJS.ctaServ.cta_nom, "0.00", subs.toFixed(2));
                } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta de servicios", "0.00", subs.toFixed(2));
                }
              }
              // Cuenta de Exportaciones
              if (vexporta != 0) {
                if (!isNullPer(jsonJS.ctaExport)) {
                  addRowPol(jsonJS.ctaExport.cta, jsonJS.ctaExport.cta_nom, "0.00", Number(vexporta).toFixed(2));
                } else {
                addRowPol("XXXXXXX", "Ingrese cuenta de Exportaciones", "0.00", Number(vexporta).toFixed(2));
                }
              }
            } else {
              // Cuenta de ventas
              if (vventas != 0) {
                if (!isNullPer(jsonJS.ctaVen)) {
                  addRowPol(jsonJS.ctaVen.cta, jsonJS.ctaVen.cta_nom, (vventas*-1).toFixed(2),"0.00");
                } else {
                addRowPol("XXXXXXX", "Ingrese cuenta de ventas", "0.00", (vventas*-1).toFixed(2),"0.00");
                }
              }

              // Cuenta Servicios
              if (subs != 0) {
                if (!isNullPer(jsonJS.ctaServ)) {
                  addRowPol(jsonJS.ctaServ.cta, jsonJS.ctaServ.cta_nom, (subs*-1).toFixed(2), "0.00");
                } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta de servicios", (subs*-1).toFixed(2), "0.00");
                }
              }

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

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

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

    // CLICK IMPRIMIR
    $("#btnGuardarImprimir").click(function (){
      guardarVenta(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 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;
      console.log(target, relatedTarget)

      if (target == "#pills-1" && (isNullPer(txtSerie.value) || isNullPer(numNum.value))) {
        if (restriccionCamposVacios()) {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") {
        $(target+' input:visible:first').focus();
      } else 
      if (target == "#pills-0" && isNullPer(txtSerie.value)) {
        selTipo.focus();
//       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;
        (relatedTarget == "#pills-2") ? numNum.focus() : 0;
      }
      //$(target+' input:visible:first').focus();
    }
  });

</script>