<?php 
include_once('../../../php/sessionStart.php'); 
include_once('../../../php/db/dbExec.php');
$dtFec=date("Y-m-d");
$nAnio=date("Y");
$nMes=date("m");

$empCod = $_SESSION['empCod'];
$empNom = $_SESSION['empNom'];
$empNit = $_SESSION['empNit'];
$pCaja = $_SESSION['pCaja'];
$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,
            TRIM(tv.tv_codasiste) AS tv_codasiste,
            tv_librosn,
            tv_impues,
            TRIM(td.td_cod) AS td_cod
           FROM tipov tv LEFT JOIN tipodoci td ON tv.tv_cod=td.td_relatv WHERE tv_pone='P'";
$sVendedor = "SELECT * FROM vendedor where vend_usu='$usuCod'";
$sBodegas = "SELECT * FROM bodegas where bod_emp='$empCod'";
$sPordesc = "SELECT * FROM pordesc ORDER BY pd_cod";
# EJECUCION DE QUERYS
$db = new dbExec();
$select["tipov"] = $db->query($sTipov);
$select["vendedor"] = $db->query($sVendedor);
$select["bodegas"] = $db->query($sBodegas);
$select["pordesc"] = $db->query($sPordesc);
$select["pordesc2"] = $db->query($sPordesc);
$db->close();

$anoTrab=date("Y", strtotime($_SESSION['empFtrab']));
$mesTrab=date("m", strtotime($_SESSION['empFtrab']));
?>
<?php include_once('../includes/htmlOpenPov.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-2">
                          <label class="font-size-md text-success" for="txtCoddm">Código</label>
                          <input type="text" class="form-control form-control-md form-control-as limpiarModalDet" id="txtCoddm" maxlength="20" disabled>
                        </div>
                        <div class="col-6">
                          <label class="font-size-md text-success" for="txtDescdm">Descripción</label>
                          <input type="text" class="form-control form-control-md form-control-as limpiarModalDet" id="txtDescdm" maxlength="120" disabled>
                        </div>
                        <div class="col-1">
                          <label class="font-size-md text-success" for="txtUnimedm">Medida</label>
                          <input type="text" class="form-control form-control-md form-control-as limpiarModalDet" id="txtUnimedm" maxlength="20" disabled>
                        </div>
                      </div>
                      <div class="form-row align-items-end">
                        <div class="col-4">
                          <label class="font-size-md text-success" for="numCantdm">Cantidad</label>
                          <input type="number" class="form-control form-control-md form-control-as dec-2 limpiarModalDet" id="numCantdm" placeholder="0.00">
                        </div>
                        <div class="col-4">
                          <label class="font-size-md text-success" for="numPreudm">Precio Unit.</label>
                          <input type="number" class="form-control form-control-md form-control-as dec-5 limpiarModalDet" id="numPreudm" placeholder="0.00">
                        </div>
                        <div class="col-4">
                          <label class="font-size-md text-success" for="numSubdm">Sub-Total</label>
                          <input type="number" class="form-control form-control-md form-control-as dec-5 limpiarModalDet" id="numSubdm" placeholder="0.00" disabled>
                        </div>
                      </div>
                      <div class="form-row align-items-end">
                        <div class="col-3">
                          <label class="font-size-md" for="numDescudm">Descuento %</label>
                          <select class="form-control form-control-md form-control-as" name="numDescudm" id="numDescudm">
                            <?php
                              while ($recm = $db->fetchAssoc($select['pordesc2'])) {
                                echo  "<option value={$recm['pd_cod']}>".utf8_encode($recm['pd_nom']).'</option>';
                              }
                            ?>
                          </select>
                        </div>
<!---
                        <div class="col-3">
                          <label class="font-size-md text-success" for="numDescudm">Descuento %</label>
                          <input type="number" class="form-control form-control-md form-control-as dec-0 limpiarModalDet" id="numDescudm" placeholder="0">
                        </div>
--->                            
                        <div class="col-3">
                          <label class="font-size-md text-success" for="numDescuvdm">Valor Descuento</label>
                          <input type="number" class="form-control form-control-md form-control-as dec-2 limpiarModalDet" id="numDescuvdm" placeholder="0.00" disabled>
                        </div>
                        <div class="col-3">
                          <label class="font-size-md text-success" for="numTotdm">Total</label>
                          <input type="number" class="form-control form-control-md form-control-as dec-5 limpiarModalDet" id="numTotdm" placeholder="0.00" disabled>
                        </div>
                        <div class="col-3 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" style='font-size:20px;' 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 FORMA DE PAGO -->
      <div class="modal fade" id="modalFpag" tabindex="-1" role="dialog" aria-labelledby="modalFpagTitle" 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-11-tab" data-toggle="pill" href="#pills-11" role="tab" aria-controls="pills-11" aria-selected="true">DESGLOCE DE PAGO</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-11" role="tabpanel" aria-labelledby="pills-11-tab">
                  
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">

                    <div class="form-group">
                      <div class="form-row align-items-end">
                        <div class="col-4">
                          <div class="form-row">
                            <div class="col-6 col-sm-12 text-center mt-3">
                              <div class="upload-btn-wrapper text-center" style="width: 100%; height: 220px;">
                                <img class="rounded-lg" name="imgCajareg" width="90%" height="90%" style="object-fit: cover;" />
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="col-1">
                          <label></label>
                        </div>
                        <div class="col-7">
                          <label class="font-size-xl text-success" style="font-size:50px; font-weight:bold;" for="numTotfp">TOTAL A PAGAR Q.</label>
                          <input type="number" class="form-control text-dark form-control-xl form-control-as limpiarModalfp text-dark text-center dec-2" style="font-size:60px; font-weight:bold;" id="numTotfp" placeholder="0.00" disabled>
                        </div>
                      </div>
                      <div class="form-row align-items-end">
                        <div class="col-3">
                          <label class="font-size-xl text-success" style="font-size:20px; font-weight:bold;" for="numEfectotfp">Efectivo Q.</label>
                          <input type="number" class="form-control form-control-xl form-control-as limpiarModalfp text-dark dec-2" style="font-size:20px;" id="numEfectotfp" placeholder="0.00">
                        </div>
                        <div class="col-3">
                          <label class="font-size-xl text-success" style="font-size:20px; font-weight:bold;" for="numExenvalfp">Exencion</label>
                          <input type="number" class="form-control form-control-xl form-control-as limpiarModalfp text-dark dec-2" style="font-size:20px;" id="numExenvalfp" placeholder="0.00">
                        </div>
                        <div class="col-3">
                          <label class="font-size-xl text-success" style="font-size:20px; font-weight:bold;" for="txtChnumfp">Numero Cheque</label>
                          <input type="text" class="form-control form-control-xl form-control-as limpiarModalfp text-dark" style="font-size:20px;" id="txtChnumfp">
                        </div>
                        <div class="col-3">
                          <label class="font-size-xl text-success" style="font-size:20px; font-weight:bold;" for="numChvalfp">Valor Cheque</label>
                          <input type="number" class="form-control form-control-xl form-control-as limpiarModalfp text-dark dec-2" style="font-size:20px;" id="numChvalfp" placeholder="0.00">
                        </div>
                      </div>
                      <div class="form-row align-items-end">
                        <div class="col-3">
                          <label class="font-size-xl text-success" style="font-size:20px; font-weight:bold;" for="numTarjfp">Pago Tarjeta</label>
                          <input type="number" class="form-control form-control-xl form-control-as limpiarModalfp text-dark dec-2" style="font-size:20px;" id="numTarjfp"  placeholder="0.00">
                        </div>
                        <div class="col-2">
                          <label class="font-size-xl text-success" style="font-size:20px; font-weight:bold;" for="numValefp">Valor Vale</label>
                          <input type="number" class="form-control form-control-xl form-control-as limpiarModalfp text-dark dec-2" style="font-size:20px;" id="numValefp" placeholder="0.00">
                        </div>
                        <div class="col-3">
                          <label class="font-size-xl text-success" style="font-size:20px; font-weight:bold;" for="numCredfp">Credito</label>
                          <input type="number" class="form-control form-control-xl form-control-as limpiarModalfp text-dark dec-2" style="font-size:20px;" id="numCredfp" placeholder="0.00">
                        </div>
                        <div class="col-2">
                          <label class="font-size-xl text-success" style="font-size:20px; font-weight:bold;" for="numDolaresfp">Dolares</label>
                          <input type="number" class="form-control form-control-xl form-control-as limpiarModalfp text-dark dec-2" style="font-size:20px;" id="numDolaresfp" placeholder="0.00">
                        </div>
                        <div class="col-2">
                          <label class="font-size-xl text-success" style="font-size:20px; font-weight:bold;" for="numTcdolarfp">Tasa Cambio</label>
                          <input type="number" class="form-control form-control-xl form-control-as limpiarModalfp text-dark dec-5" style="font-size:20px;" id="numTcdolarfp" placeholder="0.00000">
                        </div>
                      </div>
                      <div class="form-row align-items-end">
                        <div class="col-6">
                          <label></label>
                        </div>
                        <div class="col-6">
                          <label class="font-size-xl text-danger text-center" style="font-size:60px; font-weight:bold;" for="numVueltofp">VUELTO Q.</label>
                          <input type="number" class="form-control form-control-xl form-control-as limpiarModalfp text-dark text-center dec-2" style="font-size:60px; font-weight:bold;" id="numVueltofp" placeholder="0.00" disabled>
                        </div>
                      </div>
                    </div>
                    <div class="form-row">
                      <div class="col-6">
                        <button type="button" class="btn btn-danger btn-block" style="font-size:30px;" id="btnRegresa">Regresar</button>
                      </div>
                      <div class="col-6">
                        <button type="button" class="btn btn-success btn-block" style="font-size:30px;" id="btnContinua">Continuar</button>
                      </div>
                    </div>
                  </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>
                    <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>
      <!-- MODAL DESCUENTO -->
      <div class="modal fade" id="modalDescu" tabindex="-1" role="dialog" aria-labelledby="modalDescuTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-md" 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">AUTORIZACION DESCUENTO</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-3">
                          <label></label>
                        </div>
                        <div class="col-6">
                          <label class="font-size-xl text-dark" style="font-size:25px;" for="txtPassdescu">Autorizacion o Clave</label>
                          <input type="password" class="form-control form-control-xl form-control-as text-dark" style="font-size:20px;" id="txtPassdescu" placeholder="Autorizacion">
                        </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="btnSeguir">Continuar</button>
                      </div>
                    </div>
                  </form>

                </div>
              </div>

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

      <!-- MODAL CAMBIO DE PRECIOS -->
      <div class="modal fade" id="modalPrecios" tabindex="-1" role="dialog" aria-labelledby="modalPreciosTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-md" 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-13-tab" data-toggle="pill" href="#pills-13" role="tab" aria-controls="pills-13" aria-selected="true">AUTORIZACION CAMBIO DE PRECIO</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-13" role="tabpanel" aria-labelledby="pills-13-tab">
                  
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">

                    <div class="form-group">
                      <div class="form-row align-items-end">
                        <div class="col-3">
                          <label></label>
                        </div>
                        <div class="col-6">
                          <label class="font-size-xl text-dark" style="font-size:25px;" for="txtPassdescupre">Autorizacion o Clave</label>
                          <input type="password" class="form-control form-control-xl form-control-as text-dark" style="font-size:20px;" id="txtPassdescupre" placeholder="Autorizacion">
                        </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="btnSeguirpre">Continuar</button>
                      </div>
                    </div>
                  </form>

                </div>
              </div>

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

      <!-- MODAL LISTA DE EXISTENCIAS SEGUN FECHA DE VENCIMIENTO -->
      <div class="modal fade" id="modalLisExist" tabindex="-1" role="dialog" aria-labelledby="modalLisExistTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-lg" role="document">
          <div class="modal-content bg-dark">
            <div class="modal-header">
              <ul class="nav nav-pills" id="pills-tab" role="tablist">
                <li class="nav-item">
                  <a class="nav-link active" id="pills-007-tab" data-toggle="pill" href="#pills-007" role="tab" aria-controls="pills-007" aria-selected="true">Lista de Existencia Disponible en esta bodega</a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-white" aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">

              <div class="tab-content bg-transparent border-0" id="pills-tabContent">
                <div class="tab-pane fade show active" id="pills-007" role="tabpanel" aria-labelledby="pills-007-tab">
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">
                      <div class="form-row">
                        <div class="col-md-4">
                          <label class="font-size-md" for="txtDcodlis">Codigo</label>
                          <input type="text" class="form-control form-control-md form-control-as" id="txtDcodlis" disabled>
                        </div>
                        <div class="col-md-8">
                          <label class="font-size-md" for="txtDdesclis">Descripcion</label>
                          <input type="text" class="form-control form-control-md form-control-as" id="txtDdesclis" disabled>
                        </div>
                      </div>
                      <div class="form-row">
                          <label> </label>
                      </div>
                      <div class="form-row">
                        <div class="col-md-12">
                          <div class="table-responsive">
                            <table class="table table-hover table-bordered table-dark table-md" id="tblExistList">
                              <thead>
                                <tr>
                                  <th scope="col" class="text-center" style="font-size:16px;" width="70">LOTE</th>
                                  <th scope="col" class="text-center" style="font-size:16px;" width="70">FEC/VENCIMIENTO</th>
                                  <th scope="col" class="text-center" style="font-size:16px;" width="100">EXISTENCIA</th>
                                  <th scope="col" class="text-center" style="font-size:16px;" width="100">SELECCIONAR</th>
                                </tr>
                              </thead>
                              <tbody>
                              </tbody>
                              <tfoot>
                                <th scope="col"></th>
                                <th scope="col" class="text-right" style='font-size:25px;'>Total</th>
                                <th scope="col" id="dataTotExistLis" class="text-right" style='font-size:25px;'>0</th>
                                <th scope="col"></th>
                              </tfoot>
                            </table>
                          </div>
                        </div>
                      </div>
                    </div>
                    <button type="button" class="btn btn-success btn-block" id="btnContiLisExist">Regresar</button>
                  </form>
                </div>
              </div>
           </div>
          </div>
        </div>
      </div>

      <!-- MODAL LISTA DE PEDIDOS DEL DIA -->
      <div class="modal fade" id="modalLisPed" tabindex="-1" role="dialog" aria-labelledby="modalLisPedTitle" 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-008-tab" data-toggle="pill" href="#pills-008" role="tab" aria-controls="pills-008" aria-selected="true">Lista de Pedidos del Dia</a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-white" aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">

              <div class="tab-content bg-transparent border-0" id="pills-tabContent">
                <div class="tab-pane fade show active" id="pills-007" role="tabpanel" aria-labelledby="pills-007-tab">
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">
                      <div class="form-row">
                          <label> </label>
                      </div>
                      <div class="form-row">
                        <div class="col-md-12">
                          <div class="table-responsive">
                            <table class="table table-hover table-bordered table-primary table-striped table-xl" id="tblLisPed">
                              <thead>
                                <tr>
                                  <th scope="col" class="text-center" style="font-size:13px;" width="180">NOMBRE</th>
                                  <th scope="col" class="text-center" style="font-size:13px;" width="200">DIRECCION</th>
                                  <th scope="col" class="text-center" style="font-size:13px;" width="5">ZONA</th>
                                  <th scope="col" class="text-center" style="font-size:13px;" width="10">CELULAR</th>
                                  <th scope="col" class="text-center" style="font-size:13px;" width="5">HORA</th>
                                </tr>
                              </thead>
                              <tbody>
                              </tbody>
                              <tfoot>
                              </tfoot>
                            </table>
                          </div>
                        </div>
                      </div>
                    </div>
                    <button type="button" class="btn btn-success btn-block" id="btnContiLisPed">Regresar</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 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 Facturar</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" id="pills-4-tab" data-toggle="pill" href="#pills-4" role="tab" aria-controls="pills-4" aria-selected="true">Buscar Clientes Pedidos</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-2">
                            <label class="font-size-md text-success" for="txtCodd">Código</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiarDet" id="txtCodd" maxlength="20">
                          </div>
                          <div class="col-5">
                            <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" disabled>
                          </div>
                          <div class="col-1">
                            <label class="font-size-md text-success" for="txtUnimed">Medida</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiarDet" id="txtUnimed" maxlength="20" disabled>
                          </div>
                        </div>
                        <div class="form-row align-items-end">
                          <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-0 limpiarDet" id="numCantd" placeholder="0">
                          </div>
                          <div class="col-1.5">
                            <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-2 limpiarDet text-primary" id="numPreud" placeholder="0.00">
                          </div>
                          <div class="col-1.5">
                            <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-1">
                            <label class="font-size-md text-success" for="numDescud">Descuento %</label>
                            <select class="form-control form-control-md form-control-as" name="numDescud" id="numDescud">
                              <?php
                                while ($rec = $db->fetchAssoc($select['pordesc'])) {
                                  echo  '<option value="'.TRIM($rec['pd_cod']).'">'.utf8_encode($rec['pd_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
<!---                          
                          <div class="col-1.5">
                            <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-1.5">
                            <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-1.5">
                            <label class="font-size-md text-success" for="numTotd">Total</label>
                            <input type="number" class="form-control form-control-md form-control-as dec-2 limpiarDet" id="numTotd" 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 form-control-md" name="cbExentod" id="cbExentod">
                              <label class="custom-control-label text-success" style='font-size:20px;' for="cbExentod">Exento</label>
                            </div>
                          </div>
                        </div>
                      </div>

                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-4">
                            <button type="button" class="btn btn-success" style='font-size:25px;' id="btnAddDet">
                              <i class="fas fa-plus-circle"></i>  Agregar a Lista
                            </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" style="font-size:16px;" width="90">CODIGO</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" width="200">DESCRIPCIÓN</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" width="70">MEDIDA</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" width="70">CANTIDAD</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" width="70">PRECIO UNIT.</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" width="90">SUB-TOTAL</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" width="50">DESCU. %</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" 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" style="font-size:16px;" 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"></th>
                                  <th scope="col" class="text-right" style="font-size:26px;">Totales</th>
                                  <th scope="col" id="dataTotSub" class="text-right" style="font-size:18px;">0.00</th>
                                  <th scope="col"></th>
                                  <th scope="col" id="dataTotDescuv" class="text-right" style="font-size:18px;">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="" disabled>
                          </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" disabled>
                          </div>
                          <div class="col-md-4">
                            <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" disabled>
                          </div>
                          <div class="col-3">
                            <label class="pr-1 font-size-md">Entregar a Domicilio</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crDomi1" name="crDomi" class="custom-control-input font-size-md" value="S">
                              <label class="custom-control-label font-size-md" for="crDomi1">Si</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crDomi2" name="crDomi" class="custom-control-input font-size-md" value="N">
                              <label class="custom-control-label font-size-md" for="crDomi2">No</label>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="form-group">
                        <h4 class="text-primary">DATOS PARA PEDIDO</h4>
                        <div class="form-row align-items-end">
                          <div class="col-1">
                            <label class="font-size-md text-primary"  for="numIdPed">Codigo</label>
                            <input type="number" class="form-control form-control-md form-control-as limpiar" id="numIdPed">
                          </div>
                          <div class="col-2">
                            <label class="font-size-md text-primary"  for="txtCelPed">Celular</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtCelPed">
                          </div>
                          <div class="col-md-9">
                            <label class="font-size-md text-primary" for="txtNomPed">A nombre de</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtNomPed">
                          </div>
                        </div>
                        <div class="form-row align-items-end">
                          <div class="col-8">
                            <label class="font-size-md text-primary" for="txtDirPed">Dirección</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtDirPed">
                          </div>
                          <div class="col-1">
                            <label class="font-size-md text-primary" class="font-size-md" for="numZonaPed">Zona</label>
                            <input type="number" class="form-control form-control-md form-control-as limpiar" id="numZonaPed">
                          </div>
                          <div class="col-2">
                            <label class="font-size-md text-primary" class="font-size-md" for="txtTelPed">Teléfono</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtTelPed">
                          </div>
                        </div>
                        <div class="form-row align-items-end">
                          <div class="col-10">
                            <label class="font-size-md text-primary" for="txtEmail">Correo electronico</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtEmail">
                          </div>
                        </div>
                        <div class="form-row align-items-end">
                          <div class="col-10">
                            <label class="font-size-md text-primary" for="txtObsPed">Observaciones</label>
                            <textarea class="form-control form-control-sm form-control-as" id="txtObsPed" rows="2"></textarea>
                          </div>
                        </div>
                      </div>
                      <div class="form-group">
                        <h4 class="text-success">DATOS PARA FACTURAR</h4>
                        <div class="form-row align-items-end">
                          <div class="col-md-3">
                            <label class="font-size-md text-success" for="txtNit">NIT</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtNit">
                          </div>
                          <div class="col-md-9">
                            <label class="font-size-md text-success" for="txtNomFac">A nombre de</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtNomFac">
                          </div>
                        </div>
                        <div class="form-row align-items-end">
                          <div class="col-8">
                            <label class="font-size-md text-success" 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-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" disabled>
                          </div>
                          <div class="col-8 col-md-2">
                            <label for="numTcam">Tipo de Cambio</span></label>
                            <input type="number" class="form-control form-control-sm form-control-as dec-5" id="numTcam" placeholder="0.00000" disabled>
                          </div>
--->                          
                          <div class="col-3">
                            <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 class="col-3">
                            <label class="font-size-md" for="selTipo">Serie</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-relatd="'.$rec['td_cod'].'" data-impues="'.$rec['tv_impues'].'" data-abrev="'.$rec['tv_abrev'].'" data-codasiste="'.$rec['tv_codasiste'].'">'.utf8_encode($rec['tv_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-6">
                            <label class="font-size-md" for="selBodSal">Bodega Sale</label>
                            <select class="form-control form-control-md form-control-as" name="selBodSal" id="selBodSal" disabled>
                              <?php
                                while ($rec = $db->fetchAssoc($select['bodegas'])) {
                                  echo  '<option value="'.$rec['bod_cod'].'" data-ctainv="'.$rec['bod_ctainv'].'" data-ctaven="'.$rec['bod_ctaven'].'">'.utf8_encode($rec['bod_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" disabled>
                              <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" disabled>
                              <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>

                    </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:45px; font-weight:bold;">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:43px; font-weight:bold;" id="numTot" placeholder="0.00" min="0" disabled>
                          </div>
                        </div>

                        <div class="form-row">
<!---                          
                          <div class="col-12 mt-2">
                            <button class="btn btn-warning btn-block" style="font-size:21px; font-weight:bold;" id="btnGuardarImprimir" type="button" disabled>Imprimir Ticket (FEL)</button>
                          </div>
--->                          
                          <div class="col-12 mt-2">
                            <button class="btn btn-success btn-block" style="font-size:21px; font-weight:bold;" id="btnGuardar" type="button">Generar PDF (FEL)</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-info btn-block" style="font-size:21px; font-weight:bold;" id="btnCorreo" type="button">Enviar por Correo (FEL)</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-primary btn-block" style="font-size:21px; font-weight:bold;" id="btnEnvio" type="button">Generar Envio PDF</button>
                          </div>
<!--                          
                          <div class="col-12 mt-2">
                            <button class="btn btn-primary btn-block" style="font-size:21px; font-weight:bold;" id="btnEnvioT" type="button" disabled>Generar Envio Ticket</button>
                          </div>
--->                          
                          <div class="col-12 mt-2">
                            <button class="btn btn-danger btn-block" style="font-size:21px; font-weight:bold;" id="btnAnulaTran" type="button">Cancelar Transaccion</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-warning btn-block" style="font-size:21px; font-weight:bold;" id="btnLisPed" type="button">Lista de Pedidos</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: 80%; height: 200px;">
                                  <img class="rounded-lg" name="imgArtic" width="80%" height="80%" style="object-fit: cover;" />
                                </div>
                              </div>
                            </div>
                          </div>
                          <div class="col-12">
                            <div class="form-row">
<!---                              
                              <div class="col-12">
                                <div class="col-8 col-sm-12 text-center mt-3">
                                  <div class="upload-btn-wrapper text-center" style="width: 80%; height: 90px;">
                                    <img class="rounded-lg" name="imgEmpre" width="95%" height="155%" style="object-fit: cover;" />
                                  </div>
                                </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 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 class="tab-pane fade" id="pills-4" role="tabpanel" aria-labelledby="pills-4-tab">
                <?php
                  $a='0';
                  $b='4';
                  include('../busClienPedId/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 inputClienccCod = "txtCliCod";
  var inputClien = "txtNit";
  var inputCel = "txtCelPed";
  var inputIdPed = "numIdPed";
  var inputArtic = "txtCodd";
  var IdPed = 0;

  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 ctacos = "";
  var ctainv = "";
  var ctaven = "";
  var loted = "";
  var cosud = 0;

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

  var empre = '<?php echo $empCod; ?>';

  imgArtic.src = imgPhoto;
  imgCajareg.src = imgPhoto1;
  //imgEmpre.src = imgPhoto2;
  
  const colDet = ["acciones", "codd", "descd", "medid", "unimed", "cantd", "preud", "subd", "descud", "descuvd", "totd", "exensnd", "bienserd", "ctacos", "ctainv", "ctaven", "cosud"];

  // 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 txtCelPed = document.thisform.txtCelPed;
  const txtNomPed = document.thisform.txtNomPed;
  const txtDirPed = document.thisform.txtDirPed;
  const txtTelPed = document.thisform.txtTelPed;
  const numZonaPed = document.thisform.numZonaPed;
  const txtEmail = document.thisform.txtEmail;

  const crDomi = document.thisform.crDomi;

/*  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;
      }
      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 (!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') {
    }
    return false;
  }

  function addRowDetao(codd, descd, medid, unimed, cantd, preud, subd, descud, descuvd, totd, exentod, bienserd, ctacos, ctainv, ctaven, cosud){
    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' style='font-size:16px;'>"+codd+"</td>"
                +"<td id='dataDescd' style='font-size:16px;'>"+descd+"</td>"
                +"<td id='dataMedid' class='d-none' style='font-size:16px;'>"+medid+"</td>"
                +"<td id='dataUnimed' style='font-size:16px;'>"+unimed+"</td>"
                +"<td id='dataCantd' class='text-right' style='font-size:16px;'>"+cantd+"</td>"
                +"<td id='dataPreud' class='text-right' style='font-size:16px;'>"+preud+"</td>"
                +"<td id='dataSubd' class='text-right' style='font-size:16px;'>"+subd+"</td>"
                +"<td id='dataDescud' class='text-right' style='font-size:16px;'>"+descud+"</td>"
                +"<td id='dataDescuvd' class='text-right' style='font-size:16px;'>"+descuvd+"</td>"
                +"<td id='dataTotd' class='text-right' style='font-size:16px;'>"+totd+"</td>"
                +"<td id='dataExentod' class='text-center' style='font-size:16px;'>"+exentod+"</td>"
                +"<td id='dataBienserd' class='d-none'>"+bienserd+"</td>"
                +"<td id='dataCtacos' class='d-none'>"+ctacos+"</td>"
                +"<td id='dataCtainv' class='d-none'>"+ctainv+"</td>"
                +"<td id='dataCtaven' class='d-none'>"+ctaven+"</td>"
                +"<td id='dataCosud' class='d-none'>"+cosud+"</td>"
                +"</tr>";
    $("#tblDet tbody").append(row);
  }

  function addRowLisPed(nom,dir,zona,cel,hora){
    const row = "<tr>"
                  +"<td id='datanom' class='text-left' style='font-size:15px; font-weight:bold;'>"+nom+"</td>"
                  +"<td id='datadir' class='text-left' style='font-size:15px; font-weight:bold;'>"+dir+"</td>"
                  +"<td id='datazona' class='text-center' style='font-size:15px; font-weight:bold;'>"+zona+"</td>"
                  +"<td id='datacel' class='text-center' style='font-size:15px; font-weight:bold;'>"+cel+"</td>"
                  +"<td id='datahora' class='text-center' style='font-size:15px; font-weight:bold;'>"+hora+"</td>"
                +"</tr>";
    $("#tblLisPed tbody").append(row);
  }

  sumCajaLis();

  function sumCajaLis() {
    var acum = 0;
    var acuma = 0;

    $("#tblExistList").find('tbody tr').each(function () {
      acum += parseFloat($(this).find('#dataexistlis').text());
    });
    $("#tblExistList #dataTotExistLis").text(acum.toFixed(0));
  }

  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() {
    ctaCli = "";
    crDomi.value="N";
    $(".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(){
    $("#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 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 = true){
    if (restriccionTcam()) {return};
    if (restriccion()) {return};

    var txtMailc = txtEmail.value;
    var cel = txtCelPed.value;

    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("selBodSalCod", selBodSal.value);
    parametros.append("numTcam", 1);
    parametros.append("numIdPed", numIdPed.value);
    parametros.append("txtCliCod", txtCliCod.value);
    parametros.append("txtNomFac", txtNomFac.value);
    parametros.append("txtNit", txtNit.value);
    parametros.append("txtDir", txtDir.value);
    parametros.append("txtNomPed", txtNomPed.value);
    parametros.append("txtDirPed", txtDirPed.value);
    parametros.append("txtTelPed", txtTelPed.value);
    parametros.append("txtCelPed", txtCelPed.value);
    parametros.append("numZonaPed", numZonaPed.value);
    parametros.append("txtEmail", txtEmail.value);
    parametros.append("txtObsPed", txtObsPed.value);
    parametros.append("numDcre", 0);
    parametros.append("selVendCod", selVend.value);
    parametros.append("crFpag", 1);
    parametros.append("crExp", "N");
    parametros.append("crRet", "N");
    parametros.append("crReti", "N");
    parametros.append("crDomi", crDomi.value);
    parametros.append("numTotfp", numTotfp.value);
    parametros.append("numEfectotfp", numEfectotfp.value);
    parametros.append("numExenvalfp", numExenvalfp.value);
    parametros.append("txtChnumfp", txtChnumfp.value);
    parametros.append("numChvalfp", numChvalfp.value);
    parametros.append("numTarjfp", numTarjfp.value);
    parametros.append("numValefp", numValefp.value);
    parametros.append("numCredfp", numCredfp.value);
    parametros.append("numDolaresfp", numDolaresfp.value);
    parametros.append("numTcdolarfp", numTcdolarfp.value);
    parametros.append("valq", valq);
    parametros.append("txtMail", txtMail.value);
    parametros.append("numVueltofp", numVueltofp.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("selCodasiste", $('#selTipo').find('option:selected').data('codasiste'));
    parametros.append("ctainv", $('#selBodSal').find('option:selected').data('ctainv'));
    parametros.append("ctaven", $('#selBodSal').find('option:selected').data('ctaven'));
    parametros.append("tot", numTot.value);
    parametros.append("tblDet", tblToJson(colDet, "tblDet", 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("txtTelPed"));
//    $("."+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 {
          if (!isNullPer(jsonJS.mserror)) {
            //txtCodd.focus();
            alWarning({"msg":{"title":"Problema al Tratar de Grabar","text":"Alerta: Posiblemente El NIT que esta ingresando no es valido"}});
            return true;
          }
          var seriedoc = jsonJS.seriedoc1;
          var numdoc = jsonJS.numdoc1;
          var nit = jsonJS.nit;
          var idinterno = jsonJS.idinterno;
          limpiar();
          tblClear("tblDet");
          sumDet();
          txtCliCod.value = "88888888";
          txtCliNom.value = "Clientes Varios";
          txtNit.value = "CF";
          txtNomFac.value = "CONSUMIDOR FINAL";
          txtDir.value = "CIUDAD";
          txtNomPed.value = "";
          txtDirPed.value = "";
          txtCelPed.value = "";
          numZonaPed.value = 0;
          txtTelPed.value = "";
          txtEmail.value = "";
          $("#btnContinua").focus(function (){
            txtCodd.focus();
          });
          //alSuccess(jsonJS);
          if (opGrabar=='B') {
              imprimirDoc(seriedoc,numdoc,totLetras,numVueltofp.value,txtMailc,idinterno);
          }
          if (opGrabar=='A') {
              imprimirPdf(seriedoc,numdoc,totLetras,numVueltofp.value,txtMailc,idinterno);
          }
          if (opGrabar=='C') {
              enviarCorreo(seriedoc,numdoc,totLetras,numVueltofp.value,txtMail.value,nit,cel,idinterno);
          }
          txtCodd.focus();
          alSuccess(jsonJS);
        }
      }
    });  
  }

  function guardarEnvio(imprimir = true){
    if (restriccionTcam()) {return};
    if (restriccion()) {return};

    var txtMailc = txtEmail.value;
    var cel = txtCelPed.value;

    const parametros = new FormData();
    parametros.append("action", "guardarEnvio");
    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("selBodSalCod", selBodSal.value);
    parametros.append("numTcam", 1);
    parametros.append("numIdPed", numIdPed.value);
    parametros.append("txtCliCod", txtCliCod.value);
    parametros.append("txtNomFac", txtNomFac.value);
    parametros.append("txtNit", txtNit.value);
    parametros.append("txtDir", txtDir.value);
    parametros.append("txtNomPed", txtNomPed.value);
    parametros.append("txtDirPed", txtDirPed.value);
    parametros.append("txtTelPed", txtTelPed.value);
    parametros.append("txtCelPed", txtCelPed.value);
    parametros.append("numZonaPed", numZonaPed.value);
    parametros.append("txtEmail", txtEmail.value);
    parametros.append("txtObsPed", txtObsPed.value);
    parametros.append("numDcre", 0);
    parametros.append("selVendCod", selVend.value);
    parametros.append("crFpag", 1);
    parametros.append("crExp", "N");
    parametros.append("crRet", "N");
    parametros.append("crReti", "N");
    parametros.append("crDomi", crDomi.value);
    parametros.append("numTotfp", numTotfp.value);
    parametros.append("numEfectotfp", numEfectotfp.value);
    parametros.append("numExenvalfp", numExenvalfp.value);
    parametros.append("txtChnumfp", txtChnumfp.value);
    parametros.append("numChvalfp", numChvalfp.value);
    parametros.append("numTarjfp", numTarjfp.value);
    parametros.append("numValefp", numValefp.value);
    parametros.append("numCredfp", numCredfp.value);
    parametros.append("numDolaresfp", numDolaresfp.value);
    parametros.append("numTcdolarfp", numTcdolarfp.value);
    parametros.append("valq", valq);
    parametros.append("txtMail", txtMail.value);
    parametros.append("numVueltofp", numVueltofp.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("selCodasiste", $('#selTipo').find('option:selected').data('codasiste'));
    parametros.append("ctainv", $('#selBodSal').find('option:selected').data('ctainv'));
    parametros.append("ctaven", $('#selBodSal').find('option:selected').data('ctaven'));
    parametros.append("tot", numTot.value);
    parametros.append("tblDet", tblToJson(colDet, "tblDet", 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("txtTelPed"));
//    $("."+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();
          txtCliCod.value = "88888888";
          txtCliNom.value = "Clientes Varios";
          txtNit.value = "CF";
          txtNomFac.value = "CONSUMIDOR FINAL";
          txtDir.value = "CIUDAD";
          txtNomPed.value = "";
          txtDirPed.value = "";
          txtCelPed.value = "";
          numZonaPed.value = 0;
          txtTelPed.value = "";
          txtEmail.value="";
          $("#btnContinua").focus(function (){
            txtCodd.focus();
          });
          //alSuccess(jsonJS);
          if (opGrabar=='E') {
              imprimirEnvio(seriedoc,numdoc,totLetras,numVueltofp.value,txtMailc,idinterno);
          }
          if (opGrabar=='F') {
              imprimirEnvioT(seriedoc,numdoc,totLetras,numVueltofp.value,txtMailc,idinterno);
          }
          txtCodd.focus();
          alSuccess(jsonJS);
        }
      }
    });  
  }

  function imprimirDoc(seriedoc,numdoc,totLetras,vuelto,mail,idinterno){
      const parametros = new FormData();
      parametros.append("action", "email");
      parametros.append("selTipoCod", seriedoc);
      parametros.append("numdoc", numdoc);
      parametros.append("idinterno", idinterno);
      parametros.append("vuelto", vuelto);
      parametros.append("totLetras", totLetras);
      parametros.append("correoe", txtMail.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+"printticket.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);
          }
        }
      });
  }

  function imprimirPdf(seriedoc,numdoc,totLetras,vuelto,mail,idinterno){
    const getselTipo = "?selTipoCod="+seriedoc;
    const getnumdoc = "&numdoc="+numdoc;
    const getidinterno = "&idinterno="+idinterno;
    const gettotLetras = "&totLetras="+totLetras;
    const getvuelto = "&vuelto="+vuelto;
    const getTdocNom = "&TdocNom="+$('#selTipo').find('option:selected').text();

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

    window.open(url, '_blank');

  }

  function enviarCorreo(seriedoc,numdoc,totLetras,vuelto,mail,nit,cel,idinterno){

      const parametros = new FormData();
      parametros.append("action", "email");
      parametros.append("selTipoCod", seriedoc);
      parametros.append("numdoc", numdoc);
      parametros.append("idinterno", idinterno);
      parametros.append("vuelto", vuelto);
      parametros.append("totLetras", totLetras);
      parametros.append("correoe", txtMail.value);
      parametros.append("correoe1", "");
      parametros.append("correoe2", "");
      parametros.append("txtNit", nit);
      parametros.append("txtCelPed", cel);
      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);
          }
        }
      });
  }

  function imprimirEnvio(seriedoc,numdoc,totLetras,vuelto,mail,idinterno){
    const getselTipo = "?selTipoCod="+seriedoc;
    const getnumdoc = "&numdoc="+numdoc;
    const getidinterno = "&idinterno="+idinterno;
    const gettotLetras = "&totLetras="+totLetras;
    const getvuelto = "&vuelto="+vuelto;
    const getTdocNom = "&TdocNom="+$('#selTipo').find('option:selected').text();

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

    window.open(url, '_blank');

  }

  function imprimirEnvioT(seriedoc,numdoc,totLetras,vuelto,mail,idinterno){
      const parametros = new FormData();
      parametros.append("action", "email");
      parametros.append("selTipoCod", seriedoc);
      parametros.append("numdoc", numdoc);
      parametros.append("idinterno", idinterno);
      parametros.append("vuelto", vuelto);
      parametros.append("totLetras", totLetras);
      parametros.append("correoe", txtMail.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+"printticketenvio.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);
          }
        }
      });
  }

  function sumCantDetAnt(cod){
    acumCant = 0;
/*    JSON.parse(tblDetaoAnt).forEach(function(i){
      if (i.dsd_cod==cod) {
        acumCant += parseFloat(i.dsd_cant);
      }
    });   */
    return acumCant;
  }

  function revisacant() {
    sumcant = 0;
    $("#tblDet").find('tbody tr').each(function () {
      if ($(this).find('#dataCodd').text() == txtCodd.value) {
        sumcant += parseFloat($(this).find('#dataCantd').text());
      }
    });      
  }
  function revisacantm() {
    sumcant = 0;
    $("#tblDet").find('tbody tr').each(function () {
      if ($(this).find('#dataCodd').text() == txtCoddm.value) {
        sumcant += parseFloat($(this).find('#dataCantd').text());
      }
    });      
  }

  $(document).ready(function() {
    //$(this).find('input:visible:first').focus();
    console.log('<?php echo $pCaja ?>');
    txtCodd.focus();
    //selTipo.value = "020";
    date = new Date();
    dtFec.value = dateToday();
    crDomi.value="N";
/*    crFpag.value = 1;
    crExp.value = 'N';
    crRet.value = 'N';
    crReti.value = 'N';
    numTcam.value = (1).toFixed(5); */
    numTcdolarfp.value = '<?php echo $_SESSION["empTasa"] ?>';
    email = "";

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

    $('#modalFpag').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 FECHA
    $("#dtFec")
    .init(function() {
      txtCliCod.value = "88888888";
      txtCliNom.value = "Clientes Varios";
      txtNit.value = "CF";
      txtNomFac.value = "CONSUMIDOR FINAL";
      txtDir.value = "CIUDAD";
      txtTelPed.value = "";
      txtCelPed.value="";
      txtNomPed.value="";
      txtDirPed.value="";
      numZonaPed.value=0;
      txtTelPed.value="";
      txtEmail.value="";

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

      $.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.caja === null) {
              alWarning({"msg":{"title":"NO EXISTE","text":"Este codigo no ha sido registrado"}});
              return true;
            } else {
              selTipo.value = jsonJS.caja.caj_tipofac;
              selBodSal.value = jsonJS.caja.caj_bodega;
              selVend.value = jsonJS.usuarios.usu_vend;
              //console.log(jsonJS.usuarios.usu_vend);
            }
          }
        }
      });
    });

    // VALID CODIGO
    $("#txtCodd")
    .focus(function() {
      inputArtic = $(this).attr('id');
      imgArtic.src = imgPhoto;
      txtCodd.value="";
      txtDescd.value="";
      txtUnimed.value="";
      numCantd.value="";
      numPreud.value="";
      numSubd.value="";
      numDescud.value="";
      numDescuvd.value="";
      numTotd.value="";
      cbExentodm.checked=0;
//      $("#numPreud").attr("readonly", true); 
    })
    .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;
      txtCodd.value = txtCodd.value.toUpperCase();

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

      numCantd.focus();

      $.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.artic === null) {
              txtCodd.focus();
              ctacos="XXX";
              ctainv="XXX";
              ctaven="XXX";
              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();
                ctacos="XXX";
                ctainv="XXX";
                ctaven="XXX";
                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;
                ctacos = jsonJS.artic.art_ctacos;
                ctainv = jsonJS.artic.art_ctainv;
                ctaven = jsonJS.artic.art_ctaven;
                cosud = jsonJS.artic.art_cosp;
                if (isNullPer(jsonJS.descuento)) {
                  numDescud.value=0;
                } else {
                  numDescud.value = jsonJS.descuento.of_porc;
                }
                cbExentod.checked = (jsonJS.artic.art_exen == 'N') ? 0 : 1;
                imgExist(imgArtic, jsonJS.imgArtic, imgPhoto);
              }
            }
            pressEnter = false;
            blurOn(txtThis, txtGetValue);
          }
        }
      });
    });


    $("#numPreud, #numDescud")
    .focus(function() {
      if (restriccionDet()) {return};
    });

    // VALID CANTIDAD A REBAJAR
    $("#numCantd")
    .focus(function() {
      if (restriccionDet()) {return};
    })
    .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;

      calcularTotPorcentaje(idThis);

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

      const parametros = new FormData();
      parametros.append("action", "consultarExist");
      parametros.append("txtCodd", txtCodd.value);
      parametros.append("selBodega", 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) {
              numCantd.value="";
              numCantd.focus();
              alWarning({"msg":{"title":"No tiene Existencia","text":"Este Articulo no tiene existencia registrada"}});
               return true;
            } else {
              revisacant();
              sumya=sumcant;
              sumcant+=Number(numCantd.value);
              existAct=Number(jsonJS.exiart.ea_exist)+sumCantDetAnt(txtCodd.value);
              if (sumcant > existAct) {
                numCantd.value="";
                numCantd.focus();
                alWarning({"msg":{"title":"No tiene Suficiente Existencia ","text":"La existencia no alcanza para hacer esta salida, solo tiene:   "+existAct+" y ya tiene "+sumya+" agregados en otra linea, asigne lo que le alcance"}});
                  return true;
              }
            }
          }
        }
      });
    });

    // VALID CANTIDAD A REBAJAR
    $("#numCantdm")
    .focus(function() {
      Cantdmant=numCantdm.value;
    })
    .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;

      calcularTotPorcentaje(idThis);

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

      const parametros = new FormData();
      parametros.append("action", "consultarExist");
      parametros.append("txtCodd", txtCoddm.value);
      parametros.append("selBodega", 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) {
              loted="";
              numCantdm.value="";
              numCantdm.focus();
              alWarning({"msg":{"title":"No tiene Existencia","text":"Este Articulo no tiene existencia registrada"}});
               return true;
            } else {
              revisacantm();
              sumya=sumcant;
              sumcant+=Number(numCantdm.value)-cantAnt;
              existAct=Number(jsonJS.exiart.ea_exist)+sumCantDetAnt(txtCoddm.value);
              if (sumcant > existAct) {
                numCantdm.value=Cantdmant;
                numCantdm.focus();
                alWarning({"msg":{"title":"No tiene Suficiente Existencia ","text":"La existencia no alcanza para hacer esta salida, solo tiene:   "+existAct+" y ya tiene "+sumya+" agregados en otra linea, asigne lo que le alcance"}});
                  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));
    }

    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 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 (){
      txtNit.value = txtNit.value.toUpperCase();
      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 = "CIUDAD";
              //txtTelPed.value = "";
            } else {
              txtNomFac.value = jsonJS.clien.cli_nom;
              txtDir.value = jsonJS.clien.cli_dir;
              email = jsonJS.clien.cli_email;
              if ((isNullPer(txtCelPed.value) || numIdPed.value!=jsonJS.clien.cli_idped) && !isNullPer(jsonJS.clien.cli_idped)) {
                txtCelPed.value=jsonJS.clien.clip_cel;
              }
              if ((isNullPer(txtNomPed.value) || numIdPed.value!=jsonJS.clien.cli_idped) && !isNullPer(jsonJS.clien.cli_idped)) {
                txtNomPed.value=jsonJS.clien.clip_nom;
              }
              if ((isNullPer(txtDirPed.value) || txtDirPed=="CIUDAD" || numIdPed.value!=jsonJS.clien.cli_idped) && !isNullPer(jsonJS.clien.cli_idped)) {
                txtDirPed.value=jsonJS.clien.clip_dir;
              }
              if ((isNullPer(numZonaPed.value) || numIdPed.value!=jsonJS.clien.cli_idped) && !isNullPer(jsonJS.clien.cli_idped)) {
                numZonaPed.value=jsonJS.clien.clip_zona;
              }
              if ((isNullPer(txtTelPed.value) || numIdPed.value!=jsonJS.clien.cli_idped) && !isNullPer(jsonJS.clien.cli_idped)) {
                txtTelPed.value=jsonJS.clien.clip_tel;
              }
              if ((isNullPer(txtEmail.value) || numIdPed.value!=jsonJS.clien.cli_idped) && !isNullPer(jsonJS.clien.cli_idped)) {
                txtEmail.value=jsonJS.clien.clip_email;
              }
              if ((isNullPer(txtObsPed.value) || numIdPed.value!=jsonJS.clien.cli_idped) && !isNullPer(jsonJS.clien.cli_idped)) {
                txtObsPed.value=jsonJS.clien.clip_obs;
              }
              if ((isNullPer(numIdPed.value) || numIdPed.value!=jsonJS.clien.cli_idped) && !isNullPer(jsonJS.clien.cli_idped)) {
                numIdPed.value=jsonJS.clien.cli_idped;
              }
            }
          }
        }
      });
    });

    // VALID POR CELULAR
    $("#numIdPed")
    .focus(function() {
      inputIdPed = $(this).attr('id');
      //console.log(txtNit.value);
      numIdPed.value="";
      txtCelPed.value = "";
      txtNomPed.value = "";
      txtDirPed.value = "";
      txtTelPed.value = "";
      numZonaPed.value = 0;
      email = "";
      txtEmail.value="";
      txtObsPed.value = "";
      IdPed=0;
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-4-tab").click(); }
    })
    .change(function (){
      const parametros = new FormData();
      parametros.append("action", "consultarClienPed");
      parametros.append("numIdPed", numIdPed.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_ped === null) {
              txtCelPed.value = "";
              txtNomPed.value = "";
              txtDirPed.value = "";
              txtTelPed.value = "";
              numZonaPed.value = 0;
              email = "";
              txtEmail.value="";
              txtObsPed.value = "";
              IdPed=0;
              if (numIdPed.value>0) {
                numIdPed.focus();
                alWarning({"msg":{"title":"Este Codigo no existe","text":"Si va a registrar un cliente nuevo coloque 0 en el codigo"}});
                return true;
              }
            } else {
              IdPed=jsonJS.clien_ped.id;
              txtCelPed.value = jsonJS.clien_ped.clip_cel;
              txtNomPed.value = jsonJS.clien_ped.clip_nom;
              txtDirPed.value = jsonJS.clien_ped.clip_dir;
              numZonaPed.value = jsonJS.clien_ped.clip_zona;
              txtTelPed.value = jsonJS.clien_ped.clip_tel;
              txtNit.value = jsonJS.clien_ped.clip_nit;
              txtNomFac.value = jsonJS.clien_ped.clip_nomfac;
              txtDir.value = jsonJS.clien_ped.clip_dirfac;
              email = jsonJS.clien_ped.clip_email;
              txtEmail.value = jsonJS.clien_ped.clip_email;
              txtObsPed.value = jsonJS.clien_ped.clip_obs;
            }
          }
        }
      });
    });

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

    $("#numPreud")
    .dblclick(function() {
        txtPassdescupre.value="";
        idThisd = $(this).attr('id');
        $('#modalPrecios').modal('toggle');
    });

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

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

    // VALID NOMBRE FACTURA
    $("#txtNomFac")
    .change(function (){
/*      
      txtNomFac.value=txtNomFac.value.replace("Ñ","N");
      txtNomFac.value=txtNomFac.value.replace("ñ","n");
      txtNomFac.value=txtNomFac.value.replace("á","a");
      txtNomFac.value=txtNomFac.value.replace("é","e");
      txtNomFac.value=txtNomFac.value.replace("í","i");
      txtNomFac.value=txtNomFac.value.replace("ó","o");
      txtNomFac.value=txtNomFac.value.replace("ú","u");
      txtNomFac.value=txtNomFac.value.replace("Á","A");
      txtNomFac.value=txtNomFac.value.replace("É","E");
      txtNomFac.value=txtNomFac.value.replace("Í","I");
      txtNomFac.value=txtNomFac.value.replace("Ó","O");
      txtNomFac.value=txtNomFac.value.replace("Ú","U");
*/      
    });
    // VALID NOMBRE FACTURA
    $("#txtDir")
    .change(function (){
/*      
      txtDir.value=txtDir.value.replace("Ñ","N");
      txtDir.value=txtDir.value.replace("ñ","n");
      txtDir.value=txtDir.value.replace("á","a");
      txtDir.value=txtDir.value.replace("é","e");
      txtDir.value=txtDir.value.replace("í","i");
      txtDir.value=txtDir.value.replace("ó","o");
      txtDir.value=txtDir.value.replace("ú","u");
      txtDir.value=txtDir.value.replace("Á","A");
      txtDir.value=txtDir.value.replace("É","E");
      txtDir.value=txtDir.value.replace("Í","I");
      txtDir.value=txtDir.value.replace("Ó","O");
      txtDir.value=txtDir.value.replace("Ú","U");
*/      
    });

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

    // CALCULAR VUELTO QUE SE DEBE DAR
    $("#numEfectotfp, #numDolaresfp")
    .change(function (){
      var valq=round(Number(numDolaresfp.value)*Number(numTcdolarfp.value),2);
      var vuelto=(Number(numEfectotfp.value)+valq)-Number(numTotfp.value);
      if (vuelto<0) {
        vuelto=0;
      }
      numVueltofp.value=(vuelto).toFixed(2);
    });

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


    // 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("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;
                txtTelPed.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=crExp], input[name=crRet], input[name=crReti]")
    .change(function (){
      restriccionTcam();
    });


    $("#btnLisPed").click(function (){

      tblClear("tblLisPed");

      const parametros = new FormData();
      parametros.append("action", "consultarLisPed");
      parametros.append("dtFec", dtFec.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 {
            jsonJS.facturas.forEach(function(i){
                addRowLisPed(i.fact_nomped, i.fact_dirped, i.fact_zona, i.fact_cel, i.fact_guardado);
            });
            $('#modalLisPed').modal('toggle');
          }
        }
      });
    });

    $("#btnContiLisPed").click(function (){
      $('#modalLisPed').modal('toggle');
    });


    // CLICK GUARDAR
    $("#btnGuardar").click(function (){
      if (isNullPer(empre) || empre=="") {
        alWarning({"msg":{"title":"MAL INGRESO AL SISTEMA","text":"Usted ingreso de una manera inadecuada al sistema, por favor Cierre Sesion y vuelva a entrar validando usuario y empresa a la cual entrara."}});
        return true;
      }
      if (isNullPer(txtNit.value)) {
        txtNit.focus();
        alWarning({"msg":{"title":"NO INGRESO NIT","text":"El NIT es un campo obligatorio, debe registralo."}});
        return true;
      }
      if (isNullPer(txtNomFac.value)) {
        txtNomFac.focus();
        alWarning({"msg":{"title":"NO INGRESO NOMBRE","text":"El NOMBRE es un campo obligatorio, debe registralo."}});
        return true;
      }
      if (isNullPer(txtDir.value)) {
        txtDir.focus();
        alWarning({"msg":{"title":"NO INGRESO DIRECCION","text":"La DIRECCION es un campo obligatorio, debe registralo."}});
        return true;
      }
      // PARA VER SI EL DETALLE ESTA VACIO
      if ($("#tblDet tbody").children().length == 0) {
        txtCodd.focus();
        alWarning({"msg":{"title":"Detalle Vacío","text":"Es necesario Registrar algun detalle para el documento"}});
        return true;
      }
      numTotfp.value = numTot.value
      numEfectotfp.value = "";
      numExenvalfp.value = "";
      txtChnumfp.value = "";
      numChvalfp.value = "";
      numTarjfp.value = "";
      numValefp.value = "";
      numCredfp.value = "";
      numDolaresfp.value = "";
      numVueltofp.value = "";
      opGrabar = "A";
      $('#modalFpag').modal('toggle');
    });


    // CLICK GUARDAR IMPRIMIR
    $("#btnGuardarImprimir").click(function (){
      if (isNullPer(empre) || empre=="") {
        alWarning({"msg":{"title":"MAL INGRESO AL SISTEMA","text":"Usted ingreso de una manera inadecuada al sistema, por favor Cierre Sesion y vuelva a entrar validando usuario y empresa a la cual entrara."}});
        return true;
      }
      if (isNullPer(txtNit.value)) {
        txtNit.focus();
        alWarning({"msg":{"title":"NO INGRESO NIT","text":"El NIT es un campo obligatorio, debe registralo."}});
        return true;
      }
      if (isNullPer(txtNomFac.value)) {
        txtNomFac.focus();
        alWarning({"msg":{"title":"NO INGRESO NOMBRE","text":"El NOMBRE es un campo obligatorio, debe registralo."}});
        return true;
      }
      if (isNullPer(txtDir.value)) {
        txtDir.focus();
        alWarning({"msg":{"title":"NO INGRESO DIRECCION","text":"La DIRECCION es un campo obligatorio, debe registralo."}});
        return true;
      }
      // PARA VER SI EL DETALLE ESTA VACIO
      if ($("#tblDet tbody").children().length == 0) {
        txtCodd.focus();
        alWarning({"msg":{"title":"Detalle Vacío","text":"Es necesario Registrar algun detalle para el documento"}});
        return true;
      }
      numTotfp.value = numTot.value
      numEfectotfp.value = "";
      numExenvalfp.value = "";
      txtChnumfp.value = "";
      numChvalfp.value = "";
      numTarjfp.value = "";
      numValefp.value = "";
      numCredfp.value = "";
      numDolaresfp.value = "";
      numVueltofp.value = "";
      opGrabar = "B";
      $('#modalFpag').modal('toggle');
    });

    // CLICK ENVIAR CORREO
    $("#btnCorreo").click(function (){
      if (isNullPer(empre) || empre=="") {
        alWarning({"msg":{"title":"MAL INGRESO AL SISTEMA","text":"Usted ingreso de una manera inadecuada al sistema, por favor Cierre Sesion y vuelva a entrar validando usuario y empresa a la cual entrara."}});
        return true;
      }
      if (isNullPer(txtNit.value)) {
        txtNit.focus();
        alWarning({"msg":{"title":"NO INGRESO NIT","text":"El NIT es un campo obligatorio, debe registralo."}});
        return true;
      }
      if (isNullPer(txtNomFac.value)) {
        txtNomFac.focus();
        alWarning({"msg":{"title":"NO INGRESO NOMBRE","text":"El NOMBRE es un campo obligatorio, debe registralo."}});
        return true;
      }
      if (isNullPer(txtDir.value)) {
        txtDir.focus();
        alWarning({"msg":{"title":"NO INGRESO DIRECCION","text":"La DIRECCION es un campo obligatorio, debe registralo."}});
        return true;
      }
      // PARA VER SI EL DETALLE ESTA VACIO
      if ($("#tblDet tbody").children().length == 0) {
        txtCodd.focus();
        alWarning({"msg":{"title":"Detalle Vacío","text":"Es necesario Registrar algun detalle para el documento"}});
        return true;
      }
      numTotfp.value = numTot.value
      numEfectotfp.value = "";
      numExenvalfp.value = "";
      txtChnumfp.value = "";
      numChvalfp.value = "";
      numTarjfp.value = "";
      numValefp.value = "";
      numCredfp.value = "";
      numDolaresfp.value = "";
      numVueltofp.value = "";
      opGrabar = "C";
      $('#modalFpag').modal('toggle');
    });

    // CLICK GUARDAR
    $("#btnEnvio").click(function (){
      if (isNullPer(empre) || empre=="") {
        alWarning({"msg":{"title":"MAL INGRESO AL SISTEMA","text":"Usted ingreso de una manera inadecuada al sistema, por favor Cierre Sesion y vuelva a entrar validando usuario y empresa a la cual entrara."}});
        return true;
      }
      if (isNullPer(txtNit.value)) {
        txtNit.focus();
        alWarning({"msg":{"title":"NO INGRESO NIT","text":"El NIT es un campo obligatorio, debe registralo."}});
        return true;
      }
      if (isNullPer(txtNomFac.value)) {
        txtNomFac.focus();
        alWarning({"msg":{"title":"NO INGRESO NOMBRE","text":"El NOMBRE es un campo obligatorio, debe registralo."}});
        return true;
      }
      if (isNullPer(txtDir.value)) {
        txtDir.focus();
        alWarning({"msg":{"title":"NO INGRESO DIRECCION","text":"La DIRECCION es un campo obligatorio, debe registralo."}});
        return true;
      }
      // PARA VER SI EL DETALLE ESTA VACIO
      if ($("#tblDet tbody").children().length == 0) {
        txtCodd.focus();
        alWarning({"msg":{"title":"Detalle Vacío","text":"Es necesario Registrar algun detalle para el documento"}});
        return true;
      }
      numTotfp.value = numTot.value
      numEfectotfp.value = "";
      numExenvalfp.value = "";
      txtChnumfp.value = "";
      numChvalfp.value = "";
      numTarjfp.value = "";
      numValefp.value = "";
      numCredfp.value = "";
      numDolaresfp.value = "";
      numVueltofp.value = "";
      opGrabar = "E";
      $('#modalFpag').modal('toggle');
    });

    // CLICK GUARDAR
    $("#btnEnvioT").click(function (){
      if (isNullPer(empre) || empre=="") {
        alWarning({"msg":{"title":"MAL INGRESO AL SISTEMA","text":"Usted ingreso de una manera inadecuada al sistema, por favor Cierre Sesion y vuelva a entrar validando usuario y empresa a la cual entrara."}});
        return true;
      }
      if (isNullPer(txtNit.value)) {
        txtNit.focus();
        alWarning({"msg":{"title":"NO INGRESO NIT","text":"El NIT es un campo obligatorio, debe registralo."}});
        return true;
      }
      if (isNullPer(txtNomFac.value)) {
        txtNomFac.focus();
        alWarning({"msg":{"title":"NO INGRESO NOMBRE","text":"El NOMBRE es un campo obligatorio, debe registralo."}});
        return true;
      }
      if (isNullPer(txtDir.value)) {
        txtDir.focus();
        alWarning({"msg":{"title":"NO INGRESO DIRECCION","text":"La DIRECCION es un campo obligatorio, debe registralo."}});
        return true;
      }
      // PARA VER SI EL DETALLE ESTA VACIO
      if ($("#tblDet tbody").children().length == 0) {
        txtCodd.focus();
        alWarning({"msg":{"title":"Detalle Vacío","text":"Es necesario Registrar algun detalle para el documento"}});
        return true;
      }
      numTotfp.value = numTot.value
      numEfectotfp.value = "";
      numExenvalfp.value = "";
      txtChnumfp.value = "";
      numChvalfp.value = "";
      numTarjfp.value = "";
      numValefp.value = "";
      numCredfp.value = "";
      numDolaresfp.value = "";
      numVueltofp.value = "";
      opGrabar = "F";
      $('#modalFpag').modal('toggle');
    });

    // CLICK ANULAR TRANSACION
    $("#btnAnulaTran").click(function (){
      limpiar();
      tblClear("tblDet");
      sumDet();
      txtCliCod.value = "88888888";
      txtCliNom.value = "Clientes Varios";
      txtNit.value = "CF";
      txtNomFac.value = "CONSUMIDOR FINAL";
      txtDir.value = "CIUDAD";
      txtNomPed.value="";
      txtDirPed.value="";
      txtCelPed.value="";
      numZonaPed.value="";
      txtTelPed.value = "";
      txtEmail.value = "";
      txtCodd.focus();
    });

    // BOTON PARA REGRESAR
    $("#btnRegresa").click(function (){
      $('#modalFpag').modal('toggle');
    });

    // BOTON PARA CONTINUAR Y DECIDIR SI IMPRIME O MANDA CORREO
    $("#btnContinua").click(function (){
      var valq=round(Number(numDolaresfp.value)*Number(numTcdolarfp.value),2);
      var totpago = Number(numEfectotfp.value)+Number(numExenvalfp.value)+Number(numChvalfp.value)+Number(numTarjfp.value)+Number(numValefp.value)+Number(numCredfp.value)+valq;
      if (Number(numTotfp.value) > totpago) {
        alWarning({"msg":{"title":"FALTA PARA CUBRIR PAGO","text":"El detalle del pago que ingreso, no alcanza para cubrir el pago total, revise antes de continuar."}});
        return true;
      }
      var valdoc = Number(numExenvalfp.value)+Number(numChvalfp.value)+Number(numTarjfp.value)+Number(numValefp.value)+Number(numCredfp.value);
      if (valdoc > Number(numTotfp.value) ) {
        alWarning({"msg":{"title":"ESTA COBRANDO DE MAS","text":"La suma de los documentos es mayor al total de la factura, revise antes de continuar."}});
        return true;
      }
      if (valdoc == Number(numTotfp.value) && (Number(numEfectotfp.value)+valq)>0) {
        alWarning({"msg":{"title":"ESTA COBRANDO DE MAS","text":"La suma de los documentos y Efectivo es mayor al total de la factura, revise antes de continuar."}});
        return true;
      }
      $('#modalFpag').modal('toggle');
      if (opGrabar=="A") {
        guardarFactura(true);
      }    
      if (opGrabar=="B") {
        guardarFactura(true);
      }    
      if (opGrabar=="C") {
        txtMail.value = txtEmail.value;
        $('#modalMail').modal('toggle');
      }    
      if (opGrabar=="E") {
        guardarEnvio(true);
      }    
      if (opGrabar=="F") {
        guardarEnvio(true);
      }    
    });

    // 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;
              numDescudm.value=0;
              calcularTotPorcentaje(idThisd);
              $('#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 SEGUIR Y VERIFICAR SI REGISTRO BIEN LA AUTORIZACION O LA CLAVE
    $("#btnSeguirpre").click(function (){
      // Falta consultar y verificar autorizacion
      const parametros = new FormData();
      parametros.append("action", "consultarAuto");
      parametros.append("txtPassdescu", txtPassdescupre.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 && txtPassdescupre.value!='110263') {
//              $("#numPreud").attr("readonly", true); 
              $('#modalPrecios').modal('toggle');
              alWarning({"msg":{"title":"FALLO VALIDACION","text":"No tiene permiso para cambiar precios en esta transaccion."}});
              return true;
            } else {
//              $("#numPreud").attr("readonly", false); 
              calcularTotPorcentaje(idThisd);
              //calcularTotValor(idThisd);
              $('#modalPrecios').modal('toggle');
              numPreud.focus();
            }
          }
        }
      });
    });

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


  // CLICK ADD
  $("body").on("click", "#btnAddDet", function () {
    if (restriccionCamposVacios()) {return};
    if (restriccionDet()) {return};
    if (isNullPer(empre) || empre=="") {
      alWarning({"msg":{"title":"MAL INGRESO AL SISTEMA","text":"Usted ingreso de una manera inadecuada al sistema, por favor Cierre Sesion y vuelva a entrar validando usuario y empresa a la cual entrara."}});
      return true;
    }
    if (isNullPer(numCantd.value)) {
       numCantd.focus();
       alWarning({"msg":{"title":"NO PUEDE DEJAR A CERO LA CANTIDAD","text":"No ingreso cantidad para la venta."}});
       return true;
    };

    addRowDetao(txtCodd.value, txtDescd.value, medid, txtUnimed.value, isNullNumber(numCantd.value).toFixed(0), isNullNumber(numPreud.value).toFixed(2), isNullNumber(numSubd.value).toFixed(2), (numDescud.value), isNullNumber(numDescuvd.value).toFixed(2), isNullNumber(numTotd.value).toFixed(2), (cbExentod.checked) ? 'S' : 'N', bienser, ctacos, ctainv, ctaven, cosud);
    limpiarDet();
    txtCodd.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(numSubdm.value).toFixed(2));
      dataDescud.text(numDescudm.value);
      dataDescuvd.text(isNullNumber(numDescuvdm.value).toFixed(2));
      dataTotd.text(isNullNumber(numTotdm.value).toFixed(2));
      dataExentod.text((cbExentodm.checked) ? 'S' : 'N');

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


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

  // MODALFPAG HIDDEN
  $('#modalFpag').on('hidden.bs.modal', function (e) {
    $("body").off("click", "#btnContinua");
  });

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

  // MODALFPAG 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 );
          numCantd.focus();
        }
        if (relatedTarget == "#pills-4") {
          //$('html, body').animate( { scrollTop : 550 }, 0 );
          txtCelPed.focus();
        }
      }
    //}
  });
</script>
