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

$dtFec=date("Y-m-d");
$nAnio=date("Y");
$nMes=date("m");

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

$cajBodega = $_SESSION['cajBodega'];

# QUERYS
$sSerieoc = "SELECT * FROM serieoc WHERE so_emp='$empCod' ORDER BY so_cod";
$sTipodoci = "SELECT * FROM tipodoci WHERE td_eos='E' AND td_movbod='S' ORDER BY td_cod";
$sBodegas = "SELECT * FROM bodegas where bod_emp='$empCod' AND bod_cod='$cajBodega' ORDER BY bod_cod";
$sBodegas2 = "SELECT * FROM bodegas where bod_emp='$empCod' AND bod_cod!='$cajBodega' ORDER BY bod_cod";
$sCiemes = "SELECT ciem_stat FROM ciemes WHERE ciem_emp='$empCod' AND ciem_ano=$nAnio AND ciem_mes=$nMes";

$sMeses = "SELECT * FROM meses";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["serieoc"] = $db->query($sSerieoc);
$select["tipodoci"] = $db->query($sTipodoci);
$select["bodegas"] = $db->query($sBodegas);
$select["bodegas2"] = $db->query($sBodegas2);
$mesCerrado = ($db->sFetchAssoc($sCiemes)["ciem_stat"] == "C") ? "true" : "false";

$select["meses"] = $db->query($sMeses);
$anoTrab=date("Y", strtotime($_SESSION['empFtrab']));
$mesTrab=date("m", strtotime($_SESSION['empFtrab']));
$db->close();
?>
<?php include_once('../includes/htmlOpen.php'); ?>
    <main class="main" style="">
      <?php 
        $li[0] = '<i class="fas fa-file-invoice"></i>';
        $li[1] = $_GET["opcNom"];
        include_once('../../../php/includes/ol.php');
      ?>

      <!-- MODAL DETALLE DOCUMENTO -->
      <div class="modal fade" id="modalDetao" tabindex="-1" role="dialog" aria-labelledby="modalDetaoTitle" 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-00-tab" data-toggle="pill" href="#pills-00" role="tab" aria-controls="pills-00" aria-selected="true"></a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" id="pills-01-tab" data-toggle="pill" href="#pills-01" role="tab" aria-controls="pills-01" aria-selected="false">Buscar Articulos</a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-light" aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">

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

                      <div class="form-row">
                        <div class="col-md-3">
                          <label class="font-size-sm text-success" for="txtCoddm">Código</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtCoddm" maxlength="20" disabled>
                        </div>
                        <div class="col-sm-9 col-md-7">
                          <label class="font-size-sm text-success" for="txtDescdm">Descripción</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtDescdm" maxlength="120" disabled>
                        </div>
                        <div class="col-sm-3 col-md-2">
                          <label class="font-size-sm text-success" for="txtMedidm">Medida</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtMedidm" maxlength="20" disabled>
                        </div>
                        <div class="col-3">
                          <label class="font-size-sm" for="dtFvencem">Fecha Vencimiento</label>
                          <input type="date" class="form-control form-control-sm form-control-as" id="dtFvencem" placeholder="">
                        </div>
                      </div>
                      <div class="form-row align-items-end">
                        <div class="col-6 col-sm-3 col-md-2">
                          <label class="font-size-sm text-success" for="numCantdm">Cantidad</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numCantdm">
                        </div>
                        <div class="col-6 col-sm-3">
                          <label class="font-size-sm text-success" for="numCosudm">Precio/Unitario</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-5" id="numCosudm" disabled>
                        </div>
                        <div class="col-6 col-sm-3">
                          <label class="font-size-sm text-success" for="numTotdm">Importe Total</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-5" id="numTotdm" disabled>
                        </div>
                      </div>

                    </div>

                    <button type="button" class="btn btn-success btn-block" id="btnAgregar">Agregar</button>

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

                </div>
                <div class="tab-pane fade" id="pills-01" role="tabpanel" aria-labelledby="pills-01-tab">
                  <?php
                    $a='00';
                    $b='01';
                    include('../busArtic2/index.html');
                  ?>
                </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 for="txtDcodlis">Codigo</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtDcodlis" disabled>
                        </div>
                        <div class="col-md-8">
                          <label for="txtDdesclis">Descripcion</label>
                          <input type="text" class="form-control form-control-sm 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" width="80">LOTE</th>
                                  <th scope="col" class="text-center" width="80">FEC/VENCIMIENTO</th>
                                  <th scope="col" class="text-center" width="100">EXISTENCIA</th>
                                  <th scope="col" class="text-center" width="100">SELECCIONAR</th>
                                </tr>
                              </thead>
                              <tbody>
                              </tbody>
                              <tfoot>
                                <th scope="col"></th>
                                <th scope="col" class="text-right">Total</th>
                                <th scope="col" id="dataTotExistLis" class="text-right">0.00</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 POLIZA -->
      <div class="modal fade" id="modalPol" tabindex="-1" role="dialog" aria-labelledby="modalPolTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
          <div class="modal-content bg-dark">
            <div class="modal-header">
              <ul class="nav nav-pills" id="pills-tab" role="tablist">
                <li class="nav-item">
                  <a class="nav-link active" id="pills-000-tab" data-toggle="pill" href="#pills-000" role="tab" aria-controls="pills-000" aria-selected="true"></a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" id="pills-01-tab" data-toggle="pill" href="#pills-001" role="tab" aria-controls="pills-001" aria-selected="false">Buscar Cuentas</a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-light" 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-000" role="tabpanel" aria-labelledby="pills-000-tab">
                  
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">
                      <div class="form-row">
                        <div class="col-md-4">
                          <label for="txtCta">Cuenta</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtCta" placeholder="">
                        </div>
                        <div class="col-md-8">
                          <label for="txtCtaNom">Nombre Cuenta</label>
                          <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtaNom" placeholder="" disabled>
                        </div>
                      </div>
                      <div class="form-row">
                        <div class="col-md-6">
                          <label for="numDebe">Debe</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numDebe" placeholder="0.00">
                        </div>
                        <div class="col-md-6">
                          <label for="numHaber">Haber</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numHaber" placeholder="0.00">
                        </div>
                      </div>
                    </div>

                    <button type="button" class="btn btn-success btn-block" id="btnAgregarp">Agregar</button>
                    <button type="button" class="btn btn-success btn-block" id="btnModificarp">Modificar</button>
                  </form>

                </div>
                <div class="tab-pane fade" id="pills-001" role="tabpanel" aria-labelledby="pills-001-tab">
                  <?php
                    $a='000';
                    $b='001';
                    include('../busCuentasMov/index.html');
                  ?>
                </div>
              </div>

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

      <div class="container-as">
        <div class="row">
          <div class="col">
            <ul class="nav nav-pills mb-1" id="pills-tab" role="tablist">
              <li class="nav-item">
                <a class="nav-link active" id="pills-0-tab" data-toggle="pill" href="#pills-0" role="tab" aria-controls="pills-0" aria-selected="true">Mantenimiento</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" id="pills-1-tab" data-toggle="pill" href="#pills-1" role="tab" aria-controls="pills-1" aria-selected="true">Buscar Articulos</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-md-10">
                      <div class="form-group">
                        <div class="form-row align-items-center">
                          <div class="col-md-12">
                            <div class="form-row align-items-end">
                              <div class="col-3">
                                <label class="font-size-md" for="selTdoci">Tipo de Documento</label>
                                <select class="form-control form-control-md form-control-as" name="selTdoci" id="selTdoci">
                                  <?php
                                    while ($rec = $db->fetchAssoc($select['tipodoci'])) {
                                      echo  '<option value="'.$rec['td_cod'].'" data-afecos="'.$rec['td_afecos'].'" data-partsn="'.$rec['td_partsn'].'" data-relatv="'.$rec['td_relatv'].'" data-relatpol="'.$rec['td_relatpol'].'" data-inveini="'.$rec['td_inveini'].'">'.utf8_encode($rec['td_nom']).'</option>';
                                    }
                                  ?>
                                </select>
                              </div>
                              <div class="col-3">
                                <label class="font-size-md" for="dtFec">Fecha Documento</label>
                                <input type="date" class="form-control form-control-md form-control-as" id="dtFec" placeholder="">
                              </div>
                            </div>
                            <div class="form-row">
                              <div class="col-3">
                                <label class="font-size-md" for="selBodega">Bodega de donde Saldrá</label>
                                <select class="form-control form-control-md form-control-as" name="selBodega" id="selBodega">
                                  <?php
                                    while ($rec = $db->fetchAssoc($select['bodegas'])) {
                                      echo  '<option value="'.$rec['bod_cod'].'" data-ctainv="'.$rec['bod_ctainv'].'">'.utf8_encode($rec['bod_nom']).'</option>';
                                    }
                                  ?>
                                </select>
                              </div>
                              <div class="col-3">
                                <label class="font-size-md" for="selBodega2">Bodega donde Entrará</label>
                                <select class="form-control form-control-md form-control-as" name="selBodega2" id="selBodega2">
                                  <?php
                                    while ($rec = $db->fetchAssoc($select['bodegas2'])) {
                                      echo  '<option value="'.$rec['bod_cod'].'" data-ctainv="'.$rec['bod_ctainv'].'">'.utf8_encode($rec['bod_nom']).'</option>';
                                    }
                                  ?>
                                </select>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-10">
                            <label class="font-size-md" for="txtCon">Concepto</label>
                            <textarea class="form-control form-control-md form-control-as" id="txtCon" rows="2"></textarea>
                          </div>
                        </div>
                        <div class="form-row">
                        </div>
                      </div>
                      <h3 class="text-light"></h3>
                      <div class="form-group">
                        <h4 class="text-success">DETALLE DEL DOCUMENTO:</h4>
                        <div class="form-row">
                          <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" id="txtCodd" maxlength="20">
                          </div>
                          <div class="col-7">
                            <label class="font-size-md text-success" for="txtDescd">Descripción</label>
                            <input type="text" class="form-control form-control-md form-control-as" id="txtDescd" maxlength="120">
                          </div>
                          <div class="col-1">
                            <label class="font-size-md text-success" for="txtMedid">Medida</label>
                            <input type="text" class="form-control form-control-md form-control-as" id="txtMedid" maxlength="20" disabled>
                          </div>
                        </div>
                        <div class="form-row align-items-end">
                          <div class="col-2">
                            <label class="font-size-md" for="dtFvenced">Fecha Vencimiento</label>
                            <input type="date" class="form-control form-control-md form-control-as" id="dtFvenced" placeholder="">
                          </div>
                          <div class="col-2">
                            <label class="font-size-md text-success" for="numCantd">Cantidad</label>
                            <input type="number" class="form-control form-control-md form-control-as dec-2" id="numCantd" placeholder="0.00">
                          </div>
                          <div class="col-2">
                            <label class="font-size-md text-success" for="numCosud">Precio/Unitario</label>
                            <input type="number" class="form-control form-control-md form-control-as dec-5" id="numCosud" disabled>
                          </div>
                          <div class="col-2">
                            <label class="font-size-md text-success" for="numTotd">Importe Total</label>
                            <input type="number" class="form-control form-control-md form-control-as dec-5" id="numTotd" disabled>
                          </div>
                          <div class="col-3">
                            <button type="button" class="btn btn-warning" id="btnExistpeps">
                              <i class="fas fa-plus-circle"></i> BUSCAR EXISTENCIAS
                            </button>
                          </div>

                        </div>
                      </div>

                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-11 text-left">
                            <button type="button" class="btn btn-success" id="btnAdd">
                              <i class="fas fa-plus-circle"></i> Agregar a tabla
                            </button>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-12 text-right mb-2">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-md-12">
                            <div class="table-responsive">
                              <table class="table table-hover table-bordered table-dark table-lg" id="tblDetao">
                                <thead>
                                  <tr>
                                    <th scope="col" class="text-center ignore" width="50">ACCIONES</th>
                                    <th scope="col" class="text-center" width="90">CODIGO</th>
                                    <th scope="col" class="text-center" width="300">DESCRIPCIÓN</th>
                                    <th scope="col" class="text-center" width="70">MEDIDA</th>
                                    <th scope="col" class="text-center" width="70">FEC/VENC</th>
                                    <th scope="col" class="text-center" width="70">CANTIDAD</th>
                                    <th scope="col" class="text-center" width="70">COST/UNIT.</th>
                                    <th scope="col" class="text-center" width="90">IMPORTE</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" class="text-right">Totales</th>
                                  <th scope="col" id="dataTotCant" class="text-right">0.00</th>
                                  <th scope="col"></th>
                                  <th scope="col" id="dataTotTot" class="text-right">0.00000</th>
                                </tfoot>
                              </table>
                            </div>
                          </div>
                        </div>
                      </div>

                      <h3 class="text-light"></h3>

                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-5">
                            <button type="button" class="btn btn-primary" id="btnAddp">
                              <i class="fas fa-plus-circle"></i> Agregar
                            </button>
                          </div>
                          <div class="col-7 text-right">
                            <button class="btn btn-primary" id="btnPartida" type="button"><i class="fas fa-poll-h"></i> Generar Partida</button>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-12 text-right mb-2">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-md-12">
                            <div class="table-responsive">
                              <table class="table table-hover table-bordered table-dark table-sm" id="tblPol">
                                <thead>
                                  <tr>
                                    <th scope="col" class="text-center ignore" width="50">ACCIONES</th>
                                    <th scope="col" class="text-center">CUENTA</th>
                                    <th scope="col" class="text-center">DESCRIPCIÓN</th>
                                    <th scope="col" class="text-center">DEBE</th>
                                    <th scope="col" class="text-center">HABER</th>
                                  </tr>
                                </thead>
                                <tbody>
                                </tbody>
                                <tfoot>
                                  <th scope="col" class="ignore"></th>
                                  <th scope="col"></th>
                                  <th scope="col" class="text-right">Totales</th>
                                  <th scope="col" id="dataTotDebe" class="text-right">0.00</th>
                                  <th scope="col" id="dataTotHaber" class="text-right">0.00</th>
                                </tfoot>
                              </table>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="form-group">
                        <div class="form-row">
                        </div>
                      </div>
                    </div>

                    <div class="col-md-2">
                      <div class="form-group position-fixed-md">

                        <div class="form-row">
                          <div class="col-12 mt-2">
                            <button class="btn btn-info btn-block" id="btnGuardarImprimir" type="button">Imprimir / Guardar</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-success btn-block" id="btnGuardar" type="button">Guardar</button>
                          </div>
<!---                          
                          <div class="col-12 mt-2">
                            <button class="btn btn-danger btn-block" id="btnAnular" type="button">Anular</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-primary btn-block" id="btnBorrar" type="button">Borrar</button>
                          </div>
--->                          
                          <div class="col-3 col-md-12"></div>
                          <div class="col-6 col-md-12 text-center mt-3">
                            <div class="upload-btn-wrapper text-center" style="height: 150px; width: 100%;">
                              <img class="rounded-lg" name="imgArtic" width="100%" height="100%" style="object-fit: cover;" />
                            </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('../busArtic/index.html');
                ?>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var nuevoArtic = true;
  var mesCerrado = false;
  var inputCtaMov = "txtCta";
  var totant = 0;
  var inputDocp = "numNum";
  var tblDetaoAnt;
  var tblPolAnt;
  var btnAddEdit = "00";
  var inputArtic = "txtCodd";
  var unimed = "XXX";
  var ctaInc = false;
  var cantAnt=0;
  var Bodegaant="";
  var Bodegaant2="";
  var dtFecant=dateToday();
  var dtFvenceant = "0000-00-00";
  var loted = "";
  var inputFvence = "0000-00-00";

  var Bodegaant="";
  var Bodegaant2="";
  var dtFecant=dateToday();
  var empre = '<?php echo $empCod; ?>';

  const selTdoci = document.thisform.selTdoci;
  const numNum = document.thisform.numNum;
  const selBodega = document.thisform.selBodega;
  const selBodega2 = document.thisform.selBodega2;
  const dtFec = document.thisform.dtFec;
  const txtCon = document.thisform.txtCon;

  const txtCodd = document.thisform.txtCodd;
  const txtDescd = document.thisform.txtDescd;
  const txtMedid = document.thisform.txtMedid;
  const dtFvenced = document.thisform.dtFvenced;
  const numCantd = document.thisform.numCantd;
  const numCosud = document.thisform.numCosud;
  const numTotd = document.thisform.numTotd;

  const txtCoddm = document.getElementById("txtCoddm");
  const txtDescdm = document.getElementById("txtDescdm");
  const txtMedidm = document.getElementById("txtMedidm");
  const dtFvencem = document.getElementById("dtFvencem");
  const numCantdm = document.getElementById("numCantdm");
  const numCosudm = document.getElementById("numCosudm");
  const numTotdm = document.getElementById("numTotdm");

  const imgPhoto = "../../img/photo.jpg";


  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(selTdoci.value)) {
        selTdoci.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar Tipo de Documento"}});
        return true;
      }
/*      
      if (isNullPer(numNum.value)  || numNum.value == 0) {
        numNum.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE DOCUMENTO"}});
        return true;
      }
*/      
      // PARA VER SI EL DETALLE ESTA VACIO
      if ($("#tblDetao tbody").children().length == 0) {
        alWarning({"msg":{"title":"Detalle Vacío","text":"Es necesario Registrar algun detalle para el documento"}});
        return true;
      }
      if ($("#dataTotDebe").text() != $("#dataTotHaber").text() && $('#selTdoci').find('option:selected').data('partsn') == 'S') {
        alWarning({"msg":{"title":"Valores Incorrectos","text":"La partida no cuadra, verifique los valores"}});
        return true;
      }
      // RECORRER PARTIDA PARA BUSCAR UNA CUENTA INCORRECTA
      var ctaInc = false;
      $("#tblPol tbody tr").each(function(){
        if ($(this).find("td:eq(1)").text().includes('XXXX')) { ctaInc = true }
        if ($(this).find("td:eq(1)").text()==' ') { ctaInc = true }
      });
    } else {
      if (isNullPer(selTdoci.value)) {
        return true;
      }
/*      
      if (isNullPer(numNum.value)  || numNum.value == 0) {
        numNum.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE DOCUMENTO"}});
        return true;
      }  */
    }
    return false;
  }

  function restriccionMesCerrado() {
    if (mesCerrado) {
      alError({"msg":{"type":"error","title":"Mes Cerrado","text":"No puede trabajar con este mes porque ya fue cerrado", "ok":"Aceptar"}});
      return true;
    }
/*    
    if (isNullPer(numNum.value)) {
      numNum.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE DOCUMENTO"}});
      return true;
    }  */
    return false;
  }

  function restriccionCta() {
    if (isNullPer(txtCta.value)) {
      txtCtaNom.value = "";
      return true;
    }
    return false;
  }

  function restriccionCtaCod() {
    if (isNullPer($("#"+inputCtaMov).val())) {
      $("#"+inputCtaMov+"Nom").val("");
      return true;
    }
    return false;
  }

  function restriccionCamposVacios() {
    if (isNullPer(selTdoci.value)) {
      selTdoci.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar Tipo de Documento"}});
      return true;
    }
    return false;
  }


  function restriccionCoddm() {
    if (isNullPer(txtCoddm.value)) {
      txtDescdm.value = "";
      return true;
    }
    return false;
  }

/*  function restriccionCoddm() {
    if (isNullPer($("#"+inputArtic).val())) {
      $("#txtDescdm").val("");
      return true;
    }
    return false;
  }  */

  function restriccionModal() {
    if (restriccionCoddm()) {
      txtCoddm.focus();
      alWarningTimer({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar Codigo de Articulo","timer":timeOutWarningSm}});
      return true;
    }
    $('#modalDetao').modal('toggle');
    return false;
  }


  function addRowDetao(codd, descd, unimed, medid, loted, fvenced, cantd, cosud, totd){
    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='btnDel'><i class='fas fa-trash-alt'></i></button>"
                    +"<button type='button' class='btn btn-primary btn-sm btn-actions' id='btnEdit' data-toggle='modal' data-target='#modalDetao'><i class='fas fa-edit'></i></button>"
                  +"</div>"
                +"</td>"
                +"<td id='dataCodd'>"+codd+"</td>"
                +"<td id='dataDescd'>"+descd+"</td>"
                +"<td id='dataUnimed' class='d-none'>"+unimed+"</td>"
                +"<td id='dataMedid' class='text-center'>"+medid+"</td>"
                +"<td id='dataLoted' class='d-none'>"+loted+"</td>"
                +"<td id='dataFvenced' class='text-center'>"+fvenced+"</td>"
                +"<td id='dataCantd' class='text-right'>"+cantd+"</td>"
                +"<td id='dataCosud' class='text-right'>"+cosud+"</td>"
                +"<td id='dataTotd' class='text-right'>"+totd+"</td>"
                +"<td id='dataFlag' class='d-none'>"+flag+"</td>"
                +"</tr>";
    $("#tblDetao tbody").append(row);
  }

  function addRowPol(cta, ctaNom, debe, haber){
    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='btnDelp'><i class='fas fa-trash-alt'></i></button>"
                    +"<button type='button' class='btn btn-primary btn-sm btn-actions' id='btnEditp' data-toggle='modal' data-target='#modalPol'><i class='fas fa-edit'></i></button>"
                  +"</div>"
                +"</td>"
                +"<td id='dataCta'>"+cta+"</td>"
                +"<td id='dataCtaNom'>"+ctaNom+"</td>"
                +"<td id='dataDebe' class='text-right'>"+debe+"</td>"
                +"<td id='dataHaber' class='text-right'>"+haber+"</td>"
                +"</tr>";
    $("#tblPol tbody").append(row);
  }

  function addRowExistList(lotelis,fvencelis,existlis,l){
    const row = "<tr>"
                  +"<td id='datalotelis' class='text-left'>"+lotelis+"</td>"
                  +"<td id='datafvencelis' class='text-center'>"+fvencelis+"</td>"
                  +"<td id='dataexistlis' class='text-right'>"+existlis+"</td>"
                  +"<td class='text-center'>"
                    +"<div class='custom-control custom-checkbox'>"
                    +"<input type='checkbox' class='custom-control-input' id='dataCheck"+l+"' name='cblis'>"
                    +"<label class='custom-control-label mt-0' for='dataCheck"+l+"'></label>"
                    +"</div>"
                  +"</td>"
                +"</tr>";
    $("#tblExistList 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(2));
  }
/*
  function consultarDoc(){
    if (restriccion(true)) {return};
    
    if (!isNullPer(numNum.value)) {
      const parametros = new FormData();
      parametros.append("action", "consultardoc");

      parametros.append("numNum", numNum.value);
      parametros.append("selTdoci", selTdoci.value);
      parametros.append("TdociRelatpol", $('#selTdoci').find('option:selected').data('relatpol'));

      //txtNext.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);
          tblDetaoAnt = JSON.stringify(jsonJS.doce_det);
          tblPolAnt = JSON.stringify(jsonJS.poli_det);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            limpiar();
            tblClear("tblDetao");
            sumDetao();
            tblClear("tblPol");
            sumPol();
  
            if (isNullPer(jsonJS.doctose)) {
              Bodegaant="";
              Bodegaant2="";
              dtFecant=dateToday();
              nuevo=true;
            } else {
              dtFec.value = jsonJS.doctose.de_fec;
              dtFecant = jsonJS.doctose.de_fec;
              selBodega.value = jsonJS.doctose.de_bodsal;
              Bodegaant=jsonJS.doctose.de_bodsal;
              selBodega2.value = jsonJS.doctose.de_bodent;
              Bodegaant2=jsonJS.doctose.de_bodent;
              txtCon.value = jsonJS.doctose.de_obs;
              flag='S';
              jsonJS.doce_det.forEach(function(i){
                 addRowDetao(i.ded_cod, i.ded_desc, i.ded_med, i.ded_unimed, i.ded_lote, i.ded_fvence, i.ded_cant, i.ded_cosu, i.ded_cost, i.flag);
              });  
              sumDetao();
              jsonJS.poli_det.forEach(function(i){
                addRowPol(i.pold_cta, i.pold_ctan, i.pold_debe, i.pold_haber);
              });
              sumPol();
              nuevo = false;
            }
          }
        }
      });
    }      
  }  */


  function guardarDoc(imprimir = false){
    if (restriccion()) {return};

    //console.log($('#selTdoci').find('option:selected').data('afecos'));

    const pIva = <?php echo $_SESSION["pIva"]; ?>;

    var totall = $("#dataTotTot").text();

    colDetao = ["acciones","codd", "descd", "unimed", "medid", "loted", "fvenced", "cantd", "cosud", "numtot", "flag"];

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

    const parametros = new FormData();

    parametros.append("action", "guardar");

    parametros.append("nuevo", nuevo);
    parametros.append("numNum", 0);
    parametros.append("selTdoci", selTdoci.value);
    parametros.append("TdociNom", $("#selTdoci option:selected").text());
    parametros.append("TdociPartsn", $('#selTdoci').find('option:selected').data('partsn'));
    parametros.append("TdociRelatpol", $('#selTdoci').find('option:selected').data('relatpol'));
    parametros.append("TdociInveini", $('#selTdoci').find('option:selected').data('inveini'));
    parametros.append("TdociAfecos", $('#selTdoci').find('option:selected').data('afecos'));
    parametros.append("dtFec", dtFec.value);
    parametros.append("dtFecant", dtFecant);
    parametros.append("selBodega", selBodega.value);
    parametros.append("BodegaNom", $("#selBodega option:selected").text());
    parametros.append("selBodega2", selBodega2.value);
    parametros.append("BodegaNom2", $("#selBodega2 option:selected").text());
    parametros.append("Bodegaant", Bodegaant);
    parametros.append("Bodegaant2", Bodegaant2);
    parametros.append("txtCon", txtCon.value);
    parametros.append("sumtot", totall);
    parametros.append("piva", pIva);
    parametros.append("tblDetao", tblToJson(colDetao, "tblDetao", 0));
    parametros.append("tblDetaoAnt", tblDetaoAnt);
    parametros.append("tblPol", tblToJson(colPol, "tblPol", 0));
    parametros.append("tblPolAnt", tblPolAnt);

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

        if(jsonJS.error==true){
          alError(jsonJS);
        } else {
          var snhacer = true;
          var numdoc = jsonJS.numdoc;
          if (jsonJS.probpol1 != "X") {
            alError({"msg":{"type":"error","title":"PROBLEMA EN CUENTAS","text":"Alguna de las cuentas no esta asignada correctamente, verifique.", "ok":"Aceptar"}});
              var snhacer = false;
                     return true;
          } 
          if (snhacer) {
            if (imprimir) {
              imprimirDoc(numdoc,totall);
            }
            limpiar();
            tblClear("tblDetao");
            sumDetao();
            tblClear("tblPol");
            sumPol();
            alSuccess(jsonJS);
          }  
        }

        }), 0;
      }
    });
  }

  function imprimirDoc(numdoc,totall){

    const getTdoci = "?selTdoci="+selTdoci.value;
    const getnumdoc = "&numdoc="+numdoc;
    const getTdociNom = "&TdociNom="+$('#selTdoci').find('option:selected').text();
    const getBodegaNom = "&BodegaNom="+$('#selBodega').find('option:selected').text();
    const getBodegaNom2 = "&BodegaNom2="+$('#selBodega2').find('option:selected').text();

    var url = window.location.origin+window.location.pathname+"print.php"+getTdoci+getnumdoc+getTdociNom+getBodegaNom+getBodegaNom2;

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



  function limpiarModalDetao(){
    txtCoddm.value = "";
    txtDescdm.value = "";
    txtMedidm.value = "";
    dtFvencem.value= '<?php echo $dtFec; ?>';
    numCantdm.value = "";
    numCosudm.value = "";
    numTotdm.value = "";
  }

  function limpiar(todo = false){
    dtFec.value= '<?php echo $dtFec; ?>';
    txtCon.value = "";
    txtCodd.value = "";
    txtDescd.value = "";
    txtMedid.value = "";
    dtFvenced.value= '<?php echo $dtFec; ?>';
    numCantd.value = (0).toFixed(2);
    numCosud.value = (0).toFixed(5);
    numTotd.value = (0).toFixed(5);
    txtDescd.disabled = false;
  }

  function limpiarDetao(){
    txtDescd.value = "";
    txtMedid.value = "";
    dtFvenced.value= '<?php echo $dtFec; ?>';
    numCantd.value = (0).toFixed(2);
    numCosud.value = (0).toFixed(5);
    numTotd.value = (0).toFixed(5);
  }


  function sumDetao(){
    $("#tblDetao #dataTotCant").text(tblSumCol("tblDetao", "dataCantd").toFixed(2));
    $("#tblDetao #dataTotTot").text(tblSumCol("tblDetao", "dataTotd").toFixed(5));
  }

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

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

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


  $(document).ready(function() {
    $(this).find('select:visible:first').focus();
    //document.thisform.dtFec.value = '<?php echo $dtFec; ?>';
    //document.thisform.dtFvalida.value = '<?php echo $dtFec; ?>';
    //selTdoci.value="0190";
//    selBodega.value="0020";
//    selBodega2.value="0030";
    dtFec.value = dateToday();
    imgArtic.src = imgPhoto;
    txtCodd.value = "";
    txtDescd.value = "";
    txtMedid.value = "";
    dtFvenced.value= '<?php echo $dtFec; ?>';
    numCantd.value = (0).toFixed(2);
    numCosud.value = (0).toFixed(5);
    numTotd.value = (0).toFixed(5);
    txtDescd.disabled = false;

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

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

    // FOCUS NUMERO DE CHEQUE
    $("#selSerieo").focus(function() {
      limpiar();
    });


    // VALID CODIGO
    $("#txtCodd")
    .focus(function() {
      if (isNullPer(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;
      }
      inputArtic = $(this).attr('id');
      imgArtic.src = imgPhoto;
      txtCodd.value="";
      limpiarDetao();
      if (restriccionCamposVacios()) {return};

    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-1-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      const parametros = new FormData();
      parametros.append("action", "consultarArtic");
      parametros.append("txtCodd", txtCodd.value);
      parametros.append("selBod", selBodega.value);

      dtFvenced.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);
            nuevoArtic = true;
            unimed="";
            ctacos="XXX";            
            ctainv="XXX";            
          } else {
            if (jsonJS.artic === null) {
              nuevoArtic = true;
              txtCodd.focus();
              txtDescd.value = "";
              txtMedid.value="XXXX";
              unimed="XXX";
              imgArtic.src = imgPhoto;
              ctacos="XXX";
              ctainv="XXX";
              costouni=0;
              alWarning({"msg":{"title":"No Existe","text":"Este Articulo no existe, debe registrarlo"}});
               return true;
            } else {
              txtCodd.value = jsonJS.artic.art_cod;
              txtDescd.value = jsonJS.artic.art_desc;
              txtMedid.value = jsonJS.artic.um_nom;
              unimed = jsonJS.artic.art_medi;
              ctacos = jsonJS.artic.art_ctacos;
              ctainv = jsonJS.artic.art_ctainv;
              costouni = jsonJS.artic.art_cosp;
              if (selBodega.value=="0040"){
                 numCosud.value = jsonJS.artic.art_pre2;
              } else {
                 numCosud.value = jsonJS.artic.art_pre1;
              }
              if ($('#selTdoci').find('option:selected').data('afecos') != 'S') {
//                numCosud.value = jsonJS.artic.art_cosp;
              }
              if (!isNullPer(jsonJS.exiart_peps)) {
                dtFvenced.value=jsonJS.exiart_peps.ea_fvence;
              }   
              imgExist(imgArtic, jsonJS.imgArtic, imgPhoto);

              if (jsonJS.artic.art_serv == 1) {
                txtDescd.disabled = false;
              } else {
                txtDescd.disabled = true;
              }
              nuevoArtic = false;
            }
          }
        }
      });
    });

    // VALID FECHA VENCIMIENTO
    $("#dtFvenced")
    .focus(function() {
      inputFvence = $(this).attr('id');
      if (restriccionCamposVacios()) {return};
    })
    .keydown(function(e){
      if(ctrlBus(e)) { 
        document.getElementById("btnExistpeps").click(); 
      }
    });

    // FOCUS TIPO DOCUMENTO
    $("#selTdoci").focus(function (){
      tblClear("tblDetao");
      tblClear("tblPol");
      limpiar();
    });

    // FOCUS NUMERO
//    $("#numNum").focus(function() {
//      numNum.value="";
//      tblClear("tblDetao");
//      limpiar();
//    });

/*
    // VALID NUMERO
    $("#numNum")
    .blur(function (){
      consultarDoc();
    })
    .focus(function (){
      tblClear("tblDetao");
      sumDetao();

      const parametros = new FormData();
      parametros.append("action", "consultarCorr");
      parametros.append("selTdoci", selTdoci.value);
      
      tblDetaoAnt = "";
      limpiar();

      $.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);
          numNum.value = jsonJS.corrtdoci.ctdi_corr;
        } 
      });
    });
*/

    // FOCUS FECHA
    $("#txtDescd").focus(function (){
      if (restriccionCamposVacios()) {return};
      if (isNullPer(txtCodd.value)) {
        txtCodd.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Codigo del Articulo o Si es Servicio ingrese SERV en mayuscula"}});
        return true;
        return true;
      }
    });

    // VALID Cantidad y Costo unitario detalle
    // VALID CANTIDAD A REBAJAR
    $("#numCantd")
    .change(function (){
      numTotd.value = round(numCantd.value*numCosud.value,5).toFixed(5);
      txtThis = this;
      const parametros = new FormData();
      parametros.append("action", "consultarExistpeps");
      parametros.append("txtCodd", txtCodd.value);
      parametros.append("selBodega", selBodega.value);
      parametros.append("dtFvenced", dtFvenced.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_peps === null) {
              loted="";
              numCantd.value="";
              numCantd.focus();
              alWarning({"msg":{"title":"No tiene Existencia","text":"Este Articulo no tiene existencia registrada"}});
               return true;
            } else {
              revisacant();
              sumcant+=Number(numCantd.value);
              existAct=Number(jsonJS.exiart_peps.ea_exist)+sumCantDetAnt(txtCodd.value,dtFvenced);
              //numCosud.value=Number(jsonJS.exiart_peps.ea_cosu);
              numTotd.value = round(numCantd.value*numCosud.value,5).toFixed(5);
              loted=jsonJS.exiart_peps.ea_lote;
              if (sumcant > existAct) {
                numCantd.value="";
                numCantd.focus();
                alWarning({"msg":{"title":"No tiene Suficiente Existencia","text":"La existencia en esta bodega y fecha de vencimiento no alcanza para hacer esta salida, solo tiene:   "+existAct.toFixed(2)}});
                  return true;
              }
            }
          }
        }
      });
    });

    // VALID CANTIDAD A REBAJAR
    $("#numCantdm")
    .focus(function() {
      Cantdmant=numCantdm.value;
    })
    .change(function (){
      numTotdm.value = round(numCantdm.value*numCosudm.value,5).toFixed(5);
      txtThis = this;
      const parametros = new FormData();
      parametros.append("action", "consultarExistpeps");
      parametros.append("txtCodd", txtCoddm.value);
      parametros.append("selBodega", selBodega.value);
      parametros.append("dtFvenced", dtFvencem.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_peps === null) {
              loted="";
              numCantdm.value="";
              numCantdm.focus();
              alWarning({"msg":{"title":"No tiene Existencia","text":"Este Articulo no tiene existencia registrada con esta fecha de vencimiento"}});
               return true;
            } else {
              revisacantm();
              sumcant+=Number(numCantdm.value)-cantAnt;
              existAct=Number(jsonJS.exiart_peps.ea_exist)+sumCantDetAnt(txtCodd.value,dtFvenced);
              //numCosud.value=Number(jsonJS.exiart_peps.ea_cosu);
              numTotd.value = round(numCantdm.value*numCosud.value,5).toFixed(5);
              loted=jsonJS.exiart_peps.ea_lote;
              if (sumcant > existAct) {
                numCantdm.value=Cantdmant;
                numCantdm.focus();
                alWarning({"msg":{"title":"No tiene Suficiente Existencia","text":"La existencia en esta bodega y fecha de vencimiento no alcanza para hacer esta salida, solo tiene:   "+existAct.toFixed(2)}});
                  return true;
              }
            }
          }
        }
      });
    });


    // FOCUS FECHA
    $("#dtFec").focus(function (){
      if (restriccionCamposVacios()) {return};
    });

    // Valida Cantidad
    $("#numCosud")
    .focus(function (){
      if (numCantd.value == 0) {
        numCantd.focus();
        alWarning({"msg":{"title":"NO PUEDE DEJAR A CERO ESTE CAMPO","text":"Debe ingresar alguna cantidad."}});
        return;
      }
    });

    // Valida Cantidad
    $("#numCosudm")
    .focus(function (){
      if (numCantdm.value == 0) {
        numCantdm.focus();
        alWarning({"msg":{"title":"NO PUEDE DEJAR A CERO ESTE CAMPO","text":"Debe ingresar alguna cantidad."}});
        return;
      }
    });

    // FOCUS ORDEN DE COMPRA
    $("#numOrdenc").change(function (){
      consultarOrden();
    });

    // VALID CODIGO MODAL
    $("#txtCoddm")
    .focus(function() {
      inputArtic = $(this).attr('id');
      imgArtic.src = imgPhoto;
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-01-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      const parametros = new FormData();
      parametros.append("action", "consultarArtic");
      parametros.append("txtCodd", txtCoddm.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);
            nuevoArtic = true;
          } else {
            if (jsonJS.artic === null) {
              nuevoArtic = true;
              txtCoddm.focus();
              txtDescdm.value = "";
              txtMedidm.value="XXXX";
              imgArtic.src = imgPhoto;
              alWarning({"msg":{"title":"No Existe","text":"Este Articulo no existe, debe registrarlo"}});
               return true;
            } else {
              txtCoddm.value = jsonJS.artic.art_cod;
              txtDescdm.value = jsonJS.artic.art_desc;
              txtMedidm.value = jsonJS.artic.um_nom;
              imgExist(imgArtic, jsonJS.imgArtic, imgPhoto);
              nuevoArtic = false;
            }
          }
        }
      });
    });

    // FOCUS DESCRIPCION MODAL
    $("#txtDescdm").focus(function (){
      if (isNullPer(txtCoddm.value)) {
        txtCoddm.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Codigo del Articulo o Si es Servicio ingrese SERV en mayuscula"}});
        return true;
        return true;
      }
    });

    $("#btnExistpeps").click(function (){
      if (isNullPer(txtCodd.value)) {
        txtCodd.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CODIGO DEL ARTICULO"}});
        return true;
      }

      txtDcodlis.value = txtCodd.value;
      txtDdesclis.value =  txtDescd.value;
      tblClear("tblExistList");

      const parametros = new FormData();
      parametros.append("action", "consultarLisExispeps");
      parametros.append("txtCodd", txtCodd.value);
      parametros.append("selBodega", selBodega.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.exiart_peps.forEach(function(i,index){
                addRowExistList(i.ea_lote, i.ea_fvence, i.ea_exist, index);
            });
            sumCajaLis();
            $('#modalLisExist').modal('toggle');
          }
        }
      });
    });

    $("#btnContiLisExist").click(function (){
      var fvencel = "";

      $("#tblExistList").find('tbody tr').each(function (i,index) {

        fvencel = $(this).find("td:eq(1)").text();

        if ($(this).find('td input[name="cblis"]').is(":checked")){
          dtFvenced.value=fvencel;
        }

      });
      $('#modalLisExist').modal('toggle');
      numCantd.value="";
      numCantd.focus();
    });

/*
    // CLICK BORRAR
    $("#btnBorrar").click(function (){
      if (isNullPer(numNum.value)  || numNum.value == 0) {
        numNum.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE DOCUMENTO"}});
        return true;
      }
      const numDoc = numNum.value;
      const seriedoc = selTdoci.value;

      //numNum.focus();

      const fnT = function(){

        const parametros = new FormData();
        parametros.append("action", "borrar");
        parametros.append("selTdoci", selTdoci.value);
        parametros.append("TdociNom", $('#selTdoci').find('option:selected').text());
        parametros.append("TdociRelatpol", $('#selTdoci').find('option:selected').data('relatpol'));
        parametros.append("Bodegaant", Bodegaant);
        parametros.append("Bodegaant2", Bodegaant2);
        parametros.append("numNum", numDoc);
        parametros.append("dtFec", dtFec.value);
        parametros.append("dtFecant", dtFecant);
        parametros.append("tblDetaoAnt", tblDetaoAnt);
        parametros.append("tblPolAnt", tblPolAnt);

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

            if(jsonJS.error==true){
              alError(jsonJS);
            } else {
              numNum.value = "";
              limpiar();
              tblClear("tblDetao");
              sumDetao();
              tblClear("tblPol");
              sumPol();
              $("#btnBorrar").focus(function (){
                numNum.focus();
              });
              alSuccess(jsonJS);
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });


    // CLICK ANULAR
    $("#btnAnular").click(function (){
      if (isNullPer(numNum.value)  || numNum.value == 0) {
        numNum.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE DOCUMENTO"}});
        return true;
      }

      const numDoc = numNum.value;
      const serieodoc = selTdoci.value;

      //numNum.focus();

      const fnT = function(){

        const parametros = new FormData();
        parametros.append("action", "anular");
        parametros.append("selTdoci", selTdoci.value);
        parametros.append("TdociNom", $('#selTdoci').find('option:selected').text());
        parametros.append("TdociRelatpol", $('#selTdoci').find('option:selected').data('relatpol'));
        parametros.append("Bodegaant", Bodegaant);
        parametros.append("Bodegaant2", Bodegaant2);
        parametros.append("numNum", numDoc);
        parametros.append("dtFec", dtFec.value);
        parametros.append("dtFecant", dtFecant);
        parametros.append("tblDetaoAnt", tblDetaoAnt);
        parametros.append("tblPolAnt", tblPolAnt);

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

            if(jsonJS.error==true){
              alError(jsonJS);
            } else {
              numNum.value = "";
              limpiar();
              tblClear("tblDetao");
              sumDetao();
              tblClear("tblPol");
              sumPol();
              $("#btnAnular").focus(function (){
                numNum.focus();
              });
              alSuccess(jsonJS);
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });
*/

    // CLICK GUARDAR
    $("#btnGuardar").click(function (){
      if (isNullPer(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;
      }
      restriccion();
      if ($("#tblDetao tbody").children().length == 0) {
        alWarning({"msg":{"title":"NO HA REGISTRADO DETALLE","text":"Primero debe registrar detalle para el documento"}});
        return;
      }
      guardarDoc();
    });

    // CLICK GRABAR E IMPRIMIR
    $("#btnGuardarImprimir").click(function (){
      if (isNullPer(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 ($("#tblDetao tbody").children().length == 0) {
        alWarning({"msg":{"title":"NO HA REGISTRADO DETALLE","text":"Primero debe registrar detalle para el documento"}});
        return;
      }
      guardarDoc(true);
    });
    
    // CLICK AGREGAR Poliza
    $("#btnAgregarp").click(function () {
      if (restriccionModalPol()) {return};
      addRowPol(txtCta.value, txtCtaNom.value, isNullNumber(numDebe.value).toFixed(2), isNullNumber(numHaber.value).toFixed(2));
      limpiarModalPol();
      sumPol();
      $("#btnAddp").focus();
    });
  });

  // CLICK ADD
  $("body").on("click", "#btnAddp", function () {
    if (restriccionCamposVacios()) {return};
    if (restriccionMesCerrado()) {return};
    if ($('#selTdoci').find('option:selected').data('partsn') != "S") { 
      alWarning({"msg":{"title":"NO NECESITA PARTIDA","text":"A este tipo de documento no debe generarle partida."}});
      return;
    }
    
    inputCtaMov = "txtCta";
    $('#modalPol').modal('toggle');
    $("#pills-000-tab").text("Agregar");
    $("#btnAgregarp").show();
    $("#btnModificarp").hide();
    limpiarModalPol();
  });

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

  // CLICK EDIT
  $("body").on("click", "#btnEditp", function() {
    $('#pills-000-tab').text("Modificar");
    $('#btnAgregarp').hide();
    $('#btnModificarp').show();

    const dataCta = $(this).parents("tr").find("#dataCta");
    const dataCtaNom = $(this).parents("tr").find("#dataCtaNom");
    const dataDebe = $(this).parents("tr").find("#dataDebe");
    const dataHaber = $(this).parents("tr").find("#dataHaber");

    txtCta.value = dataCta.text();
    txtCtaNom.value = dataCtaNom.text();
    numDebe.value = dataDebe.text();
    numHaber.value = dataHaber.text();

    $("body").on("click", "#btnModificarp", function() {
      if (restriccionModalPol()) {return};
      dataCta.text(txtCta.value);
      dataCtaNom.text(txtCtaNom.value);
      dataDebe.text(isNullNumber(numDebe.value).toFixed(2));
      dataHaber.text(isNullNumber(numHaber.value).toFixed(2));
      limpiarModalPol();
      sumPol();
    });
  });

  // CLICK ADD
  $("body").on("click", "#btnAdd", function () {
    if (restriccionCamposVacios()) {return};
    if (isNullPer(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 (txtCodd.value == "") {
      alWarning({"msg":{"title":"CAMPO OBLIGATORIO EN DETALLE","text":"No ha ingresado codigo de la linea en el detalle"}});
      return;
    }
    if (txtDescd.value == "") {
      alWarning({"msg":{"title":"CAMPO OBLIGATORIO EN DETALLE","text":"No ha ingresado Descripcion de la linea en el detalle"}});
      return;
    }
    if (numCantd.value == 0) {
      alWarning({"msg":{"title":"NO PUEDE DEJAR A CERO ESTE CAMPO","text":"Debe ingresar alguna cantidad."}});
      return;
    }

    flag='N';
    addRowDetao(txtCodd.value, txtDescd.value, unimed, txtMedid.value, loted, dtFvenced.value, isNullNumber(numCantd.value).toFixed(2), isNullNumber(numCosud.value).toFixed(5), isNullNumber(numTotd.value).toFixed(5), flag);
    sumDetao();
    txtCodd.value="";
    txtCodd.focus();
  });

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

  // CLICK EDIT
  $("body").on("click", "#btnEdit", function() {
    $('#pills-00-tab').text("Modificar");
    $('#btnAgregar').hide();
    $('#btnModificar').show();

    const dataCodd = $(this).parents("tr").find("#dataCodd");
    const dataDescd = $(this).parents("tr").find("#dataDescd");
    const dataMedid = $(this).parents("tr").find("#dataMedid");
    const dataFvenced = $(this).parents("tr").find("#dataFvenced");
    const dataCantd = $(this).parents("tr").find("#dataCantd");
    const dataCosud = $(this).parents("tr").find("#dataCosud");
    const dataTotd = $(this).parents("tr").find("#dataTotd");
    const dataFlag = $(this).parents("tr").find("#dataFlag");

    cantAnt = Number(dataCantd.text());
    txtCoddm.value = dataCodd.text();
    txtDescdm.value = dataDescd.text();
    txtMedidm.value = dataMedid.text();
    dtFvencem.value = dataFvenced.text();
    numCantdm.value = dataCantd.text();
    numCosudm.value = dataCosud.text();
    numTotdm.value = dataTotd.text();
    Cantdmant = Number(dataCantd.text());
    flag = dataFlag.text();

    $("body").on("click", "#btnModificar", function() {
      if (restriccionModal()) {return};
      dataCodd.text(txtCoddm.value);
      dataDescd.text(txtDescdm.value);
      dataMedid.text(txtMedidm.value);
      dataFvenced.text(dtFvencem.value);
      dataCantd.text(isNullNumber(numCantdm.value).toFixed(2));
      dataCosud.text(isNullNumber(numCosudm.value).toFixed(5));
      dataTotd.text(isNullNumber(numTotdm.value).toFixed(5));

      limpiarModalDetao();
      sumDetao();
    });
  });

  // MODALDetao HIDDEN
  $('#modalDetao').on('hidden.bs.modal', function (e) {
    cantAnt=0;
    $("body").off("click", "#btnModificar");
  });

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

  // CLICK btnPartida
    $("#btnPartida").click(function (){
      if (restriccionCamposVacios()) {return};
      if (restriccionMesCerrado()) {return};
      if ($("#tblPol tbody").children().length != 0) {
        alWarning({"msg":{"title":"Ya existe partida","text":"La partida de este documento ya existe"}});
        return;
      }
      if ($('#selTdoci').find('option:selected').data('partsn') != "S") { 
        alWarning({"msg":{"title":"NO NECESITA PARTIDA","text":"A este tipo de documento no debe generarle partida."}});
        return;
      }

      const pIva = <?php echo $_SESSION["pIva"]; ?>;

      colDetao = ["acciones","codd", "descd", "unimed", "medid", "loted", "fvenced", "cantd", "cosud", "numtot", "bonid", "cbexentod", "ctacos", "ctainv"];

      //colDocp = ["acciones", "codp", "clienp", "ctap", "tipo", "serie", "numero", "fecha", "tipocam", "concep", "saldo", "abono", "check"];

      const parametros = new FormData();
      parametros.append("action", "generarPartida");
      parametros.append("tblDetao", tblToJson(colDetao, "tblDetao", 0));
      parametros.append("ctainv", $('#selBodega').find('option:selected').data('ctainv'));
      parametros.append("ctainvB2", $('#selBodega2').find('option:selected').data('ctainv'));
      parametros.append("TdociInveini", $('#selTdoci').find('option:selected').data('inveini'));
      parametros.append("piva", pIva);


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

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            // Cuenta Inventario
            jsonJS.ctaInv.forEach(function(i){
              addRowPol(i.cta, i.cta_nom, Number(i.cta_debe).toFixed(2), "0.00");
            });
            // Cuenta Costos
            jsonJS.ctaCos.forEach(function(i){
              addRowPol(i.cta, i.cta_nom, "0.00", Number(i.cta_haber).toFixed(2));
            });
            sumPol();
            alClose();
          }
        }
      });
    });


  // 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") ? dtFvenced.focus() : 0;
        (relatedTarget == "#pills-01") ? txtCoddm.focus() : 0;
      }
      //$(target+' input:visible:first').focus();
    }
  });

</script>
