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

$empCod = $_SESSION['empCod'];
$usuCod = $_SESSION['usuCod'];

# QUERYS
$sTipov = "SELECT 
            TRIM(tv.tv_cod) AS tv_cod,
            TRIM(tv.tv_nom) AS tv_nom,
            TRIM(tv.tv_abrev) AS tv_abrev,
            tv_librosn,
            tv_impues,
            tv_soloinv
           FROM tipov tv WHERE tv_soloinv='S' AND tv_cod='999'";


$sVendedor = "SELECT * FROM vendedor v INNER JOIN usuarios u ON v.vend_cod=u.usu_vend where u.usu_cod='$usuCod'";
$sBodegas = "SELECT * FROM bodegas where bod_emp='$empCod' ORDER BY bod_cod";
# EJECUCION DE QUERYS
$db = new dbExec();
$select["tipov"] = $db->query($sTipov);
$select["vendedor"] = $db->query($sVendedor);
$select["bodegas"] = $db->query($sBodegas);
$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 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-sm-4 col-xl-3">
                          <label class="font-size-sm text-success" for="txtCoddm">Código</label>
                          <input type="text" class="form-control form-control-sm form-control-as limpiarModalDet" id="txtCoddm" maxlength="20" disabled>
                        </div>
                        <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" disabled>
                        </div>
                        <div class="col-md-3 col-xl-2">
                          <label class="font-size-sm text-success" for="txtUnimedm">Medida</label>
                          <input type="text" class="form-control form-control-sm form-control-as limpiarModalDet" id="txtUnimedm" maxlength="20" disabled>
                        </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="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-6">
                              <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-5 limpiarModalDet" id="numPreudm" placeholder="0.00">
                            </div>
                            <div class="col-12">
                              <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">
                            </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>

      <div class="container-as">
        <div class="row">
          <div class="col">
            <ul class="nav nav-pills mb-1" id="pills-tab" role="tablist">
              <li class="nav-item">
                <a class="nav-link active" id="pills-0-tab" data-toggle="pill" href="#pills-0" role="tab" aria-controls="pills-0" aria-selected="true">Mantenimiento</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" id="pills-1-tab" data-toggle="pill" href="#pills-1" role="tab" aria-controls="pills-1" aria-selected="true">Buscar Cliente</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" id="pills-2-tab" data-toggle="pill" href="#pills-2" role="tab" aria-controls="pills-2" aria-selected="true">Buscar Artículo</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 align-items-center">
                          <div class="col-md-7">
                            <div class="form-row align-items-end">
                              <div class="col-md-8">
                                <label for="selTipo">Tipo</label>
                                <select class="form-control form-control-md form-control-as" name="selTipo" id="selTipo">
                                  <?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']} data-soloinv={$rec['tv_soloinv']}>".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-soloinv="'.$rec['tv_soloinv'].'">'.utf8_encode($rec['tv_nom']).'</option>';
                                    }
                                  ?>
                                </select>
                              </div>
<!--                               <div class="col-6 col-md-4">
                                <label for="numNum">Número</label>
                                <input type="number" class="form-control form-control-sm form-control-as dec-0" id="numNum" placeholder="0">
                              </div>   -->
                              <div class="col-6 col-md-4">
                                <label 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-8">
                                <label for="selBodSal">Bodega Salida</label>
                                <select class="form-control form-control-sm form-control-as" name="selBodSal" id="selBodSal">
                                  <?php
                                    while ($rec = $db->fetchAssoc($select['bodegas'])) {
                                      echo  "<option value={$rec['bod_cod']}>".utf8_encode($rec['bod_nom']).'</option>';
                                    }
                                  ?>
                                </select>
                              </div>
                            </div>
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-md-3">
                            <label 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-9">
                            <label for="txtCliNom"></label>
                            <input type="text" class="form-control form-control-sm form-control-as form-info limpiar" id="txtCliNom" disabled>
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-md-9">
                            <label 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-md-3">
                            <label for="txtNit">NIT</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtNit">
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-12">
                            <label 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 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 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 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">
                          </div>
                          <div class="col-md-4">
                            <label for="selVend">Vendedor</label>
                            <select class="form-control form-control-md form-control-as" name="selVend" id="selVend">
                              <?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-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" disabled>
                              <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" disabled>
                              <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" disabled>
                              <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" disabled>
                              <label class="custom-control-label" for="crReti2">No</label>
                            </div>
                          </div>
                        </div>

                        <div class="form-row">
                          <div class="col-12">
                            <label for="txtObs">Observación</label>
                            <textarea class="form-control form-control-sm form-control-as limpiar" id="txtObs" rows="3"></textarea>
                          </div>
                        </div>
                      </div>

                      <div class="form-group">
                        <h4 class="text-success">DETALLE DEL DOCUMENTO:</h4>
                        <div class="form-row align-items-end">
                          <div class="col-sm-4 col-xl-3">
                            <label class="font-size-sm text-success" for="txtCodd">Código</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiarDet" id="txtCodd" maxlength="20">
                          </div>
                          <div class="col-md-9 col-xl-7">
                            <label class="font-size-sm text-success" for="txtDescd">Descripción</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiarDet" id="txtDescd" maxlength="120" disabled>
                          </div>
                          <div class="col-md-3 col-xl-2">
                            <label class="font-size-sm text-success" for="txtUnimed">Medida</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiarDet" id="txtUnimed" maxlength="20" disabled>
                          </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="numCantd">Cantidad</label>
                                <input type="number" class="form-control form-control-sm form-control-as dec-2 limpiarDet" id="numCantd" placeholder="0.00">
                              </div>
                              <div class="col-6">
                                <label class="font-size-sm text-success" for="numPreud">Precio Unit.</label>
                                <input type="number" class="form-control form-control-sm form-control-as dec-5 limpiarDet" id="numPreud" placeholder="0.00">
                              </div>
                              <div class="col-12">
                                <label class="font-size-sm text-success" for="numSubd">Sub-Total</label>
                                <input type="number" class="form-control form-control-sm form-control-as dec-5 limpiarDet" id="numSubd" 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="numDescud">Descuento %</label>
                                <input type="number" class="form-control form-control-sm form-control-as dec-2 limpiarDet" id="numDescud" placeholder="0.00">
                              </div>
                              <div class="col-6">
                                <label class="font-size-sm text-success" for="numDescuvd">Valor Descuento</label>
                                <input type="number" class="form-control form-control-sm form-control-as dec-2 limpiarDet" id="numDescuvd" placeholder="0.00">
                              </div>
                              <div class="col-12">
                                <label class="font-size-sm text-success" for="numTotd">Total</label>
                                <input type="number" class="form-control form-control-sm form-control-as dec-5 limpiarDet" id="numTotd" 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="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="40">ACCIONES</th>
                                    <th scope="col" class="text-center" width="90">CODIGO</th>
                                    <th scope="col" class="text-center" width="200">DESCRIPCIÓN</th>
                                    <th scope="col" class="text-center" width="70">MEDIDA</th>
                                    <th scope="col" class="text-center" width="70">CANTIDAD</th>
                                    <th scope="col" class="text-center" width="70">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" 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"></th>
                                  <th scope="col"></th>
                                  <th scope="col" class="text-right">Totales</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">0.00</th>
                                </tfoot>
                              </table>
                            </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 for="numSub">Suma de Unidades</label>
                          </div>
                          <div class="col-6">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar text-right" id="numSumUni" placeholder="0.00" min="0" disabled>
                          </div>
                          <div class="col-6">
                            <label for="numSub">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" id="numSub" placeholder="0.00" min="0" disabled>
                          </div>
                          <div class="col-6">
                            <label for="numDescuv">Valor Desc.</label>
                          </div>
                          <div class="col-6">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar text-right" id="numDescuv" placeholder="0.00" min="0" disabled>
                          </div>
                          <div class="col-6">
                            <label for="numTot">Total</label>
                          </div>
                          <div class="col-6">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar text-right" id="numTot" placeholder="0.00" min="0" disabled>
                          </div>
                        </div>

                        <div class="form-row">
                          <div class="col-12 mt-2">
                            <button class="btn btn-info btn-block" id="btnGuardarImprimir" type="button">Imprimir / Guardar</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-success btn-block" id="btnGuardar" type="button">Guardar</button>
                          </div>
<!--                          <div class="col-12 mt-2">
                            <button class="btn btn-danger btn-block" id="btnAnular" type="button">Anular</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-primary btn-block" id="btnBorrar" type="button">Borrar</button>
                          </div>  --->
                          <div class="col-12">
                            <div class="form-row">
                              <div class="col-2"></div>
                              <div class="col-8 col-sm-12 text-center mt-3">
                                <div class="upload-btn-wrapper text-center" style="width: 100%; height: 220px;">
                                  <img class="rounded-lg" name="imgArtic" width="100%" height="100%" style="object-fit: cover;" />
                                </div>
                              </div>
                            </div>
                          </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>
          </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 inputArtic = "txtCodd";

  var cliCta = "";
  var medid = "";
  var cantAnt = 0;
  var bienser = "";
  var bienserm = "";
  var imgPhoto = "../../img/photo.jpg";
  imgArtic.src = imgPhoto;
  
  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;

  const crFpag = document.thisform.crFpag;
  const crRet = document.thisform.crRet;
  const crReti = document.thisform.crReti;
  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;
      }
      if (numTot.value == 0) {
        alWarning({"msg":{"title":"Total en Cero","text":"No se puede guardar porque el total del Documento es cero"}});
        return true;
      }
      if (!restriccionImpues(false)) {
      }
    } else {
      /*if (isNullPer(txtCliCod.value) || isNullPer($('#tblPol #dataTot').text())) {
        return true;
      }*/
    }
    return false;
  }

  function restriccionCamposVacios() {
  }

  function restriccionModalDet() {
    if (isNullPer(txtCoddm.value)) {
      txtCoddm.value = "";
      txtCoddm.focus();
      alWarningTimer({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CÓDIGO","timer":timeOutWarningSm}});
      return true;
    }
    if (isNullPer(txtDescdm.value)) {
      txtDescdm.value = "";
      txtDescdm.focus();
      alWarningTimer({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar la DESCRIPCIÓN","timer":timeOutWarningSm}});
      return true;
    }
    $('#modalDet').modal('toggle');
    return false;
  }

  function restriccionDet() {
    if (isNullPer(txtCodd.value)) {
      txtCodd.value = "";
      txtCodd.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CÓDIGO"}});
      return true;
    }
    if (isNullPer(txtDescd.value)) {
      txtDescd.value = "";
      txtDescd.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar la DESCRIPCIÓN"}});
      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') {
      if (mostrarMensaje) {
        alWarning({"msg":{"title":"Exento de Impuesto","text":"Los documentos exentos de impuestos no necesitan partida"}});
      }
      return true;
    }
    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'>"+codd+"</td>"
                +"<td id='dataDescd'>"+descd+"</td>"
                +"<td id='dataMedid' class='d-none'>"+medid+"</td>"
                +"<td id='dataUnimed'>"+unimed+"</td>"
                +"<td id='dataCantd' class='text-right'>"+cantd+"</td>"
                +"<td id='dataPreud' class='text-right'>"+preud+"</td>"
                +"<td id='dataSubd' class='text-right'>"+subd+"</td>"
                +"<td id='dataDescud' class='text-right'>"+descud+"</td>"
                +"<td id='dataDescuvd' class='text-right'>"+descuvd+"</td>"
                +"<td id='dataTotd' class='text-right'>"+totd+"</td>"
                +"<td id='dataExentod' class='text-center'>"+exentod+"</td>"
                +"<td id='dataBienserd' class='d-none'>"+bienserd+"</td>"
                +"</tr>";
    $("#tblDet 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="";
    bienser="";
  }

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

  function limpiar(tfNumEnv = false) {
    ctaCli = "";
    $(".limpiar").val("");
    dtFec.value = dateToday();
    crFpag.value = 1;
    crExp.value = 'N';
    crRet.value = 'N';
    crReti.value = 'N';
    numTcam.value = (1).toFixed(5);

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

  function sumDet(){
    numSumUni.value = tblSumCol("tblDet", "dataCantd").toFixed(2);
    $("#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 sumCantDetAnt(cod){
    acumCant = 0;
/*    JSON.parse(tblDetAnt).forEach(function(i){
      if (i.factd_cod==cod) {
        acumCant += parseFloat(i.factd_cant);
      }
    });  */
    return acumCant;
  }

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

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

    var seriedoc = $('#selTipo').find('option:selected').data('abrev');
    var numdoc = 0;

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

    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("numNum", 0);
    parametros.append("dtFec", dtFec.value);
    parametros.append("selBodSalCod", selBodSal.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("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("txtObs", txtObs.value);
    parametros.append("selTipoLibrosn", $('#selTipo').find('option:selected').data('librosn'));
    parametros.append("selTipoRelatd", $('#selTipo').find('option:selected').data('relatd'));
    parametros.append("selTipoImpues", $('#selTipo').find('option:selected').data('impues'));
    parametros.append("tot", numTot.value);
    parametros.append("tblDet", tblToJson(colDet, "tblDet", 0));
    parametros.append("tblPol", tblToJson(colPol, "tblPol", 0));

    parametros.append("tblDetAnt", tblDetAnt);
    parametros.append("tblPolAnt", tblPolAnt);

    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 = "";
    if ($('#selTipo').find('option:selected').data('soloinv') == 'S') {
        p = 'fac1011';
    } else {
        p = 'fac1010';
    }  

/*    switch ($(this).find('option:selected').data('soloinv')){
      case 'S':
        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.4cm";
    $("."+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()+" - "+$(this).find("#dataCodd").text()+"</td>"
                  +"<td class='text-right'>"+formatNumber(Number($(this).find("#dataPreud").text()), 2)+"</td>"
                  +"<td class='text-right'>"+formatNumber(Number($(this).find("#dataTotd").text()), 2)+"</td>"
                  +"</tr>";
      $("."+p+" #tblDetPrint tbody").append(row);
    });
    //  Para agregar el total de unidados en la factura

    const row = "<tr>"
               +"<td class='text-right'>"+''+"</td>"
               +"<td style='padding-left: 6cm'>"+'TOTAL DE UNIDADES ------>'+"</td>"
               +"<td class='text-right'>"+formatNumber(Number(numSumUni.value), 2)+"</td>"
               +"<td class='text-right'>"+''+"</td>"
               +"</tr>";
    $("."+p+" #tblDetPrint tbody").append(row);

    $("."+p+" #printTotl").text(totLetras);
    $("."+p+" #printTot").text(formatNumber(Number(parametros.get("tot")), 2));
    
//    selTipo.focus();

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

        if(jsonJS.error==true){
          alError(jsonJS);
        } else {
          var idinterno = jsonJS.idinterno;
          numdoc=jsonJS.numdoc;
          $("#btnGuardar, #btnGuardarImprimir").focus(function (){
            dtFec.focus();
          });
          //alSuccess(jsonJS);
          if (imprimir) {
              imprimirDoc(seriedoc,numdoc,totLetras,idinterno);
          }
        }
      }
    });
  }

  function imprimirDoc(seriedoc,numdoc,totLetras,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');

  }


  $(document).ready(function() {
    $(this).find('select:visible:first').focus();
    selTipo.value = "999";
    date = new Date();
    dtFec.value = dateToday();
    crFpag.value = 1;
    crExp.value = 'N';
    crRet.value = 'N';
    crReti.value = 'N';
    numTcam.value = (1).toFixed(5);

    // SHOW MODAL
    $('#modalDet, #modalPol').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
    $("#txtCodd")
    .focus(function() {
      inputArtic = $(this).attr('id');
      imgArtic.src = imgPhoto;
    })
    .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-2-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      txtGetValue = txtDescd;

      if (isNullPer(txtThis.value)) {
        limpiarDet();
        return;
      };
      $(txtThis).off("blur");

      const parametros = new FormData();
      parametros.append("action", "consultarArtic");
      parametros.append("txtCodd", txtCodd.value);

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (jsonJS.artic === null) {
              txtCodd.focus();
              limpiarDet();
              alErrorFocusTimer({"msg":{"type":"error","title":"No Existe","text":"Este Artículo no existe, debe registrarlo", "ok":"Aceptar", "timer":timeOutErrorSm}}, txtThis);
            } else {
              if (jsonJS.artic.art_bloqueado=='1') {
                txtCodd.focus();
                limpiarDet();
                alWarningFocusTimer({"msg":{"type":"warning","title":"Bloqueado","text":"No puede usar este Artículo porque está bloqueado", "ok":"Aceptar", "timer":timeOutErrorSm}}, txtThis);
              } else {
                medid = jsonJS.artic.art_medi;
                bienser = jsonJS.artic.art_bienser;

                txtCodd.value = jsonJS.artic.art_cod;
                txtDescd.value = jsonJS.artic.art_desc;
                txtUnimed.value = jsonJS.artic.um_nom;
                numPreud.value = jsonJS.artic.art_pre1;
                cbExentod.checked = (jsonJS.artic.art_exen == 'N') ? 0 : 1;
                imgExist(imgArtic, jsonJS.imgArtic, imgPhoto);
              }
            }
            pressEnter = false;
            blurOn(txtThis, txtGetValue);
          }
        }
      });
    });

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

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

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

    // VALID VALOR DESCUENTO
    $("#numDescuvd, #numDescuvdm")
    .change(function (){
      calcularTotValor($(this).attr('id'));
    });

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

      const idThis = $(this).attr('id');
      const cod = (idThis.substr(-1)=='m') ? txtCoddm.value : txtCodd.value;
      const bienOServicio = (idThis.substr(-1)=='m') ? bienserm : bienser;

      if (bienOServicio=='S') {
        return;
      }

      const parametros = new FormData();
      parametros.append("action", "consultarExist");
      parametros.append("txtCod", cod);
      parametros.append("selBod", selBodSal.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.error == true){
            alError(jsonJS);
          } else {
/*            if (jsonJS.exiart === null) {
              txtThis.value="";
              alWarningFocusTimer({"msg":{"title":"No tiene Existencia","text":"Este Artículo no tiene existencia registrada","timer":timeOutWarningSm}}, txtThis);
            } else {
              var existAct = Number(jsonJS.exiart.ea_exist)+sumCantDetAnt(cod);
              var cantSale = Number(txtThis.value)-cantAnt+sumCant(cod);
              if (cantSale > existAct) {
                txtThis.value="";
                alWarningFocusTimer({"msg":{"title":"No tiene Suficiente Existencia","text":"La existencia en esta bodega no alcanza para hacer esta salida, solo tiene:   "+existAct.toFixed(2),"timer":timeOutWarningSm}}, txtThis);
              }
            }   */
            calcularTotPorcentaje(idThis);
          }
        }
      });
    });

    // FOCUS INPUT
    $("form[name='thisform'] input, select, textarea, #btnPartida").focus(function (){
      if (!($("input:visible:first").is(":focus")) && !($("#selTipo").is(":focus"))) {
        if (restriccionCamposVacios()) {return};
      }
    });
    

    $("#dtFec")
    .focus(function (){
      $("#btnGuardar").off("focus");
      $("#btnGuardarImprimir").off("focus");
      $("#btnAnular").off("focus");
      $("#btnBorrar").off("focus");
      limpiar();
    });


    // 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-1-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      txtGetValue = document.getElementById("txtCliNom");
      txtNext = document.getElementById("txtNomFac");

      $(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;
                selVend.value = jsonJS.cliencc.cli_ven;
                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();

      if ($(this).find('option:selected').data('soloinv') != "S") {
        $('#noEsEnvio').show(500);
      } else {
        $('#noEsEnvio').hide(500);
      }
    });

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

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

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

  });

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

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

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

  // 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 );
          txtCodd.focus();
        }
      }
    //}
  });
</script>

