<?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']."'";
$sSerieoc = "SELECT * FROM serieoc WHERE so_emp='".$_SESSION['empCod']."'";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["tipoc"] = $db->query($sTipoc);
$select["meses"] = $db->query($sMeses);
$select["bancos"] = $db->query($sBancos);
$select["serieoc"] = $db->query($sSerieoc);
$db->close();

$anoTrab=date("Y");
$mesTrab=date("m");
//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>

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

              <div class="tab-content bg-transparent border-0" id="pills-tabContent">
                <div class="tab-pane fade show active" id="pills-007" role="tabpanel" aria-labelledby="pills-007-tab">
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">
                      <div class="form-row">
                        <div class="col-md-4">
                          <label for="txtAcodlis">Codigo</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtAcodlis" disabled>
                        </div>
                        <div class="col-md-8">
                          <label for="txtAprovlis">Nombre Proveedor</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtAprovlis" disabled>
                        </div>
                      </div>
                      <div class="form-row">
                          <label> </label>
                      </div>
                      <div class="form-row">
                        <div class="col-md-12">
                          <div class="table-responsive">
                            <table class="table table-hover table-bordered table-dark table-xs table-striped" id="tblAntiLis">
                              <thead>
                                <tr>
                                  <th scope="col" class="text-center" width="80">No. ANTICIPO</th>
                                  <th scope="col" class="text-center" width="45">FEC/ANTICIPO</th>
                                  <th scope="col" class="text-center" width="70">T/CAMBIO</th>
                                  <th scope="col" class="text-center" width="100">VALOR</th>
                                  <th scope="col" class="text-center" width="60">TIPO/RELA</th>
                                  <th scope="col" class="text-center" width="70">DOCUMENTO RELACIONADO</th>
                                  <th scope="col" class="text-center" width="100">INCLUIR</th>
                                </tr>
                              </thead>
                              <tbody>
                              </tbody>
                              <tfoot>
                                <th scope="col"></th>
                                <th scope="col"></th>
                                <th scope="col" class="text-right">Totales</th>
                                <th scope="col" id="dataTotAntiLis" class="text-right">0.00</th>
                                <th scope="col"></th>
                                <th scope="col"></th>
                                <th scope="col"></th>
                              </tfoot>
                            </table>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="form-group">
                      <div class="form-row">
                        <div class="form-group col-4">
                        </div>
                        <div class="form-group col-4">
                          <button type="button" class="btn btn-warning btn-block" id="btnAsigAnti">Asignar Anticipo</button>
                        </div>
                      </div>
                    </div>

                  </form>

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

      <div class="container-as">
        <div class="row">
          <div class="col">
            <ul class="nav nav-pills mb-1" id="pills-tab" role="tablist">
              <li class="nav-item">
                <a class="nav-link active" id="pills-0-tab" data-toggle="pill" href="#pills-0" role="tab" aria-controls="pills-0" aria-selected="true">Mantenimiento</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" id="pills-1-tab" data-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="txtCodp">Codigo</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtCodp" maxlength="20">
                          </div>
                          <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="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'].'" data-partidasn="'.$rec['tc_partidasn'].'">'.utf8_encode($rec['tc_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                        </div>

                        <div class="form-row">
                          <div class="col-9">
                            <label for="txtProv">Proveedor</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtProv" maxlength="20" disabled>
                          </div>
                          <div class="col-3">
                            <label for="txtNit">Nit</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtNit" maxlength="20" disabled>
                          </div>
                        </div>

                        <div class="form-row">
                          <div class="col-md-2.5">
                            <label for="dtFec">Fecha Documento</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFec" placeholder="">
                          </div>
                          <div class="col-md-2.5">
                            <label for="dtFecrece">Fecha Recepcion</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFecrece" placeholder="">
                          </div>
                          <div class="col-md-2.5">
                            <label for="dtFecp">Fecha Pago</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFecp" placeholder="">
                          </div>

                          <div class="col-2">
                            <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>
                        <div class="form-row">
                          <div class="col-md-2.5">
                            <label for="numTcam">Tasa de Cambio</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numTcam" placeholder="0.000000" oninput="numberDec(this, 14, 6);">
                          </div>
                          <div class="col-md-2.5">
                            <label for="numContra">No. Contraseña</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numContra" placeholder="">
                          </div>
                          <div class="col-md-2.5">
                            <label for="dtFcontra">Fecha Contraseña</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFcontra" placeholder="">
                          </div>
                          <div class="col-2">
                            <label for="selOrden">Serie Orden</label>
                            <select class="form-control form-control-sm form-control-as" name="selOrden" id="selOrden">
                              <?php
                                while ($rec = $db->fetchAssoc($select['serieoc'])) {
                                  echo  '<option value="'.$rec['so_cod'].'">'.utf8_encode($rec['so_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-2">
                            <label for="numOrden">Número Orden</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numOrden" placeholder="">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-4">
                            <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-4">
                            <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-4">
                            <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="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 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="numAbo">OTROS ABONOS</label>
                          </div>
                          <div class="col-6">
                            <input type="number" class="form-control form-control-lg form-control-as form-info limpiar text-right dec-2" id="numAbo" 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 class="col-12 mt-2">
                            <button class="btn btn-warning btn-block" id="btnAnti" type="button">Asignar Anticipos</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('../busProvcp/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 inputProvcp = "txtCodp"

  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 txtCodp = document.thisform.txtCodp;
  const txtNit = document.thisform.txtNit;
  const selTipo = document.thisform.selTipo;
  const txtProv = document.thisform.txtProv;
  const dtFec = document.thisform.dtFec;
  const dtFecrece = document.thisform.dtFecrece;
  const dtFecp = document.thisform.dtFecp;
  const numTcam = document.thisform.numTcam;
  const numContra = document.thisform.numContra;
  const dtFcontra = document.thisform.dtFcontra;
  const selOrden = document.thisform.selOrden;
  const numOrden = document.thisform.numOrden;
  const numAbo = document.thisform.numAbo;

  const selMes = document.thisform.selMes;
  const numAno = document.thisform.numAno;

  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 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 addRowAntiLis(numdlis, fecdlis, tcamlis, vallis, tiporlis, numrlis, l){
    const row = "<tr>"
                  +"<td id='datanumdlis' class='text-left'>"+numdlis+"</td>"
                  +"<td id='datafecdlis' class='text-center'>"+YMDToDMY(fecdlis)+"</td>"
                  +"<td id='datatcamlis' class='text-right'>"+tcamlis+"</td>"
                  +"<td id='datavallis' class='text-right'>"+vallis+"</td>"
                  +"<td id='datatrelalis' class='text-center'>"+tiporlis+"</td>"
                  +"<td id='datanrelalis' class='text-left'>"+numrlis+"</td>"
                  +"<td class='text-center'>"
                    +"<div class='custom-control custom-checkbox'>"
                    +"<input type='checkbox' class='custom-control-input' id='dataCheck"+l+"' name='cb'>"
                    +"<label class='custom-control-label mt-0' for='dataCheck"+l+"'></label>"
                    +"</div>"
                  +"</td>"
                +"</tr>";
    $("#tblAntiLis tbody").append(row);
  }

  sumCajaLis();

  function sumCajaLis() {
    var acum = 0;

    $("#tblAntiLis").find('tbody tr').each(function () {
      if ($(this).find('td input[name="cb"]').is(":checked")){
         acum += parseFloat($(this).find('#datavallis').text());
      }  
    });
    $("#tblAntiLis #dataTotAntiLis").text(acum.toFixed(2));
  }

  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(txtCodp.value)) {
        txtCodp.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CODIGO"}});
        return true;
      }
      if (mes) {
        if (restriccionMesCerrado()) {
          return true;
        }
      }
      if ($("#dataTotDebe").text() != $("#dataTotHaber").text() && $('#selTipo').find('option:selected').data('partidasn') == 'S') {
        alWarning({"msg":{"title":"Valores Incorrectos","text":"La partida no cuadra, verifique los valores"}});
        return true;
      }
      // PARA VER SI LA PARTIDA ESTÁ VACÍA
      if ($("#tblPol tbody").children().length == 0 && $('#selTipo').find('option:selected').data('partidasn') == '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) || isNullPer(txtCodp.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(txtCodp.value)) {
      txtCodp.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CODIGO"}});
      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 cod = txtCodp.value;

    var Qbien = round((numBien.value*numTcam.value),2);
    var Qserv = round((numServ.value*numTcam.value),2);
    var Qpeque = round((numPeque.value*numTcam.value),2);
    var Qpeque2 = round((numPeque2.value*numTcam.value),2);
    var Qimp = round((numImp.value*numTcam.value),2);
    var Qimpre = round((numImpre.value*numTcam.value),2);
    var Qmedi = round((numMedi.value*numTcam.value),2);
    var Qtasam = round((numTasam.value*numTcam.value),2);
    var Qnoafe = round((numNoafe.value*numTcam.value),2);
    var Qvehi = round((numVehi.value*numTcam.value),2);
    var Qtfacom = round((numTfacom.value*numTcam.value),2);
    var Qcomb = round((numComb.value*numTcam.value),2);
    var Qsubb = round((subb*numTcam.value),2);
    var Qsubs = round((subs*numTcam.value),2);
    var Qsubpe = round((subpe*numTcam.value),2);
    var Qsubco = round((subco*numTcam.value),2);
    var Qsubve = round((subve.value*numTcam.value),2);
    var Qsubi = round((subi*numTcam.value),2);
    var Qsubir = round((subir*numTcam.value),2);
    var Qsubna = round((subna*numTcam.value),2);
    var Qsubme = round((subme*numTcam.value),2);

    var Qsub = round((numSub.value*numTcam.value),2);
    var Qtot = round(((numTot.value-numDedu.value)*numTcam.value),2);
    var Qiva = round((Qtot-Qsub),2);
    var Qdedu = round((deduTot*numTcam.value),2);
    var Qret = round((numRet.value*numTcam.value),2);
    var Qreti = round((numReti.value*numTcam.value),2);


    const parametros = new FormData();
    parametros.append("action", "guardar");
    parametros.append("nuevo", nuevo);
    parametros.append("nuevoProvee", nuevoProvee);
    parametros.append("txtCod", cod);
    parametros.append("txtSerie", serie);
    parametros.append("numNum", num);
    parametros.append("txtNit", txtNit.value);
    parametros.append("selTipoCod", selTipo.value);
    parametros.append("txtProv", txtProv.value);
    parametros.append("dtFec", dtFec.value);
    parametros.append("dtFecrece", dtFecrece.value);
    parametros.append("dtFecp", dtFecp.value);
    parametros.append("numTcam", numTcam.value);
    parametros.append("numContra", numContra.value);
    parametros.append("dtFcontra", dtFcontra.value);
    parametros.append("selOrden", selOrden.value);
    parametros.append("numOrden", numOrden.value);
    parametros.append("numAbo", numAbo.value);
    parametros.append("selMesCod", selMes.value);
    parametros.append("numAno", numAno.value);
    parametros.append("rfecAnt", rfecAnt);
    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("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("dcreProv", dcreProv);

    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("Qbien", Qbien);
    parametros.append("Qserv", Qserv);
    parametros.append("Qpeque", Qpeque);
    parametros.append("Qpeque2", Qpeque2);
    parametros.append("Qimp", Qimp);
    parametros.append("Qimpre", Qimpre);
    parametros.append("Qtasam", Qtasam);
    parametros.append("Qmedi", Qmedi);
    parametros.append("Qnoafe", Qnoafe);
    parametros.append("Qvehi", Qvehi);
    parametros.append("Qtfacom", Qtfacom);
    parametros.append("Qcomb", Qcomb);
    parametros.append("Qsubb", Qsubb);
    parametros.append("Qsubs", Qsubs);
    parametros.append("Qsubpe", Qsubpe);
    parametros.append("Qsubco", Qsubco);
    parametros.append("Qsubve", Qsubve);
    parametros.append("Qsubi", Qsubi);
    parametros.append("Qsubir", Qsubir);
    parametros.append("Qsubna", Qsubna);
    parametros.append("Qsubme", Qsubme);
    parametros.append("Qret", Qret);
    parametros.append("Qreti", Qreti);
    parametros.append("Qsub", Qsub);
    parametros.append("Qiva", Qiva);
    parametros.append("Qtot", Qtot);
    parametros.append("Qdedu", Qdedu);


    parametros.append("tblPol", tblToJson(colPol, "tblPol", 0));
    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 {
          if (imprimir) {
            imprimirCompra(serie, num, cod);
          }
          alSuccess(jsonJS);
        }
      }
    });
  }

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

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

    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();
    dtFecrece.value = dateToday();
    dtFecp.value = dateToday();
    numTcam.value = (1.000000).toFixed(6);
    numContra.value = 0;
    dtFcontra.value = dateToday();
    numOrden.value = 0;
    numAbo.value = 0.00;
    selMes.value = <?php echo $mesTrab; ?>;
    numAno.value = <?php echo $anoTrab; ?>;
    crRet.value = "N";
    crReti.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();
    dtFecrece.value = dateToday();
    dtFecp.value = dateToday();
    numTcam.value = (1.000000).toFixed(6);
    numContra.value = 0;
    dtFcontra.value = dateToday();
    numOrden.value = 0;
    numAbo.value = 0.00;
    selMes.value = <?php echo $mesTrab; ?>;
    numAno.value = <?php echo $anoTrab; ?>;
    crRet.value = "N";
    crReti.value = "N";
    crAfe.value = "S";
    ctaProv = "";
    retsnProv = "N";
    dcreProv=0;

    // SHOW MODAL
    $('#modalPol','#modalLisDocp').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;
      }
    });  */

    $("#btnAnti").click(function (){
      if (isNullPer(txtCodp.value)) {
        txtCodp.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CODIGO DEL PROVEEDOR"}});
        return true;
      }
      if ((valAbo+Number(numRet.value)+Number(numReti.value)) >= numTot.value) {
        alWarning({"msg":{"title":"NO HAY SALDO PENDIENTE","text":"Este documento ya no tiene saldo pendiente, revise."}});
        return true;
      }

      // Para guardar el documento actual
      if (restriccion()) {return};

      calcular();

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

      const serie = txtSerie.value;
      const num = numNum.value;
      const cod = txtCodp.value;

      var Qbien = round((numBien.value*numTcam.value),2);
      var Qserv = round((numServ.value*numTcam.value),2);
      var Qpeque = round((numPeque.value*numTcam.value),2);
      var Qpeque2 = round((numPeque2.value*numTcam.value),2);
      var Qimp = round((numImp.value*numTcam.value),2);
      var Qimpre = round((numImpre.value*numTcam.value),2);
      var Qmedi = round((numMedi.value*numTcam.value),2);
      var Qtasam = round((numTasam.value*numTcam.value),2);
      var Qnoafe = round((numNoafe.value*numTcam.value),2);
      var Qvehi = round((numVehi.value*numTcam.value),2);
      var Qtfacom = round((numTfacom.value*numTcam.value),2);
      var Qcomb = round((numComb.value*numTcam.value),2);
      var Qsubb = round((subb*numTcam.value),2);
      var Qsubs = round((subs*numTcam.value),2);
      var Qsubpe = round((subpe*numTcam.value),2);
      var Qsubco = round((subco*numTcam.value),2);
      var Qsubve = round((subve.value*numTcam.value),2);
      var Qsubi = round((subi*numTcam.value),2);
      var Qsubir = round((subir*numTcam.value),2);
      var Qsubna = round((subna*numTcam.value),2);
      var Qsubme = round((subme*numTcam.value),2);

      var Qsub = round((numSub.value*numTcam.value),2);
      var Qtot = round(((numTot.value-numDedu.value)*numTcam.value),2);
      var Qiva = round((Qtot-Qsub),2);
      var Qdedu = round((deduTot*numTcam.value),2);
      var Qret = round((numRet.value*numTcam.value),2);
      var Qreti = round((numReti.value*numTcam.value),2);

      const fnT = function(){


        const parametros = new FormData();

        txtAcodlis.value = txtCodp.value;
        txtAprovlis.value =  txtProv.value;
        tblClear("tblAntiLis");

        parametros.append("action", "consultarLisAnti");
        parametros.append("txtCod", txtCodp.value);
        parametros.append("nuevo", nuevo);
        parametros.append("nuevoProvee", nuevoProvee);
        parametros.append("txtCod", cod);
        parametros.append("txtSerie", serie);
        parametros.append("numNum", num);
        parametros.append("txtNit", txtNit.value);
        parametros.append("selTipoCod", selTipo.value);
        parametros.append("txtProv", txtProv.value);
        parametros.append("dtFec", dtFec.value);
        parametros.append("dtFecrece", dtFecrece.value);
        parametros.append("dtFecp", dtFecp.value);
        parametros.append("numTcam", numTcam.value);
        parametros.append("numContra", numContra.value);
        parametros.append("dtFcontra", dtFcontra.value);
        parametros.append("selOrden", selOrden.value);
        parametros.append("numOrden", numOrden.value);
        parametros.append("numAbo", numAbo.value);
        parametros.append("selMesCod", selMes.value);
        parametros.append("numAno", numAno.value);
        parametros.append("rfecAnt", rfecAnt);
        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("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("dcreProv", dcreProv);

        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("Qbien", Qbien);
        parametros.append("Qserv", Qserv);
        parametros.append("Qpeque", Qpeque);
        parametros.append("Qpeque2", Qpeque2);
        parametros.append("Qimp", Qimp);
        parametros.append("Qimpre", Qimpre);
        parametros.append("Qtasam", Qtasam);
        parametros.append("Qmedi", Qmedi);
        parametros.append("Qnoafe", Qnoafe);
        parametros.append("Qvehi", Qvehi);
        parametros.append("Qtfacom", Qtfacom);
        parametros.append("Qcomb", Qcomb);
        parametros.append("Qsubb", Qsubb);
        parametros.append("Qsubs", Qsubs);
        parametros.append("Qsubpe", Qsubpe);
        parametros.append("Qsubco", Qsubco);
        parametros.append("Qsubve", Qsubve);
        parametros.append("Qsubi", Qsubi);
        parametros.append("Qsubir", Qsubir);
        parametros.append("Qsubna", Qsubna);
        parametros.append("Qsubme", Qsubme);
        parametros.append("Qret", Qret);
        parametros.append("Qreti", Qreti);
        parametros.append("Qsub", Qsub);
        parametros.append("Qiva", Qiva);
        parametros.append("Qtot", Qtot);
        parametros.append("Qdedu", Qdedu);

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

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

            if(jsonJS.error == true){
              alError(jsonJS);
            } else {
              jsonJS.anticp.forEach(function(i,index){
                addRowAntiLis(i.ant_num, i.ant_fec, i.ant_tcam, i.ant_tot, i.tp_abrev, i.ant_ndoc, index);
              });
              sumCajaLis();
              $('#modalLisDocp').modal('toggle');
            }
          }
        });
      }
      const fnF = function(){
        return true;
      }
      usuClave(fnT, fnF);
    });

    $("#btnAsigAnti").click(function (){
      if (restriccion()) {return};

      colAnti = ["numdlis", "fecdlis", "tcamlis", "vallis", "tiporlis", "numrlis", "check"];

      const serie = txtSerie.value;
      const num = numNum.value;
      const cod = txtCodp.value;
      const nit = txtNit.value;
      const nsaldo=Number(numTot.value)-(Number(numAbo.value)+Number(numRet.value)+Number(numReti.value));

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

      parametros.append("txtSerie", serie);
      parametros.append("numNum", num);
      parametros.append("txtCod", cod);
      parametros.append("txtNit", nit);
      parametros.append("nsaldo", nsaldo);
      parametros.append("tblAntiLis", tblToJsonCbSkip(colAnti, "tblAntiLis", 10, 6));

      $.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 {
            abo=Number(jsonJS.doctosc.dc_abo);
            valAbo=Number(jsonJS.doctosc.dc_abo);
            numAbo.value=abo.toFixed(2);
            tblClear("tblAntiLis");
            $('#modalLisDocp').modal('toggle');
            //alSuccess(jsonJS);
            //alSuccess(JSON.parse('{"msg":'+decode_utf8(JSON.stringify(jsonJS.msg))+"}"));
          }
        }
      });
    });


    // CHANGE CAJA
    $("body").on("change", "input[name=cb]", function (){
      sumCajaLis();
      nsal=Number(numTot.value)-(Number(numAbo.value)+Number(numRet.value)+Number(numReti.value));
      if ($("#tblAntiLis #dataTotAntiLis").text() > nsal) {
          alWarning({"msg":{"title":"SOBRE PASO EL SALDO PENDIENTE","text":"Ya sobre paso el saldo que tiene pendiente este documento, tome en cuenta que solo se asignara el saldo pendiente."}});
          return true;
      }    
    });
    

    // FOCUS SERIE
    $("#txtSerie").focus(function (){
      txtSerie.value = "";
      numNum.value = "";
      limpiar();
    });

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

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

          if(jsonJS.error == true){
            alError(jsonJS);
            nuevoProvee = true;
          } else {
            if (jsonJS.provcp === null) {
              nuevoProvee = true;
              txtCodp.focus();
              txtProv.value = "";
              txtNit.value = "";
              alWarning({"msg":{"title":"No Existe","text":"Este proveedor no existe, debe registrarlo"}});
               return true;
            } else {
              txtProv.value = jsonJS.provcp.pro_nom;
              txtNit.value = jsonJS.provcp.pro_nit;
              ctaProv= jsonJS.provcp.pro_cta;
              retsnProv = jsonJS.provcp.pro_retsn;
              crRet.value = jsonJS.provcp.pro_retsn;
              dcreProv = jsonJS.provcp.pro_dcre;
              nuevoProvee = false;
            }
          }
        }
      });
    });

    // VALID SERIE, NUMERO, COD
    $("#numNum")
    .focus(function (){
      numNum.value = "";
      limpiar();
    })
    .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("txtCod", txtCodp.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);
            tblPolAnt = JSON.stringify(jsonJS.poli_det);

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

              if (jsonJS.doctosc === null) {
                mesCerrado = false;
                crRet.value = retsnProv;
                valAbo=0.00;
                //console.log(dcreProv);
                dtFecp.value = sumYMD(dtFec.value,Number(dcreProv));
              } else {
                if (jsonJS.doctosc.ciem_stat === "C") {
                  mesCerrado = true;
                  txtSerie.focus();
                  alWarning({"msg":{"title":"MES CERRADO","text":"No puede trabajar con este documento, porque el mes al que corresponde ya fue cerrado"}});
                  return true;
                } else {
                  mesCerrado = false;
                }
              }
              
              if (jsonJS.doctosc === null) {
                nuevo = true;
                rfecAnt = "0000-00-00";
              } else {
                ctaProv= jsonJS.doctosc.pro_cta;
                selTipo.value = jsonJS.doctosc.dc_tipo;
                txtProv.value = jsonJS.doctosc.dc_prov;
                txtNit.value = jsonJS.doctosc.dc_nit;
                dtFec.value = jsonJS.doctosc.dc_fec;
                dtFecrece.value = jsonJS.doctosc.dc_fecrece;
                dtFecp.value = jsonJS.doctosc.dc_fecp;
                numContra.value = jsonJS.doctosc.dc_contra;
                dtFcontra.value = jsonJS.doctosc.dc_fcontra;
                selOrden.value = jsonJS.doctosc.dc_seriecn;
                numOrden.value = jsonJS.doctosc.dc_numcn;

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

                crRet.value = jsonJS.doctosc.dc_retsn;
                crReti.value = jsonJS.doctosc.dc_retisn;
                crAfe.value = jsonJS.doctosc.dc_afe;
                numBien.value = numberFixedEmpty(Number(jsonJS.doctosc.dc_bien));
                numServ.value = numberFixedEmpty(Number(jsonJS.doctosc.dc_serv));
                numPeque.value = numberFixedEmpty(Number(jsonJS.doctosc.dc_peque));
                numPeque2.value = numberFixedEmpty(Number(jsonJS.doctosc.dc_peque2));
                numImp.value = numberFixedEmpty(Number(jsonJS.doctosc.dc_imp));
                numImpre.value = numberFixedEmpty(Number(jsonJS.doctosc.dc_impre));
                numTasam.value = numberFixedEmpty(Number(jsonJS.doctosc.dc_tasam));
                numMedi.value = numberFixedEmpty(Number(jsonJS.doctosc.dc_medi));
                numNoafe.value = numberFixedEmpty(Number(jsonJS.doctosc.dc_noafe));
                numVehi.value = numberFixedEmpty(Number(jsonJS.doctosc.dc_vehi));
                numVehia.value = numberFixedEmpty(Number(jsonJS.doctosc.dc_vehia));
                crTvehi.value = jsonJS.doctosc.dc_tvehi;
                numTfacom.value = numberFixedEmpty(Number(jsonJS.doctosc.dc_tfacom));
                numGalos.value = numberFixedEmpty(Number(jsonJS.doctosc.dc_galos), 3);
                numGalor.value = numberFixedEmpty(Number(jsonJS.doctosc.dc_galor), 3);
                numGalod.value = numberFixedEmpty(Number(jsonJS.doctosc.dc_galod), 3);
                numComb.value = numberFixedEmpty(Number(jsonJS.doctosc.dc_comb));
                txtCon.value = jsonJS.doctosc.dc_con;

                calculoDedu();
                tot=Number(jsonJS.doctosc.dc_tot);
                dedu=Number(jsonJS.doctosc.dc_dedu);                
                sub=Number(jsonJS.doctosc.dc_sub);
                iva=Number(jsonJS.doctosc.dc_iva);
                ret=Number(jsonJS.doctosc.dc_ret);
                reti=Number(jsonJS.doctosc.dc_reti);
                tcam=Number(jsonJS.doctosc.dc_tcam);
                abo=Number(jsonJS.doctosc.dc_abo);
                valAbo=Number(jsonJS.doctosc.dc_abo);
                // TOTALES
                numRet.value=ret.toFixed(2);
                numReti.value=reti.toFixed(2);
                numSub.value=sub.toFixed(2);
                numIva.value=iva.toFixed(2);
                numDedu.value=dedu.toFixed(2);
                numTot.value=tot.toFixed(2);
                numTcam.value=tcam.toFixed(6);
                numAbo.value=abo.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 FECHA
    $("#dtFec")
    .focus(function (){
      if ($('#selTipo').find('option:selected').data('partidasn') == 'S') {
        crAfe.value='S';
      } else {
        crAfe.value='N';
        crRet.value='N';
        crReti.value='N';
      }
    })
    .change(function (){
      dtFecp.value = sumYMD(this.value,Number(dcreProv));
    });

    // VALID MES Y ANO
    $("#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;
              numAno.value = <?php echo $anoTrab; ?>;
              selMes.value = <?php echo $mesTrab; ?>;
            } 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+deduTot).toFixed(2);
    });

    // FOCUS INPUT
    $("form[name='thisform'] input, select, textarea, #btnPartida").focus(function (){
     /* if (!($("input:visible:first").is(":focus")) && !($("#numNum").is(":focus")) && !($("#txtCodp").is(":focus")) && !($("#txtSerie").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};
      if (valAbo != 0.00) {
        numNum.focus();
        alWarning({"msg":{"title":"TIENE ABONOS","text":"Este documento no puede ser borrrado, porque tiene abonos aplicados, borre primero los abonos y vuelva a intentarlo"}});
        return true;
      }
      const serie = txtSerie.value;
      const num = numNum.value;
      const cod = txtCodp.value;
      const nit = txtNit.value;

      //numNum.focus();

      const fnT = function(){
        colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

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

        parametros.append("txtSerie", serie);
        parametros.append("numNum", num);
        parametros.append("txtCod", cod);
        parametros.append("txtNit", nit);

        parametros.append("rfecAnt", rfecAnt);
        parametros.append("tblPolAnt", tblPolAnt);
        
        $.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 (){
      if ($('#selTipo').find('option:selected').data('partidasn') != "S" && $("#tblPol tbody").children().length > 0) { 
        alWarning({"msg":{"title":"NO NECESITA PARTIDA","text":"A este tipo de documento no debe generarle partida."}});
        return;
      }
      if ($("#tblPol tbody").children().length == 0 && $('#selTipo').find('option:selected').data('partidasn') == "S") {
        alWarning({"msg":{"title":"NO HA GENERADO PARTIDA","text":"A este dodumento debe registrarle partida"}});
        return;
      }
      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;
      }

      var Qsub = round((numSub.value*numTcam.value),2);
      var Qtot = round(((numTot.value-numDedu.value)*numTcam.value),2);
      var Qiva = round((Qtot-Qsub),2);
      var Qdedu = round((deduTot*numTcam.value),2);
      var Qret = round((numRet.value*numTcam.value),2);
      var Qreti = round((numReti.value*numTcam.value),2);
      var Qtasam = round((numTasam.value*numTcam.value),2);

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

      parametros.append("numBien", numBien.value);
      parametros.append("numServ", numServ.value);
      parametros.append("numIva", numIva.value);
      parametros.append("deduTot", deduTot);
      parametros.append("numRet", numRet.value);
      parametros.append("numReti", numReti.value);
      parametros.append("txtCodp", txtCodp.value);
      parametros.append("ctaProv", ctaProv);


      $('#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);
          //console.log(jsonPhp);
          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            tblClear("tblPol");
            sumPol();
            
            if ($('#selTipo').find('option:selected').data('pone')!="N") {
              if (!isNullPer(jsonJS.ctaGas)) {
                addRowPol(jsonJS.ctaGas.cta, jsonJS.ctaGas.cta_nom, (Qsub-Qtasam).toFixed(2), "0.00");
              } else {
                addRowPol("XXXXXXX", "Ingrese cuenta de gastos", (Qsub-Qtasam).toFixed(2), "0.00");
              }

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

              if (numTasam.value != 0) {
                if (!isNullPer(jsonJS.ctaTasa)) {
                  addRowPol(jsonJS.ctaTasa.cta, jsonJS.ctaTasa.cta_nom, (Qtasam).toFixed(2), "0.00");
                } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta de Tasa Municipal", (Qtasam).toFixed(2), "0.00");
                }
              }

              // Cuenta Impuesto Combustible
              if (Qdedu != 0) {
                if (!isNullPer(jsonJS.ctaComb)) {
                  addRowPol(jsonJS.ctaComb.cta, jsonJS.ctaComb.cta_nom, (Qdedu).toFixed(2), "0.00");
                } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta Imp. Combustible", (Qdedu).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", (Qret).toFixed(2));
                } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta de Retención de ISR", "0.00", (Qret).toFixed(2));
                }
              }

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

              // Cuenta Proveedor
              if (!isNullPer(jsonJS.ctaProv)) {
                addRowPol(jsonJS.ctaProv.cta, jsonJS.ctaProv.cta_nom, "0.00", ((Qtot+Qdedu)-(Qret+Qreti).toFixed(2)).toFixed(2));
              } else {
                addRowPol("XXXXXXX", "Ingrese la cuenta de Proveedores", "0.00", ((Qtot+Qdedu)-(Qret+Qreti).toFixed(2)).toFixed(2));
              }
            } else {
              // Cuenta Caja
              if (!isNullPer(jsonJS.ctaProv)) {
                addRowPol(jsonJS.ctaProv.cta, jsonJS.ctaProv.cta_nom, ((tot+deduTot)*-1).toFixed(2), "0.00");
              } else {
                addRowPol("XXXXXXX", "Ingrese la cuenta de Proveedores", ((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(txtCodp.value)) {
        txtCodp.focus();
      } else if (target == "#pills-0" && isNullPer(txtSerie.value)) {
        txtSerie.focus();
      } else if (target == "#pills-0" && isNullPer(numNum.value)) {
        numNum.focus();
      } else {
        (relatedTarget == "#pills-1") ? txtCodp.focus() : 0;
      }
      //$(target+' input:visible:first').focus();
    }
  });

</script>