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

$empCod = $_SESSION['empCod'];
$empNom = $_SESSION['empNom'];
$empNit = $_SESSION['empNit'];

# QUERYS
$sTipov = "SELECT 
            TRIM(tv.tv_cod) AS tv_cod,
            TRIM(tv.tv_nom) AS tv_nom,
            TRIM(tv.tv_abrev) AS tv_abrev,
            TRIM(tv.tv_codasiste) AS tv_codasiste,
            tv_librosn,
            tv_impues
           FROM tipov tv WHERE tv_pone='P' and tv_fel='S'";
$sVendedor = "SELECT * FROM vendedor";
$sBancos = "SELECT *, 
              TRIM(ban_nom) as ban_nom,
              TRIM(ban_ctab) as ban_ctab,
              TRIM(ban_ctac) as ban_ctac
            FROM bancos WHERE ban_emp='$empCod'";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["tipov"] = $db->query($sTipov);
$select["vendedor"] = $db->query($sVendedor);
$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>

      <!-- MODAL DETALLE -->
      <div class="modal fade" id="modalDet" tabindex="-1" role="dialog" aria-labelledby="modalDetTitle" 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-10-tab" data-toggle="pill" href="#pills-10" role="tab" aria-controls="pills-10" aria-selected="true"></a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-white" aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">

              <div class="tab-content bg-transparent border-0" id="pills-tabContent">
                <div class="tab-pane fade show active" id="pills-10" role="tabpanel" aria-labelledby="pills-10-tab">
                  
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">

                    <div class="form-group">
                      <div class="form-row align-items-end">
                        <div class="col-md-9 col-xl-7">
                          <label class="font-size-sm text-success" for="txtDescdm">Descripción</label>
                          <input type="text" class="form-control form-control-sm form-control-as limpiarModalDet" id="txtDescdm" maxlength="120">
                        </div>
                        <div class="col-md-6">
                          <div class="form-row align-items-end">
                            <div class="col-4">
                              <label class="font-size-sm text-success" for="numCantdm">Cantidad</label>
                              <input type="number" class="form-control form-control-sm form-control-as dec-2 limpiarModalDet" id="numCantdm" placeholder="0.00">
                            </div>
                            <div class="col-4">
                              <label class="font-size-sm text-success" for="numPreudm">Precio Unit.</label>
                              <input type="number" class="form-control form-control-sm form-control-as dec-2 limpiarModalDet" id="numPreudm" placeholder="0.00">
                            </div>
                            <div class="col-4">
                              <label class="font-size-sm text-success" for="numTotdm">Total</label>
                              <input type="number" class="form-control form-control-sm form-control-as dec-2 limpiarModalDet" id="numTotdm" placeholder="0.00" disabled>
                            </div>

<!------                            
                            <div class="col-6">
                              <label class="font-size-sm text-success" for="numSubdm">Sub-Total</label>
                              <input type="number" class="form-control form-control-sm form-control-as dec-5 limpiarModalDet" id="numSubdm" placeholder="0.00" disabled>
                            </div>
--->                            
                          </div>
                        </div>
<!---                        
                        <div class="col-md-6">
                          <div class="form-row align-items-end">
                            <div class="col-6">
                              <label class="font-size-sm text-success" for="numDescudm">Descuento %</label>
                              <input type="number" class="form-control form-control-sm form-control-as dec-2 limpiarModalDet" id="numDescudm" placeholder="0.00">
                            </div>
                            <div class="col-6">
                              <label class="font-size-sm text-success" for="numDescuvdm">Valor Descuento</label>
                              <input type="number" class="form-control form-control-sm form-control-as dec-2 limpiarModalDet" id="numDescuvdm" placeholder="0.00" disabled>
                            </div>
                            <div class="col-12">
                              <label class="font-size-sm text-success" for="numTotdm">Total</label>
                              <input type="number" class="form-control form-control-sm form-control-as dec-5 limpiarModalDet" id="numTotdm" placeholder="0.00" disabled>
                            </div>
                          </div>
                        </div>
                        <div class="col-12 text-center mt-2">
                          <div class="custom-control custom-switch">
                            <input type="checkbox" class="custom-control-input" name="cbExentodm" id="cbExentodm">
                            <label class="custom-control-label text-success" for="cbExentodm">Exento</label>
                          </div>
                        </div>
---->                        
                      </div>
                    </div>

                    <button type="button" class="btn btn-success btn-block" id="btnModificarDet">Modificar</button>

                  </form>

                </div>
              </div>

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


      <!-- MODAL CORREO ELECTRONICO -->
      <div class="modal fade" id="modalMail" tabindex="-1" role="dialog" aria-labelledby="modalMailTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg" role="document">
          <div class="modal-content bg-ligth">
            <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-12-tab" data-toggle="pill" href="#pills-12" role="tab" aria-controls="pills-12" aria-selected="true">CORREO ELECTRONICO</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-12" role="tabpanel" aria-labelledby="pills-12-tab">
                  
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">
                      <div class="form-row align-items-end">
                        <div class="col-12">
                          <label class="font-size-xl text-success" style="font-size:25px;" for="txtMail">Correo al que se enviara</label>
                          <input type="text" class="form-control form-control-xl form-control-as text-dark" style="font-size:20px;" id="txtMail" placeholder="Correo">
                        </div>
                      </div>
                      <div class="form-row align-items-end">
                        <div class="col-12">
                          <label class="font-size-xl text-success" style="font-size:25px;" for="txtMail1">Con Copia 1</label>
                          <input type="text" class="form-control form-control-xl form-control-as text-dark" style="font-size:20px;" id="txtMail1" placeholder="Copia 1">
                        </div>
                      </div>
                      <div class="form-row align-items-end">
                        <div class="col-12">
                          <label class="font-size-xl text-success" style="font-size:25px;" for="txtMail2">Con Copia 2</label>
                          <input type="text" class="form-control form-control-xl form-control-as text-dark" style="font-size:20px;" id="txtMail2" placeholder="Copia 2">
                        </div>
                      </div>
                    </div>
                    <div class="form-row">
                      <div class="col-3">
                        <label></label>
                      </div>
                      <div class="col-6">
                        <button type="button" class="btn btn-success btn-block" id="btnEnviar">Continuar</button>
                      </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 Clientes CxC </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 Artículo</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" id="pills-3-tab" data-toggle="pill" href="#pills-3" role="tab" aria-controls="pills-3" aria-selected="true">Buscar Clientes Contado</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">
                        <h4 class="text-success">DETALLE DEL DOCUMENTO:</h4>
                        <div class="form-row align-items-end">
                          <div class="col-7">
                            <label class="font-size-md text-success" for="txtDescd">Descripción</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiarDet" id="txtDescd" maxlength="120">
                          </div>
                          <div class="col-1">
                            <label class="font-size-md text-success" for="numCantd">Cantidad</label>
                            <input type="number" class="form-control form-control-md form-control-as dec-2 limpiarDet" id="numCantd" placeholder="0.00">
                          </div>
                          <div class="col-2">
                            <label class="font-size-md text-success" for="numPreud">Precio Unit.</label>
                            <input type="number" class="form-control form-control-md form-control-as dec-5 limpiarDet" id="numPreud" placeholder="0.00">
                          </div>
                          <div class="col-2">
                            <label class="font-size-md text-success" for="numTotd">Total</label>
                            <input type="number" class="form-control form-control-md form-control-as dec-5 limpiarDet" id="numTotd" placeholder="0.00" disabled>
                          </div>
                        </div>
                        <div class="form-row align-items-end">
<!---                          
                          <div class="col-2">
                            <label class="font-size-md text-success" for="numSubd">Sub-Total</label>
                            <input type="number" class="form-control form-control-md form-control-as dec-5 limpiarDet" id="numSubd" placeholder="0.00" disabled>
                          </div>
                          <div class="col-2">
                            <label class="font-size-md text-success" for="numDescud">Descuento %</label>
                            <input type="number" class="form-control form-control-md form-control-as dec-2 limpiarDet" id="numDescud" placeholder="0.00">
                          </div>
                          <div class="col-2">
                            <label class="font-size-md text-success" for="numDescuvd">Valor Descuento</label>
                            <input type="number" class="form-control form-control-md form-control-as dec-2 limpiarDet" id="numDescuvd" placeholder="0.00" disabled>
                          </div>
----->                          
<!----                          
                          <div class="col-2 text-center mt-2">
                            <div class="custom-control custom-switch">
                              <input type="checkbox" class="custom-control-input" name="cbExentod" id="cbExentod">
                              <label class="custom-control-label text-success" for="cbExentod">Exento</label>
                            </div>
                          </div>
---->                          
                        </div>
                      </div>

                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-5">
                            <button type="button" class="btn btn-success" id="btnAddDet">
                              <i class="fas fa-plus-circle"></i> Agregar
                            </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-md" id="tblDet">
                                <thead>
                                  <tr>
                                    <th scope="col" class="text-center ignore" width="20">ACCIONES</th>
                                    <th scope="col" class="text-center" style="font-size:18px;" width="350">DESCRIPCIÓN</th>
                                    <th scope="col" class="text-center" style="font-size:18px;" width="70">CANTIDAD</th>
                                    <th scope="col" class="text-center" style="font-size:18px;" width="90">PRECIO UNIT.</th>
<!--                                    
                                    <th scope="col" class="text-center" width="90">SUB-TOTAL</th>
                                    <th scope="col" class="text-center" width="50">DESCU. %</th>
                                    <th scope="col" class="text-center" width="90">VALOR DESCU.</th>
--->                                    
                                    <th scope="col" class="text-center" style="font-size:16px;" width="90">TOTAL</th>
<!---                                    
                                    <th scope="col" class="text-center" width="10">EXENTO</th>
--->                                    
                                  </tr>
                                </thead>
                                <tbody>
                                </tbody>
                                <tfoot>
                                  <th scope="col" class="ignore"></th>
                                  <th scope="col"></th>
                                  <th scope="col"></th>
                                  <th scope="col" class="text-right" style="font-size:18px;">Total</th>
<!---                                  
                                  <th scope="col" id="dataTotSub" class="text-right">0.00</th>
                                  <th scope="col"></th>
                                  <th scope="col" id="dataTotDescuv" class="text-right">0.00</th>
--->                                  
                                  <th scope="col" id="dataTotTot" class="text-right" style="font-size:18px;">0.00</th>
                                </tfoot>
                              </table>
                            </div>
                          </div>
                        </div>
                      </div>
                      
                      <div class="form-group">
                        <div class="form-row align-items-end">
                          <div class="col-md-2">
                            <label class="font-size-md" for="dtFec">Fecha del Documento</label>
                            <input type="date" class="form-control form-control-md form-control-as" id="dtFec" placeholder="">
                          </div>
                          <div class="col-md-2">
                            <label class="font-size-md" for="txtCliCod">Código Cliente</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtCliCod">
                          </div>
                          <div class="col-md-7">
                            <label class="font-size-md" for="txtCliNom"></label>
                            <input type="text" class="form-control form-control-md form-control-as form-info limpiar" id="txtCliNom">
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-2">
                            <label class="font-size-md" for="txtNit">NIT/CUI</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtNit">
                          </div>
                          <div class="col-8">
                            <label class="font-size-md" for="txtNomFac">A nombre de</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtNomFac">
                          </div>
                          <div class="col-2 text-center">
                            <label class="pr-1 font-size-md">Usara NIT/CUI</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crNitCui1" name="crNitCui" class="custom-control-input" value="N">
                              <label class="custom-control-label font-size-md" for="crNitCui1">NIT</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crNitCui2" name="crNitCui" class="custom-control-input" value="C">
                              <label class="custom-control-label font-size-md" for="crNitCui2">CUI</label>
                            </div>
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-12">
                            <label class="font-size-md" for="txtDir">Dirección</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtDir">
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-md-4">
                            <label class="font-size-md" for="txtTel">Teléfono</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtTel">
                          </div>
                          <div class="col-4 col-md-2">
                            <label class="font-size-md" for="numDcre">Días Crédito</label>
                            <input type="number" class="form-control form-control-md form-control-as dec-0 limpiar" id="numDcre" placeholder="0">
                          </div>
                          <div class="col-8 col-md-2">
                            <label class="font-size-md" for="numTcam">Tipo de Cambio</span></label>
                            <input type="number" class="form-control form-control-md form-control-as dec-5" id="numTcam" placeholder="0.00000" disabled>
                          </div>
                          <div class="col-md-4">
                            <label class="font-size-md" for="selVend">Vendedor</label>
                            <select class="form-control form-control-md form-control-as" name="selVend" id="selVend">
                              <option value="000"></option>
                              <?php
                                while ($rec = $db->fetchAssoc($select['vendedor'])) {
                                  echo  '<option value="'.TRIM($rec['vend_cod']).'">'.utf8_encode($rec['vend_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                        </div>
                        <div class="form-row align-items-end">
                          <div class="col-12">
                            <label class="font-size-md" for="txtAlumno">Alumno</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtAlumno">
                          </div>
                        </div>
                        <div class="form-row align-items-end">
                          <div class="col-md-8">
                            <div class="form-row align-items-end">
                              <div class="col-md-4">
                                <label class="font-size-md" for="selTipo">Tipo Factura</label>
                                <select class="form-control form-control-md form-control-as" name="selTipo" id="selTipo" disabled>
                                  <?php
                                    while ($rec = $db->fetchAssoc($select['tipov'])) {
                                      //echo  "<option value={$rec['tv_cod']} data-librosn={$rec['tv_librosn']} data-relatd={$rec['td_cod']} data-impues={$rec['tv_impues']} data-abrev={$rec['tv_abrev']}>".utf8_encode($rec['tv_nom']).'</option>';
                                      echo  '<option value="'.$rec['tv_cod'].'" data-librosn="'.$rec['tv_librosn'].'" data-impues="'.$rec['tv_impues'].'" data-abrev="'.$rec['tv_abrev'].'" data-codasiste="'.$rec['tv_codasiste'].'">'.utf8_encode($rec['tv_nom']).'</option>';
                                    }
                                  ?>
                                </select>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="form-row align-items-center">
                          <div class="col-7 col-md-4 text-center">
                            <label class="pr-1">Forma de Pago</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crFpag1" name="crFpag" class="custom-control-input" value="1">
                              <label class="custom-control-label" for="crFpag1">Contado</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crFpag2" name="crFpag" class="custom-control-input" value="2">
                              <label class="custom-control-label" for="crFpag2">Crédito</label>
                            </div>
                          </div>
<!--                          <div class="col-5 col-md-2 text-center">
                            <label class="pr-1">Exportación</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crExp1" name="crExp" class="custom-control-input calcular" value="S" disabled>
                              <label class="custom-control-label" for="crExp1">Si</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crExp2" name="crExp" class="custom-control-input calcular" value="N" disabled>
                              <label class="custom-control-label" for="crExp2">No</label>
                            </div>
                          </div>   -->
                          <div class="col-7 col-md-3 text-center">
                            <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-5 col-md-3 text-center">
                            <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>
                      </div>
                      <div class="form-group">
                        <h4 class="text-light">Partida</h4>
                        <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">

                        <div class="form-row align-items-center ml-2">
<!----                          
                          <div class="col-6">
                            <label class="text-success" for="numSub" style="font-size:25px; font-weight:bold;">Sub-Total</label>
                          </div>
                          <div class="col-6">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar text-right" style="font-size:25px; font-weight:bold;" id="numSub" placeholder="0.00" min="0" disabled>
                          </div>
                          <div class="col-6">
                            <label class="text-danger" for="numDescuv" style="font-size:25px; font-weight:bold;">Descuento</label>
                          </div>
                          <div class="col-6">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar text-right" style="font-size:25px; font-weight:bold;" id="numDescuv" placeholder="0.00" min="0" disabled>
                          </div>
--->                          
                          <div class="col-6">
                            <label class="text-success" for="numTot" style="font-size:35px; font-weight:bold;">Total a Pagar</label>
                          </div>
                          <div class="col-6">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar text-right" style="font-size:33px; font-weight:bold;" id="numTot" placeholder="0.00" min="0" disabled>
                          </div>
                        </div>

                        <div class="form-row align-items-center ml-2">
                          <div class="col-12">
                            <label style="font-size:35px; font-weight:bold;"></label>
                          </div>
                          <div class="col-12">
                            <label style="font-size:35px; font-weight:bold;">FORMA DE PAGO</label>
                          </div>
                        </div>
                        <div class="form-row align-items-center ml-2">
                          <div class="col-6">
                            <label class="text-success" for="numEfec" style="font-size:23px; font-weight:bold;">Efectivo</label>
                          </div>
                          <div class="col-4">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar" style="font-size:18px; font-weight:bold;" id="numEfec" placeholder="0.00" min="0">
                          </div>
                        </div>
                        <div class="form-row align-items-center ml-2">
                          <div class="col-6">
                            <label class="text-success" for="numDepo" style="font-size:23px; font-weight:bold;">Deposito</label>
                          </div>
                          <div class="col-4">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar" style="font-size:18px; font-weight:bold;" id="numDepo" placeholder="0.00" min="0">
                          </div>
                        </div>
                        <div class="form-row align-items-center ml-2">
                          <div class="col-8">
                            <label class="font-size-md text-success" for="selBanDepo">Banco Deposito</label>
                            <select class="form-control form-control-md form-control-as" name="selBanDepo" id="selBanDepo">
                              <?php
                                while ($rec = $db->fetchAssoc($select['bancos'])) {
                                  echo  '<option value="'.$rec['ban_num'].'" data-ctab="'.$rec['ban_ctab'].'" data-ctac="'.$rec['ban_ctac'].'" data-forma="'.$rec['ban_forma'].'">'.utf8_encode($rec['ban_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                        </div>
                        <div class="form-row align-items-center ml-2">
                          <div class="col-6">
                            <label class="font-size-md text-success" for="numNdepo">No. Deposito</label>
                            <input type="number" class="form-control form-control-md form-control-as form-info limpiar" id="numNdepo" placeholder="0">
                          </div>
                        </div>
                        <div class="form-row align-items-center ml-2">
                          <div class="col-6">
                            <label class="text-success" for="numTarj" style="font-size:23px; font-weight:bold;">Tarjeta</label>
                          </div>
                          <div class="col-4">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar" style="font-size:18px; font-weight:bold;" id="numTarj" placeholder="0.00" min="0">
                          </div>
                        </div>
                        <div class="form-row align-items-center ml-2">
                          <div class="col-6">
                            <label class="text-success" for="numCred" style="font-size:23px; font-weight:bold;">Credito</label>
                          </div>
                          <div class="col-4">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar" style="font-size:18px; font-weight:bold;" id="numCred" placeholder="0.00" min="0">
                          </div>
                        </div>
                        <div class="form-row align-items-center ml-2">
                          <div class="col-6">
                            <label class="text-warning" for="numTotfp" style="font-size:23px; font-weight:bold;">SUMATORIA</label>
                          </div>
                          <div class="col-4">
                            <input type="number" class="form-control form-control-sm form-control-as limpiar" style="font-size:18px; font-weight:bold;" id="numTotfp" placeholder="0.00" min="0" disabled>
                          </div>
                        </div>

                        <div class="form-row">
                          <div class="col-4">
                            <label style="font-size:23px; font-weight:bold;"></label>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-warning btn-block" style="font-size:25px; font-weight:bold;" id="btnGuardarImprimir" type="button">Imprimir / Guardar</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-success btn-block" style="font-size:18px; font-weight:bold;" id="btnGuardar" type="button">Solo Grabar</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-info btn-block" style="font-size:18px; font-weight:bold;" id="btnCorreo" type="button">Enviar por Correo</button>
                          </div>
<!--                          <div class="col-12 mt-2">
                            <button class="btn btn-primary btn-block" id="btnEnvio" type="button">Imprimir Envio</button>
                          </div>  -->
                        </div>
                        <div class="form-row">
                          <div class="col-2">
                            <label> .</label>
                          </div>
                          <div class="col-2">
                            <label> .</label>
                          </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('../busClienccCod/index.html')
                ?>
              </div>
              <div class="tab-pane fade" id="pills-2" role="tabpanel" aria-labelledby="pills-2-tab">
                <?php
                  $a='0';
                  $b='2';
                  include('../busArtic2/index.html');
                ?>
              </div>
              <div class="tab-pane fade" id="pills-3" role="tabpanel" aria-labelledby="pills-3-tab">
                <?php
                  $a='0';
                  $b='3';
                  include('../busClien/index.html')
                ?>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var mesCerrado = false;

  var tblDetAnt;
  var tblPolAnt;

  var inputCtaMov = "txtCta";
  var inputClienccCod = "txtCliCod";
  var inputClien = "txtNit";
  var inputArtic = "txtCodd";

  var cliCta = "";
  var medid = "";
  var cantAnt = 0;
  var bienser = "";
  var bienserm = "";
  var opGrabar = "A";
  var resolnum = "";
  var resolstat = "A";
  var resolini = 1;
  var resolfin = 1;
  var resolcorr = 1;
  var email = "";
  var nit = "";

//  var imgPhoto = "../../img/photo.jpg";
//  var imgPhoto1 = "../../img/CAJAREG4.jpg";
 // var imgPhoto2 = "img/SENORO.jpeg";
  var idThisd = "";

//  imgArtic.src = imgPhoto;
//  imgCajareg.src = imgPhoto1;
//  imgSenor.src = imgPhoto2;
  
  const colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

  const colDet = ["acciones", "codd", "descd", "medid", "unimed", "cantd", "preud", "subd", "descud", "descuvd", "totd", "exensnd", "bienserd"];

  // Valores
  var tot = 0;
  var ret = 0;
  var reti = 0;
  var iva = 0;
  var sub = 0;
  var valq = 0;
  var vuelto = 0;

  const txtNit = document.thisform.txtNit;
  const txtNomFac = document.thisform.txtNomFac;
  const txtDir = document.thisform.txtDir;
  const txtAlumno = document.thisform.txtAlumno;
  const numEfec = document.thisform.numEfec;
  const numDepo = document.thisform.numDepo;
  const selBanDepo = document.thisform.selBanDepo;
  const numNdepo = document.thisform.numNdepo;
  const numTarj = document.thisform.numTarj;
  const numCred = document.thisform.numCred;

  const crFpag = document.thisform.crFpag;
  const crRet = document.thisform.crRet;
  const crReti = document.thisform.crReti;
  const crNitCui = document.thisform.crNitCui;
  //const crExp = document.thisform.crExp;

  function restriccion(consultar = false, mes = true){
    if (!consultar) {
      if (isNullPer(txtCliCod.value)) {
        txtCliCod.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CÓDIGO CLIENTE"}});
        return true;
      }
      console.log(restriccionImpues(false), (!restriccionImpues(false)) ? "examinar" : "no examinar");
      if (numTot.value == 0) {
        alWarning({"msg":{"title":"Total en Cero","text":"No se puede guardar porque el total de la factura es cero"}});
        return true;
      }
      if (numTot.value >= 2500 && crNitCui.value=="N" && txtNit.value=="CF") {
        alWarning({"msg":{"title":"NO PUEDE USAR CF","text":"No puede usar CF en el Nit ya que el valor es igual o mayor a 2500.00, debe utilizar CUI"}});
        return true;
      }
      if (!restriccionImpues(false)) {
        if ($("#dataTotDebe").text() != $("#dataTotHaber").text()) {
          alWarning({"msg":{"title":"Valores Incorrectos","text":"La partida no cuadra, verifique los valores"}});
          return true;
        }
        // PARA VER SI LA PARTIDA ESTÁ VACÍA
        if ($("#tblPol tbody").children().length == 0) {
          alWarning({"msg":{"title":"Partida Vacía","text":"Es necesario Generar Partida"}});
          return true;
        }
        // RECORRER PARTIDA PARA BUSCAR UNA CUENTA NO DEFINIDA
        var ctaInc = false;
        $("#tblPol tbody tr").each(function(){
          if ($(this).find("td:eq(1)").text().includes("XXXX")) {
            ctaInc = true;
            return false;
          }
        });
        if (ctaInc) {
          alWarning({"msg":{"title":"Cuenta Incorrecta","text":"Alguna cuenta de la partida no está asignada correctamente, verifique"}});
          return true;
        }
      }
    } else {
      /*if (isNullPer(txtCliCod.value) || isNullPer($('#tblPol #dataTot').text())) {
        return true;
      }*/
    }
    return false;
  }

  function restriccionCamposVacios() {
  }


  function restriccionModalDet() {
    $('#modalDet').modal('toggle');
    return false;
  }

  function restriccionDet() {
    return false;
  }

  function restriccionFpago() {
    if (numTot.value!=numTotfp.value) {
      numEfec.focus();
      alWarning({"msg":{"title":"HAY DESCUADRE","text":"El total de del documento no cuadra con el total de la forma de pago."}});
      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 restriccionCta() {
    if (isNullPer(txtCta.value)) {
      txtCtaNom.value = "";
      return true;
    }
    return false;
  }

  function restriccionTcam() {
    if (numTcam.value <= 0) {
      alWarning({"msg":{"title":"Tipo de Cambio","text":"La TASA DE CAMBIO no puede ser menor o igual a cero"}});
      numTcam.value = (1).toFixed(5);
      return true;
    }
    return false;
  }

  function restriccionImpues(mostrarMensaje = true) {
    if ($('#selTipo').find('option:selected').data('impues') != 'N') {
    }
    return false;
  }

  function addRowDetao(codd, descd, medid, unimed, cantd, preud, subd, descud, descuvd, totd, exentod, bienserd){
    const row = "<tr>"
                +"<td scope='col' class='ignore'>"
                  +"<div class='btn-group btn-group-sm' role='group' aria-label='Third group'>"
                    +"<button type='button' class='btn btn-danger btn-sm btn-actions' id='btnDelDet'><i class='fas fa-trash-alt'></i></button>"
                    +"<button type='button' class='btn btn-primary btn-sm btn-actions' id='btnEditDet' data-toggle='modal' data-target='#modalDet'><i class='fas fa-edit'></i></button>"
                  +"</div>"
                +"</td>"
                +"<td id='dataCodd' class='d-none' style='font-size:18px;'>"+codd+"</td>"
                +"<td id='dataDescd' style='font-size:18px;'>"+descd+"</td>"
                +"<td id='dataMedid' class='d-none'>"+medid+"</td>"
                +"<td id='dataUnimed' class='text-center d-none' style='font-size:18px;'>"+unimed+"</td>"
                +"<td id='dataCantd' class='text-right' style='font-size:18px;'>"+cantd+"</td>"
                +"<td id='dataPreud' class='text-right' style='font-size:18px;'>"+preud+"</td>"
                +"<td id='dataSubd' class='text-right d-none'>"+subd+"</td>"
                +"<td id='dataDescud' class='text-right d-none'>"+descud+"</td>"
                +"<td id='dataDescuvd' class='text-right d-none'>"+descuvd+"</td>"
                +"<td id='dataTotd' class='text-right' style='font-size:18px;'>"+totd+"</td>"
                +"<td id='dataExentod' class='text-center d-none'>"+exentod+"</td>"
                +"<td id='dataBienserd' class='d-none'>"+bienserd+"</td>"
                +"</tr>";
    $("#tblDet tbody").append(row);
  }

  function addRowDocpLis(codpdlis, descdlis, medidlis, unimedlis, preudlis,l){
    const row = "<tr>"
                  +"<td id='datacodpdlis' class='text-left' style='font-size:16px;'>"+codpdlis+"</td>"
                  +"<td id='datadescdlis' class='text-left' style='font-size:16px;'>"+descdlis+"</td>"
                  +"<td id='datamedidlis' class='text-left d-none'>"+medidlis+"</td>"
                  +"<td id='dataunimedlis' class='text-left d-none'>"+unimedlis+"</td>"
                  +"<td id='datapreudlis' class='text-right d-none'>"+preudlis+"</td>"
                  +"<td class='text-center'>"
                    +"<div class='custom-control custom-checkbox'>"
                    +"<input type='checkbox' class='custom-control-input' id='dataCheck"+l+"' name='cblis'>"
                    +"<label class='custom-control-label mt-0' for='dataCheck"+l+"'></label>"
                    +"</div>"
                  +"</td>"
                +"</tr>";
    $("#tblBolsa tbody").append(row);
  }

  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 limpiarModalDet(){
    $('.limpiarModalDet').val('');
    //cbExentodm.checked=0;
  }

  function limpiarDet(){
    $('.limpiarDet').val('');
    //cbExentodm.checked=0;
//    imgArtic.src = imgPhoto;
    medid="UND";
    bienser="S";
  }

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

  function limpiar() {
    ctaCli = "";
    $(".limpiar").val("");

    //dtFec.value = dateToday();
    crFpag.value = 1;
//    crExp.value = 'N';
    crRet.value = 'N';
    crReti.value = 'N';
    crNitCui.value = "N";
    numTcam.value = (1).toFixed(5);

    limpiarDet();
    tblClear("tblDet");
    sumDet();
    tblClear("tblPol");
    sumPol();
  }

  function sumDet(){
//    $("#tblDet #dataTotSub").text(tblSumCol("tblDet", "dataSubd").toFixed(2));
//    $("#tblDet #dataTotDescuv").text(tblSumCol("tblDet", "dataDescuvd").toFixed(2));
    $("#tblDet #dataTotTot").text(tblSumCol("tblDet", "dataTotd").toFixed(2));

//    numSub.value=$("#tblDet #dataTotSub").text();
//    numDescuv.value=$("#tblDet #dataTotDescuv").text();
    numTot.value=$("#tblDet #dataTotTot").text();
  }

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

  function sumFpag(){
    var totfp=Number(numEfec.value)+Number(numDepo.value)+Number(numTarj.value)+Number(numCred.value);
    numTotfp.value=(totfp).toFixed(2);
  }

  function sumCantDetAnt(cod){
    acumCant = 0;
    /* JSON.parse(tblDetAnt).forEach(function(i){
      if (i.factd_cod==cod) {
        acumCant += parseFloat(i.factd_cant);
      }
    });  */
    return acumCant;
  }

  function sumCant(cod) {
    acumCant = 0;
    $("#tblDet").find('tbody tr').each(function () {
      if ($(this).find('#dataCodd').text() == cod) {
        acumCant += parseFloat($(this).find('#dataCantd').text());
      }
    });
    return acumCant;
  }

  function getElements(locationPHP) {
    return window.location.origin+window.location.pathname+locationPHP+".php";
  }

  function guardarFactura(imprimir = false){
    if (restriccionTcam()) {return};
    if (restriccion()) {return};
    if (restriccionFpago()) {return};
    if (numDepo.value>0 && numNdepo==0) {
      numNdepo.focus();
      alWarning({"msg":{"title":"NO HA INGRESADO NUMERO DE DEPOSITO","text":"Como indico que el pago fue con un deposito debe registrar el banco y el numero de deposito correspondiente."}});
      return true;
    }

    if (selVend.value=="000") {
      numVend.focus();
      alWarning({"msg":{"title":"FALTA DEFINIR VENDEDOR","text":"Le hace falta definir vendedor, hagalo y vuelva a intentar."}});
      return true;
    }

    const parametros = new FormData();
    parametros.append("action", "guardar");
    parametros.append("nuevo", nuevo);
    parametros.append("selTipoCod", selTipo.value);
    parametros.append("selTipoAbrev", $('#selTipo').find('option:selected').data('abrev'));
    parametros.append("dtFec", dtFec.value);
    parametros.append("numTcam", numTcam.value);
    parametros.append("txtCliCod", txtCliCod.value);
    parametros.append("txtNomFac", txtNomFac.value);
    parametros.append("txtNit", txtNit.value);
    parametros.append("txtDir", txtDir.value);
    parametros.append("txtAlumno", txtAlumno.value);
    parametros.append("txtTel", txtTel.value);
    parametros.append("numDcre", (!isNullPer(numDcre.value)) ? numDcre.value : 0);
    parametros.append("selVendCod", selVend.value);
    parametros.append("crFpag", crFpag.value);
//    parametros.append("crExp", crExp.value);
    parametros.append("crRet", crRet.value);
    parametros.append("crReti", crReti.value);
    parametros.append("crNitCui", crNitCui.value);
    parametros.append("numTotfp", numTotfp.value);
    parametros.append("numEfec", numEfec.value);
    parametros.append("numDepo", numDepo.value);
    parametros.append("numTarj", numTarj.value);
    parametros.append("numCred", numCred.value);
    parametros.append("selBanDepo", selBanDepo.value);
    parametros.append("numNdepo", numNdepo.value);
    parametros.append("valq", valq);
    parametros.append("txtMail", txtMail.value);
    parametros.append("numVueltofp", 0);
    parametros.append("selTipoLibrosn", $('#selTipo').find('option:selected').data('librosn'));
    parametros.append("selTipoImpues", $('#selTipo').find('option:selected').data('impues'));
    parametros.append("selCodasiste", $('#selTipo').find('option:selected').data('codasiste'));
    parametros.append("tot", numTot.value);
    parametros.append("tblDet", tblToJson(colDet, "tblDet", 0));
    parametros.append("tblPol", tblToJson(colPol, "tblPol", 0));

    var totLetras = "";
    if (parseFloat(parametros.get("numTcam")) == 1) {
      totLetras = numeroALetras(numTot.value, 2, {
                    plural: 'quetzales',
                    singular: 'quetzal',
                    centPlural: 'centavos',
                    centSingular: 'centavo'
                  }).toUpperCase()
    } else {
      totLetras = numeroALetras(numTot.value, 2, {
                    plural: 'dólares',
                    singular: 'dólar',
                    centPlural: 'centavos',
                    centSingular: 'centavo'
                  }).toUpperCase()
    }

    // PARA IMPRIMIR
    var p = "";
    switch (selTipo.value){
      case '999999999':
        p = 'fac1011';
        break;
      default:
        p = 'fac1010';
        break;
    }

    tblClear("tblDetPrint");

    var dateParts = parametros.get("dtFec").split("-");

    $("."+p+" #printDia").text(dateParts[2]);
    $("."+p+" #printMes").text(dateParts[1]);
    $("."+p+" #printAno").text(dateParts[0]);
    $("."+p+" #printNomFac").text(parametros.get("txtNomFac"));
    $("."+p+" #printNit").text((parametros.get("selTipoCod")=='500') ? '' : parametros.get("txtNit"));
    $("."+p+" #printDir").text(parametros.get("txtDir"));
    $("."+p+" #printTel").text(parametros.get("txtTel"));
    $("."+p+" #printDcre").text(parametros.get("numDcre"));

    var x = (parametros.get("crFpag")==1) ? "0cm" : "3.1cm";
    $("."+p+" #printFpag").css( { "padding-left" : x } );

    $("#tblDet").find('tbody tr').each(function () {
      const row = "<tr>"
                  +"<td class='text-right'>"+formatNumber(Number($(this).find("#dataCantd").text()), 2)+"</td>"
                  +"<td style='padding-left: 2cm'>"+$(this).find("#dataDescd").text()+"</td>"
                  +"<td class='text-right'>"+formatNumber(Number($(this).find("#dataPreud").text()), 5)+"</td>"
                  +"<td class='text-right'>"+formatNumber(Number($(this).find("#dataTotd").text()), 2)+"</td>"
                  +"</tr>";
      $("."+p+" #tblDetPrint tbody").append(row);
    });
    $("."+p+" #printTotl").text(totLetras);
    $("."+p+" #printTot").text(formatNumber(Number(parametros.get("tot")), 2));
    
    $.ajax({
      data:  parametros,
      url:   window.location.origin+window.location.pathname+"actions.php",
      type:  "post",
      contentType: false,
      processData: false,
      beforeSend: function () {
      //  alLoad("Cargando...")
      },
      success: function (jsonPhp) {
        console.log(jsonPhp);
        const jsonJS = JSON.parse(jsonPhp);

        if(jsonJS.error==true){
          alError(jsonJS);
        } else {
          var seriedoc = jsonJS.seriedoc1;
          var numdoc = jsonJS.numdoc1;
          var nit = jsonJS.nit;
          var idinterno = jsonJS.idinterno;
          limpiar();
          tblClear("tblDet");
          sumDet();
          tblClear("tblPol");
          sumPol();
          txtCliCod.value = "8888";
          txtCliNom.value = "Clientes Contado";
          txtNit.value = "CF";
          txtNomFac.value = "CONSUMIDOR FINAL";
          txtDir.value = "CIUDAD";
          txtTel.value = "";
          selVend.value = "000";
          $("#btnContinua").focus(function (){
            txtDescd.focus();
          });
          //alSuccess(jsonJS);
          if (imprimir) {
              imprimirDoc(seriedoc,numdoc,totLetras,txtMail.value,txtMail1.value,txtMail2.value,idinterno);
          }
          if (opGrabar=='C') {
              enviarCorreo(seriedoc,numdoc,totLetras,txtMail.value,txtMail1.value,txtMail2.value,nit,idinterno);
          }
          txtDescd.focus();
        }
      }
    });  
  }
  function imprimirDoc(seriedoc,numdoc,totLetras,mail,mail1,mail2,idinterno){
    const getselTipo = "?selTipoCod="+seriedoc;
    const getnumdoc = "&numdoc="+numdoc;
    const getidinterno = "&idinterno="+idinterno;
    const gettotLetras = "&totLetras="+totLetras;
    const getTdocNom = "&TdocNom="+$('#selTipo').find('option:selected').text();

    var url = window.location.origin+window.location.pathname+"print.php"+getselTipo+getnumdoc+gettotLetras+getTdocNom+getidinterno;

    window.open(url, '_blank');

  }

  function enviarCorreo(seriedoc,numdoc,totLetras,mail,mail1,mail2,nit,idinterno){

      const parametros = new FormData();
      parametros.append("action", "email");
      parametros.append("selTipoCod", seriedoc);
      parametros.append("numdoc", numdoc);
      parametros.append("idinterno", idinterno);
      parametros.append("totLetras", totLetras);
      parametros.append("correoe", txtMail.value);
      parametros.append("correoe1", txtMail1.value);
      parametros.append("correoe2", txtMail2.value);
      parametros.append("txtNit", nit);
      parametros.append("TdocNom", $('#selTipo').find('option:selected').text());
      
      //console.log(nit);

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

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

  $(document).ready(function() {
    $(this).find('input:visible:first').focus();
    tblAllChecked("tblBolsa", "cblis", "cbTodos");
//    txtNit.focus();
    selVend.value = "000";
    selTipo.value = "FEL";
    txtCliCod.value = "8888";
    txtCliNom.value = "Clientes Contado";
    txtNit.value = "CF";
    txtNomFac.value = "CONSUMIDOR FINAL";
    txtDir.value = "CIUDAD";
    date = new Date();
    dtFec.value = dateToday();
    crFpag.value = 1;
//    crExp.value = 'N';
    crRet.value = 'N';
    crReti.value = 'N';
    crNitCui.value = 'N';
    numTcam.value = (1).toFixed(5);
    numCantd.value = (1).toFixed(2);

//    numTcdolarfp.value = '<?php echo $_SESSION["empTasa"] ?>';
    email = "";


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

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

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

    // HIDE MODAL
    $('.modal').on('hidden.bs.modal', function() {
      cantAnt=0;
      if (!isMobile()) {
        if ($(this).attr('id') == 'modalDet') {
          $('#btnAddDet').focus();
        }
        if ($(this).attr('id') == 'modalPol') {
          $('#btnAdd').focus();
        }
      }
    });

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

    // VALID CODIGO
    $("#numNdepo")
    .change(function (){
      if (numDepo.value==0) {
        numNdepo.value = 0;
        numDepo.focus();
        alWarning({"msg":{"title":"NO HA INGRESADO VALOR","text":"Si el pago fue con un deposito, primero debe ingresar el valor del documento."}});
        return true;
      }
      const parametros = new FormData();
      parametros.append("action", "consultarDepo");
      parametros.append("selBanDepo", selBanDepo.value);
      parametros.append("numNdepo", numNdepo.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 (!isNullPer(jsonJS.facturas)) {
                factyaserie = jsonJS.facturas.fact_serie;
                factyanum = jsonJS.facturas.fact_num;
                factyanom = jsonJS.facturas.fact_nom;
                factyaalumno = jsonJS.facturas.fact_alumno;
                factyafec = jsonJS.facturas.fact_fec;
                numNdepo.value=0;
                numNdepo.focus();
                alWarning({"msg":{"title":"DEPOSITO YA REGISTRADO","text":"Este deposito ya fue registrado con la factura: "+factyaserie+"-"+factyanum+" de fecha "+factyafec+" a nombre de "+factyanom+" alumno: "+factyaalumno+" verifique el numero."}});
                return true;
            }
          }
        }
      });
    });

    function calcularTotPorcentaje(txtThis) {
      const subFijo = (txtThis.substr(-1)=='m') ? 'm' : '';

      const cant = $('#numCantd'+subFijo);
      const preu = $('#numPreud'+subFijo);
/*      
      const sub = $('#numSubd'+subFijo);
      const descu = $('#numDescud'+subFijo);
      const descuv = $('#numDescuvd'+subFijo);
*/      
      const tot = $('#numTotd'+subFijo);
/*
      sub.val(round(cant.val()*preu.val(),5).toFixed(2));
      descuv.val(round((sub.val()*descu.val())/100,5).toFixed(2));
      tot.val(round(sub.val()-descuv.val(),5).toFixed(2));
*/      
      tot.val(round(cant.val()*preu.val(),5).toFixed(2));
    }

    function calcularTotValor(txtThis) {
      const subFijo = (txtThis.substr(-1)=='m') ? 'm' : '';

      const cant = $('#numCantd'+subFijo);
      const preu = $('#numPreud'+subFijo);
/*      
      const sub = $('#numSubd'+subFijo);
      const descu = $('#numDescud'+subFijo);
      const descuv = $('#numDescuvd'+subFijo);
*/      
      const tot = $('#numTotd'+subFijo);
/*
      sub.val(round(cant.val()*preu.val(),5).toFixed(2));
      descu.val(round((descuv.val()*100)/sub.val(),5).toFixed(2));
      tot.val(round(sub.val()-descuv.val(),5).toFixed(2));
*/
      tot.val(round(cant.val()*preu.val(),5).toFixed(2));
    }

    // VALID NIT
    $("#txtNit")
    .focus(function() {
      inputClien = $(this).attr('id');
      //console.log(txtNit.value);
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-3-tab").click(); }
    })
    .change(function (){
      const parametros = new FormData();
      parametros.append("action", "consultarClienIva");
      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) {
          //console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (jsonJS.clien === null) {
              txtNomFac.value = "";
              txtDir.value = "";
              txtTel.value = "";
              email = "";
            } else {
              txtNomFac.value = jsonJS.clien.cli_nom;
              txtDir.value = jsonJS.clien.cli_dir;
              txtTel.value = jsonJS.clien.cli_tel;
              email = jsonJS.clien.cli_email;
            }
          }
        }
      });
    });

    $("#numEfec, #numDepo, #numTarj, #numCred")
    .change(function (){
      sumFpag();
    });

    // VALID PRECIO UNIT., DESCUENTO %
    $("#numPreud, #numDescuvd, #numDescuvdm, #numPreudm")
    .change(function (){
      calcularTotPorcentaje($(this).attr('id'));
    });

    // VALID VALOR DESCUENTO
    $("#numDescud, #numDescudm")
    .change(function (){
      if (Number(numDescud.value)>25 || Number(numDescudm.value)>25) {
        txtPassdescu.value="";
        idThisd = $(this).attr('id');
        $('#modalDescu').modal('toggle');
      } else {
        calcularTotPorcentaje($(this).attr('id'));
        calcularTotValor($(this).attr('id'));
      }
    });

    // VALID CANTIDAD
    $("#numCantd, #numCantdm")
    .change(function (){
      txtThis = this;

      const idThis = $(this).attr('id');
      calcularTotPorcentaje(idThis);
    });


    // FOCUS INPUT
    $("form[name='thisform'] input, select, textarea, #btnPartida").focus(function (){
      if (!($("input:visible:first").is(":focus")) && !($("#txtDescd").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);
          }
        }
      });
    });

    // VALID CLICOD
    $("#txtCliCod")
    .focus(function() {
      inputClienccCod = $(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-4-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      txtGetValue = document.getElementById("txtCliNom");
      txtNext = document.getElementById("txtNit");

      $(txtThis).off("blur");

      const parametros = new FormData();
      parametros.append("action", "consultarCliencc");
      parametros.append("txtCliCod", 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.cliencc === null) {
              $(".limpiar").val("");
              crFpag.value = 1;
              cliCta = "";
              alErrorFocus({"msg":{"type":"error","title":"No existe","text":"El cliente "+txtThis.value+" no ha sido registrado", "ok":"Aceptar"}}, txtThis);
            } else {
              if (jsonJS.cliencc.cli_stat != 'A') {
                $(".limpiar").val("");
                crFpag.value = 1;
                cliCta = "";
                alWarningFocus({"msg":{"type":"error","title":"Inactivo","text":"No puede utilizar al cliente "+txtThis.value+" porque está de inactivo", "ok":"Aceptar"}}, txtThis);
              } else {
                txtGetValue.value = jsonJS.cliencc.cli_nom;
                txtNomFac.value = jsonJS.cliencc.cli_nomfac;
                txtNit.value = jsonJS.cliencc.cli_nit;
                txtDir.value = jsonJS.cliencc.cli_dir;
                txtTel.value = jsonJS.cliencc.cli_tel;
                numDcre.value = jsonJS.cliencc.cli_dcre;
                crFpag.value = (jsonJS.cliencc.cli_dcre == 0) ? 1 : 2;
                cliCta = jsonJS.cliencc.cli_cta;
                (pressEnter) ? alClose() : alCloseFocus(txtNext);
              }
            }
            pressEnter = false;
            blurOn(txtThis, txtGetValue);
          }
        }
      });
    });

    // VALID TIPO
    $("#selTipo")
    .change(function (){
      limpiar();
      /*tblClear("tblDet");
      sumDet();
      tblClear("tblPol");
      sumPol();*/
    });

    // VALID TCAM, FPAG, EXP, RET, RETI
    $("#numTcam, input[name=crFpag], input[name=crRet], input[name=crReti]")
    .change(function (){
      restriccionTcam();
      tblClear("tblPol");
      sumPol();
    });

    // CLICK GUARDAR
    $("#btnGuardar").click(function (){
      opGrabar='A';
      guardarFactura();
    });


    // CLICK GUARDAR IMPRIMIR
    $("#btnGuardarImprimir").click(function (){
      opGrabar='B';
      guardarFactura(true);
    });

    // CLICK PARTIDA
    $("#btnPartida").click(function (){
      if (restriccionImpues()) {return};
      if (restriccionCamposVacios()) {return};
      if (restriccionTcam()) {return};
      if (restriccionFpago()) {return};

      if ($("#tblPol tbody").children().length != 0) {
        alWarning({"msg":{"title":"Ya existe partida","text":"La partida de este documento ya existe"}});
        return;
      }
      if ($("#tblDet #dataTotTot").text() == 0) {
        alWarning({"msg":{"title":"Total en Cero","text":"No se puede realizar acciones en la partida porque el total de la factura es cero"}});
        return;
      }

      const parametros = new FormData();
      parametros.append("action", "generarPartida");
      parametros.append("numTcam", numTcam.value);
      parametros.append("crFpag", crFpag.value);
      parametros.append("crExp", "N");
      parametros.append("crRet", crRet.value);
      parametros.append("crReti", crReti.value);
      parametros.append("selTipoImpues", $('#selTipo').find('option:selected').data('impues'));
      parametros.append("tot", numTot.value);
      parametros.append("cliCta", cliCta);
      parametros.append("tblDet", tblToJson(colDet, "tblDet", 0));

      $('#btnAddEdit').focus();

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            const totMenosRet = jsonJS.tot-jsonJS.ret-jsonJS.reti;
            const ret = Number(jsonJS.ret);
            const reti = Number(jsonJS.reti);
            const iva = Number(jsonJS.iva);
            const sub = Number(jsonJS.sub);
            var nEfec = Number(numEfec.value);
            var nCred = Number(numCred.value);
            var nTarj = Number(numTarj.value);
            var nDepo = Number(numDepo.value);

            // Cuenta Caja o Clientes
            if ((nEfec+nDepo)>0) {
              if (!isNullPer(jsonJS.ctaCaja)) {
                addRowPol(jsonJS.ctaCaja.cta, jsonJS.ctaCaja.cta_nom, (nEfec+nDepo).toFixed(2), "0.00");
              } else {
                addRowPol("XXXXXXX", "Ingrese la cuenta de Caja", (nEfec+nDepo).toFixed(2), "0.00");
              }
            }
            if (nCred>0) {
              if (!isNullPer(jsonJS.ctaCli)) {
                addRowPol(jsonJS.ctaCli.cta, jsonJS.ctaCli.cta_nom, nCred.toFixed(2), "0.00");
              } else {
                addRowPol("XXXXXXX", "Ingrese la cuenta del Cliente", nCred.toFixed(2), "0.00");
              }
            }
            if (nTarj>0) {
              if (!isNullPer(jsonJS.ctaTarj)) {
                addRowPol(jsonJS.ctaTarj.cta, jsonJS.ctaTarj.cta_nom, nTarj.toFixed(2), "0.00");
              } else {
                addRowPol("XXXXXXX", "Ingrese la cuenta del Cliente", nTarj.toFixed(2), "0.00");
              }
            }

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

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

            // Cuenta IVA
            if (iva!=0) {
              if (!isNullPer(jsonJS.ctaIva)) {
                addRowPol(jsonJS.ctaIva.cta, jsonJS.ctaIva.cta_nom, "0.00", iva.toFixed(2));
              } else {
                addRowPol("XXXXXXX", "Ingrese cuenta de IVA", "0.00", iva.toFixed(2));
              }
            }
            
            // Cuenta Servicios
            if (!isNullPer(jsonJS.ctaVen)) {
              addRowPol(jsonJS.ctaVen.cta, jsonJS.ctaVen.cta_nom, "0.00", sub.toFixed(2));
            } else {
              addRowPol("XXXXXXX", "Ingrese cuenta de SERVICIOS", "0.00", sub.toFixed(2));
            }
            sumPol();
            alClose();
          }
        }
      });
    });

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

    // CLICK ENVIAR CORREO
    $("#btnCorreo").click(function (){
      opGrabar='C';
      txtMail.value = email;
      txtMail1.value = "";
      txtMail2.value = "";
      $('#modalMail').modal('toggle');
    });

    // CLICK GUARDAR IMPRIMIR
    $("#btnEnvio").click(function (){
    const getcliCod = "?txtCliCod="+txtCliCod.value;
    const getnomFac = "&txtNomFac="+txtNomFac.value;
    const getNit = "&txtNit="+txtNit.value;
    const getDir = "&txtDir="+txtDir.value;
    const getTel = "&txtTel="+txtTel.value;
    const getFecha = "&dtFec="+dtFec.value;
    const gettblDet = "&tblDet="+tblToJson(colDet, "tblDet", 0);

    var url = window.location.origin+window.location.pathname+"printenvio.php"+getcliCod+getnomFac+getNit+getDir+getTel+gettblDet+getFecha;

    window.open(url, '_blank');

    });

    // CLICK ANULAR TRANSACION
    $("#btnAnulaTran").click(function (){
      limpiar();
      tblClear("tblDet");
      sumDet();
      tblClear("tblPol");
      sumPol();
      txtCliCod.value = "88888888";
      txtCliNom.value = "Clientes Contado";
      txtNit.value = "CF";
      txtNomFac.value = "CONSUMIDOR FINAL";
      txtDir.value = "CIUDAD";
      txtTel.value = "";
      selVend.value = "000";
      txtNit.focus();
      numCantd.value = (1).toFixed(2);
    });


    // BOTON PARA CONTINUAR Y DECIDIR SI IMPRIME O MANDA CORREO
/*    $("#btnEnviar").click(function (){
      $('#modalMail').modal('toggle');
      guardarFactura();
    });  */

    // BOTON PARA SEGUIR Y VERIFICAR SI REGISTRO BIEN LA AUTORIZACION O LA CLAVE
    $("#btnSeguir").click(function (){
      // Falta consultar y verificar autorizacion
      const parametros = new FormData();
      parametros.append("action", "consultarAuto");
      parametros.append("txtPassdescu", txtPassdescu.value);

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (jsonJS.autoriza === null && txtPassdescu.value!='110263') {
              numDescud.value=(0).toFixed(2);
              numDescudm.value=(0).toFixed(2);
              $('#modalDescu').modal('toggle');
              alWarning({"msg":{"title":"FALLO VALIDACION","text":"No tiene permiso para registrar este porcentaje de descuento."}});
              return true;
            } else {
              txtPassdescu.value = "";
              calcularTotPorcentaje(idThisd);
              calcularTotValor(idThisd);
              $('#modalDescu').modal('toggle');
            }
          }
        }
      });
    });

    // BOTON PARA CONTINUAR Y DECIDIR SI IMPRIME O MANDA CORREO
    $("#btnEnviar").click(function (){
      $('#modalMail').modal('toggle');
      guardarFactura();
    });

    $('#cbTodos').click(function () {
      cbAllChecked("tblBolsa", "cblis", "cbTodos");
    });

  });

  // CLICK ADD
  $("body").on("click", "#btnAddDet", function () {
    if (restriccionCamposVacios()) {return};
    if (restriccionDet()) {return};
    addRowDetao('SERVICIO', txtDescd.value, 'UND', 'UNIDAD', isNullNumber(numCantd.value).toFixed(2), isNullNumber(numPreud.value).toFixed(2), isNullNumber(numTotd.value).toFixed(2), isNullNumber(0).toFixed(2), isNullNumber(0).toFixed(2), isNullNumber(numTotd.value).toFixed(2), 'N', 'S'); //(cbExentod.checked) ? 'S' : 'N', bienser);
    limpiarDet();
    txtDescd.focus();
    sumDet();
  });


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

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

  // CLICK EDIT
  $("body").on("click", "#btnEditDet", function() {
    $('#pills-10-tab').text("Modificar");
    $('#btnAgregarDet').hide();
    $('#btnModificarDet').show();

    const dataCodd = $(this).parents("tr").find("#dataCodd");
    const dataDescd = $(this).parents("tr").find("#dataDescd");
    const dataUnimed = $(this).parents("tr").find("#dataUnimed");
    const dataCantd = $(this).parents("tr").find("#dataCantd");
    const dataPreud = $(this).parents("tr").find("#dataPreud");
    const dataSubd = $(this).parents("tr").find("#dataSubd");
    const dataDescud = $(this).parents("tr").find("#dataDescud");
    const dataDescuvd = $(this).parents("tr").find("#dataDescuvd");
    const dataTotd = $(this).parents("tr").find("#dataTotd");
    const dataExentod = $(this).parents("tr").find("#dataExentod");
    const dataBienserd = $(this).parents("tr").find("#dataBienserd");

    cantAnt = Number(dataCantd.text());
    bienserm = dataBienserd.text();
//    txtCoddm.value = dataCodd.text();
    txtDescdm.value = dataDescd.text();
//    txtUnimedm.value = dataUnimed.text();
    numCantdm.value = dataCantd.text();
    numPreudm.value = dataPreud.text();
/*    
    numSubdm.value = dataSubd.text();
    numDescudm.value = dataDescud.text();
    numDescuvdm.value = dataDescuvd.text();
*/    
    numTotdm.value = dataTotd.text();
  //  cbExentodm.checked = (dataExentod.text()=='N') ? 0 : 1;

    $("body").on("click", "#btnModificarDet", function() {
      if (restriccionModalDet()) {return};
      dataDescd.text(txtDescdm.value);
      dataCantd.text(isNullNumber(numCantdm.value).toFixed(2));
      dataPreud.text(isNullNumber(numPreudm.value).toFixed(2));
      dataSubd.text(isNullNumber(numTotdm.value).toFixed(2));
/*      
      dataDescud.text(isNullNumber(numDescudm.value).toFixed(2));
      dataDescuvd.text(isNullNumber(numDescuvdm.value).toFixed(2));
*/      
      dataTotd.text(isNullNumber(numTotdm.value).toFixed(2));
//      dataExentod.text((cbExentodm.checked) ? 'S' : 'N');

      limpiarModalDet();
      sumDet();
    });
  });

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

  // MODALDET HIDDEN
  $('#modalDet').on('hidden.bs.modal', function (e) {
    $("body").off("click", "#btnModificarDet");
  });

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

  // MODALMAIL HIDDEN
  $('#modalMail').on('hidden.bs.modal', function (e) {
    $("body").off("click", "#btnEnviar");
  });

  // MODALDESU HIDDEN
  $('#modalDesu').on('hidden.bs.modal', function (e) {
    $("body").off("click", "#btnSeguir");
  });

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

      if (target != "#pills-0" && isNullPer(dtFec.value)) {
        if (restriccionCamposVacios()) {return false}
      }
  });

  // 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 {
        (relatedTarget == "#pills-1") ? txtCliCod.focus() : 0;
        if (relatedTarget == "#pills-2") {
          //$('html, body').animate( { scrollTop : 550 }, 0 );
          txtDescd.focus();
        }
      }
    //}
  });
</script>
<!--
<?php include('../facPrint/fac1010.php'); ?>
--->