<?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'];

# QUERYS
$sCiemes = "SELECT ciem_stat FROM ciemes WHERE ciem_emp='$empCod' AND ciem_ano=$nAnio AND ciem_mes=$nMes";
$sTipodoci = "SELECT * FROM tipodoci where td_prorratsn='S'";
$sMeses = "SELECT * FROM meses";

# EJECUCION DE QUERYS
$db = new dbExec();
$mesCerrado = ($db->sFetchAssoc($sCiemes)["ciem_stat"] == "C") ? "true" : "false";
$select["tipodoci"] = $db->query($sTipodoci);
$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>
              </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>
                      <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" disabled>
                        </div>
                        <div class="col-6 col-sm-3">
                          <label class="font-size-sm text-success" for="numCosuqm">Unitario/Fob Q.</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-6" id="numCosuqm" disabled>
                        </div>
                        <div class="col-6 col-sm-3">
                          <label class="font-size-sm text-success" for="numTotqm">Total/Fob Q</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-6" id="numTotqm" disabled>
                        </div>
                        <div class="col-6 col-sm-3 col-md-2">
                          <label class="font-size-sm text-success" for="numDistribm">% Distribucion</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-6" id="numDistribm" disabled>
                        </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="numGastosm">Otros Gastos</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numGastosm" disabled>
                        </div>
                        <div class="col-6 col-sm-3">
                          <label class="font-size-sm text-success" for="numDaim">Dai Q.</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-6" id="numDaim">
                        </div>
                        <div class="col-6 col-sm-3">
                          <label class="font-size-sm text-success" for="numTotalm">Total Q</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-6" id="numTotalm" disabled>
                        </div>
                        <div class="col-6 col-sm-3 col-md-2">
                          <label class="font-size-sm text-success" for="numCosunitm">Costo/Unit Q.</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-6" id="numCosunitm" 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 GASTOS EN DOLARES -->
      <div class="modal fade" id="modalGastos1" tabindex="-1" role="dialog" aria-labelledby="modalGastos1Title" 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-000-tab" data-toggle="pill" href="#pills-000" role="tab" aria-controls="pills-000" aria-selected="true"></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-7">
                          <label class="font-size-xl text-success" for="txtDescg1">Descripción</label>
                          <input type="text" class="form-control form-control-xl form-control-as" id="txtDescg1" maxlength="40" disabled>
                        </div>
                      </div>
                      <div class="form-row align-items-end">
                        <div class="col-4">
                          <label class="font-size-xl text-success" for="numValg1">Valor $</label>
                          <input type="number" class="form-control form-control-xl form-control-as dec-2" id="numValg1">
                        </div>
                      </div>

                    </div>

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

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

                </div>
              </div>

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

      <!-- MODAL GASTOS EN QUETZALES -->
      <div class="modal fade" id="modalGastos2" tabindex="-1" role="dialog" aria-labelledby="modalGastos2Title" 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-0000-tab" data-toggle="pill" href="#pills-0000" role="tab" aria-controls="pills-0000" aria-selected="true"></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-0000" role="tabpanel" aria-labelledby="pills-0000-tab">
                  
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">

                      <div class="form-row">
                        <div class="col-7">
                          <label class="font-size-sm text-success" for="txtDescg2">Descripción</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtDescg2" maxlength="40" disabled>
                        </div>
                      </div>
                      <div class="form-row align-items-end">
                        <div class="col-4">
                          <label class="font-size-xl text-success" for="numValg2">Valor $</label>
                          <input type="number" class="form-control form-control-xl form-control-as dec-2" id="numValg2">
                        </div>
                      </div>

                    </div>

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

                    <button type="button" class="btn btn-success btn-block" id="btnModificarg2">Modificar</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">Documentos Pendientes Prorrateo</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-end">
                          <div class="col-sm-3">
                            <label class="font-size-sm" for="numNum">Número de Prorrateo</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numNum" placeholder="0">
                          </div>
                          <div class="col-sm-6">
                            <label class="font-size-sm"></label>
                          </div>
                          <div class="col-sm-2">
                            <label class="font-size-xl" for="txtStat"></label>
                            <input type="text" class="form-control form-control-xl form-control-as" id="txtStat" placeholder="" disabled>
                          </div>
                        </div>
                        <div class="form-row align-items-end">
                          <div class="col-sm-3">
                            <label class="font-size-sm" for="dtFec">Fecha Prorrateo</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFec" placeholder="">
                          </div>
                          <div class="col-sm-3">
                            <label class="font-size-sm" for="selTdoci">Tipo de Documento</label>
                            <select class="form-control form-control-sm form-control-as" name="selTdoci" id="selTdoci">
                              <?php
                                while ($rec = $db->fetchAssoc($select['tipodoci'])) {
                                  echo  '<option value="'.$rec['td_cod'].'">'.utf8_encode($rec['td_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-3">
                            <label class="font-size-sm" for="numImpor">Numero Documento</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numImpor" maxlength="20">
                          </div>
                          <div class="col-3">
                            <label class="font-size-sm" for="numTcam">Tasa de Cambio</label>
                            <input type="number" class="form-control form-control-sm form-control-as dec-6" id="numTcam">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-md-5">
                            <div class="form-row">
                               <div class="col-12 mt-2">
                                <button type="button" class="btn btn-warning" id="btnCargadet">
                                  <i class="fas fa-plus-circle"></i> CARGAR DETALLE DEL DOCUMENTO
                                </button>
                              </div>
                            </div>
                          </div>
                        </div>

                        <div class="form-row">
                        </div>
                      </div>

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

                      <div class="form-group">
                        <div class="form-row">
                        </div>
                        <div class="form-row">
                          <div class="col-6">
                            <label class="font-size-xl">DATOS PARA PRORRATEO</label>
                          </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-xs" 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="200">DESCRIPCIÓN</th>
                                    <th scope="col" class="text-center">CANTIDAD</th>
                                    <th scope="col" class="text-center" width="70">UNIT/FOB Q</th>
                                    <th scope="col" class="text-center" width="90">TOTAL FOB Q.</th>
                                    <th scope="col" class="text-center" width="60">% DISTRIB</th>
                                    <th scope="col" class="text-center" width="90">OTROS/GASTOS</th>
                                    <th scope="col" class="text-center" width="80">DAI</th>
                                    <th scope="col" class="text-center" width="90">TOTAL Q</th>
                                    <th scope="col" class="text-center" width="90">COSTO/UNIT. Q</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="dataTotCant" class="text-right">0.00</th>
                                  <th scope="col"></th>
                                  <th scope="col" id="dataTotTFob" class="text-right">0.000000</th>
                                  <th scope="col" id="dataTotTDis" class="text-right">0.000000</th>
                                  <th scope="col" id="dataTotTGas" class="text-right">0.000000</th>
                                  <th scope="col" id="dataTotTDai" class="text-right">0.000000</th>
                                  <th scope="col" id="dataTotTTot" class="text-right">0.00000</th>
                                </tfoot>
                              </table>
                            </div>
                          </div>
                        </div>
                      </div>

                      <div class="form-group">
                        <div class="form-row">
                        </div>
                        <div class="form-row">
                          <div class="col-6">
                            <label class="font-size-xl text-success">GASTOS ADICIONALES EN DOLARES</label>
                          </div>
                          <div class="col-6">
                            <label class="font-size-xl text-info">GASTOS ADICIONALES EN QUETZALES</label>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-md-6">
                            <div class="table-responsive">
                              <table class="table table-hover table-bordered table-dark table-sm" id="tblDetaG1">
                                <thead>
                                  <tr>
                                    <th scope="col" class="text-center ignore" width="50">ACCIONES</th>
                                    <th scope="col" class="text-center" width="150">DESCRIPCIÓN</th>
                                    <th scope="col" class="text-center" width="70">VALOR $</th>
                                  </tr>
                                </thead>
                                <tbody>
                                </tbody>
                                <tfoot>
                                  <th scope="col" class="ignore"></th>
                                  <th scope="col" class="text-right">Totales</th>
                                  <th scope="col" id="dataTotGdolar" class="text-right">0.00</th>
                                </tfoot>
                              </table>
                            </div>
                          </div>
                          <div class="col-md-6">
                            <div class="table-responsive">
                              <table class="table table-hover table-bordered table-dark table-sm" id="tblDetaG2">
                                <thead>
                                  <tr>
                                    <th scope="col" class="text-center ignore" width="50">ACCIONES</th>
                                    <th scope="col" class="text-center" width="150">DESCRIPCIÓN</th>
                                    <th scope="col" class="text-center" width="70">VALOR Q</th>
                                  </tr>
                                </thead>
                                <tbody>
                                </tbody>
                                <tfoot>
                                  <th scope="col" class="ignore"></th>
                                  <th scope="col" class="text-right">Totales</th>
                                  <th scope="col" id="dataTotGQuet" class="text-right">0.00</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="btnProcesar" type="button">Procesar</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>

                      </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('../busDocProrrat/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 inputDocimp = "numImp";
  var tblDetaoAnt;
  var tblPolAnt;
  var btnAddEdit = "00";
  var btnAddEditg1 = "000";
  var btnAddEditg2 = "0000";
  var inputArtic = "txtCodd";
  var unimed = "XXX";
  var ctaInc = false;
  
  const numNum = document.thisform.numNum;
  const dtFec = document.thisform.dtFec;
  const selTdoci = document.thisform.selTdoci;
  const numImpor = document.thisform.numImpor;
  const numTcam = document.thisform.numTcam;
  const txtStat = document.thisform.txtStat;

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


  function restriccion(consultar = false){
    if (!consultar) {
      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()) {
        alWarning({"msg":{"title":"Valores Incorrectos","text":"La partida no cuadra, verifique los valores"}});
        return true;
      }
      // PARA VER SI LA PARTIDA ESTÁ VACÍA
      if ($("#tblPol tbody").children().length == 0) {
        alWarning({"msg":{"title":"Partida Vacía","text":"Es necesario Generar Partida"}});
        return true;
      }
      // RECORRER PARTIDA PARA BUSCAR UNA CUENTA 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 }
      });
    }
    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() {
    return false;
  }

  function condicionesobligatorias() {
    if (isNullPer(numTcam.value)) {
      numTcam.value = (1).toFixed(5);
      numTcam.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar algun Valor en la Tasa de Cambio"}});
      return true;
    }
  }


  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 restriccionModalPol() {
    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 addRowDetao(codd, descd, cant, cosuq, totq, distrib, gastos, dai, total, cosunit, ctacos, ctainv){
    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='dataCantd' class='text-right'>"+cant+"</td>"
                +"<td id='dataCosuq' class='text-right'>"+cosuq+"</td>"
                +"<td id='dataTotq' class='text-right'>"+totq+"</td>"
                +"<td id='dataDistrib' class='text-right'>"+distrib+"</td>"
                +"<td id='dataGastos' class='text-right'>"+gastos+"</td>"
                +"<td id='dataDai' class='text-right'>"+dai+"</td>"
                +"<td id='dataTotal' class='text-right'>"+total+"</td>"
                +"<td id='dataCosunit' class='text-right'>"+cosunit+"</td>"
                +"<td id='dataCtacos' class='d-none'>"+ctacos+"</td>"
                +"<td id='dataCtainv' class='d-none'>"+ctainv+"</td>"

                +"</tr>";
    $("#tblDetao tbody").append(row);
  }

  function addRowDetaG1(codg1, descg1, valg1, tcg1){
    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='btnDelg1'><i class='fas fa-trash-alt'></i></button>"
                    +"<button type='button' class='btn btn-primary btn-sm btn-actions' id='btnEditg1' data-toggle='modal' data-target='#modalGastos1'><i class='fas fa-edit'></i></button>"
                  +"</div>"
                +"</td>"
                +"<td id='dataCodg1' class='d-none'>"+codg1+"</td>"
                +"<td id='dataDescg1'>"+descg1+"</td>"
                +"<td id='dataValg1' class='text-right'>"+valg1+"</td>"
                +"</tr>";
    $("#tblDetaG1 tbody").append(row);
  }

  function addRowDetaG2(codg2, descg2, valg2){
    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='btnDelg2'><i class='fas fa-trash-alt'></i></button>"
                    +"<button type='button' class='btn btn-primary btn-sm btn-actions' id='btnEditg2' data-toggle='modal' data-target='#modalGastos2'><i class='fas fa-edit'></i></button>"
                  +"</div>"
                +"</td>"
                +"<td id='dataCodg2' class='d-none'>"+codg2+"</td>"
                +"<td id='dataDescg2'>"+descg2+"</td>"
                +"<td id='dataValg2' class='text-right'>"+valg2+"</td>"
                +"</tr>";
    $("#tblDetaG2 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 consultarDoc(){
    if (restriccion(true)) {return};
    
    if (!isNullPer(numNum.value)) {
      const parametros = new FormData();
      parametros.append("action", "consultardoc");

      parametros.append("numNum", numNum.value);

      //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.prt_det1);
          tblDetaG1Ant = JSON.stringify(jsonJS.prt_detc);
          tblDetaG2Ant = JSON.stringify(jsonJS.prt_detf);
          tblPolAnt = JSON.stringify(jsonJS.prt_partida);  */

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (isNullPer(jsonJS.prorrat)) {
              bodega="";
              datosbase();
              nuevo=true;
              prtstatus='X';
            } else {
            dtFec.value = jsonJS.prorrat.prt_fec;
            numTcam.value = jsonJS.prorrat.prt_tcam;
            selTdoci.value = jsonJS.prorrat.prt_tipod;
            numImpor.value = jsonJS.prorrat.prt_numd;
            bodega=jsonJS.prorrat.prt_bodega;
            prtstatus=jsonJS.prorrat.prt_stat;
            if (prtstatus=='P') {
              txtStat.value="   YA PROCESADO";
            }
            jsonJS.prt_det1.forEach(function(i){
               addRowDetao(i.pd1_codpro, i.pd1_desc, i.pd1_cant, i.pd1_cosu, i.pd1_tfobq, i.pd1_pord, i.pd1_gastq, i.pd1_dai, i.pd1_vtotal, i.pd1_costuq, i.pd1_ctacos, i.pd1_ctainv);
            });  
            sumDetao();

            jsonJS.prt_detc.forEach(function(i){
               addRowDetaG1(i.prdc_tipog, i.prdc_nomg, i.prdc_vald);
            });  
            sumDetaG1();

            jsonJS.prt_detf.forEach(function(i){
               addRowDetaG2(i.prdf_tipog, i.prdf_nomg, i.prdf_valq);
            });  
            sumDetaG2();

            jsonJS.prt_partida.forEach(function(i){
              addRowPol(i.pold_cta, i.pold_ctan, i.pold_debe, i.pold_haber);
            });
            sumPol();
            nuevo = false;
          }
        }
      }
    });
    }      
  }

  function consultarimpor(){
    if (restriccion(true)) {return};

    if (isNullPer(numImpor.value)  || numImpor.value == 0) {
      numImpor.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el NO. DE DOCUMENTO"}});
      return true;
    }
    
    const parametros = new FormData();
    parametros.append("action", "consultarimpor");
    parametros.append("numNum", numImpor.value);
    parametros.append("selTdoci", selTdoci.value);

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

        if(jsonJS.error == true){
          alError(jsonJS);
        } else {
          if (isNullPer(jsonJS.doctose)) {
            numImpor.value="";
            numImpor.focus();
            bodega="";
            alWarning({"msg":{"title":"DOCUMENTO NO REGISTRADO","text":"Este Documento no ha sido registrado, revise."}});
            return true;
          } else {
            if (jsonJS.doctose.de_prorsn == 'N') {
              numImpor.value="";
              numImpor.focus();
              alWarning({"msg":{"title":"NO ES PARA PRORRATEAR","text":"Este Documento no fue marcado para hacerle prorrateo"}});
              return true;
            }
            if (jsonJS.doctose.de_proya == 'S') {
              nprorrateo=jsonJS.doctose.de_nprorrateo;
              numImpor.value="";
              numImpor.focus();
              alWarning({"msg":{"title":"YA FUE PRORRATEADO","text":"Este Documento ya fue prorrateado con el prorrateo Numero: "+nprorrateo}});
              return true;
            }
            numTcam.value = jsonJS.doctose.de_tcam;
            bodega = jsonJS.doctose.de_bodent;
          }
        }
      }
    });
  }

  function datosbase(){
    if (restriccion(true)) {return};
    
    if (!isNullPer(numNum.value)) {
      const parametros = new FormData();
      parametros.append("action", "datosbase");

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            jsonJS.prorgas1.forEach(function(i){
               addRowDetaG1(i.prg_cod, i.prg_nom, Number(0).toFixed(2));
            });  
            sumDetaG1();

            jsonJS.prorgas2.forEach(function(i){
               addRowDetaG2(i.prg_cod, i.prg_nom, Number(0).toFixed(2));
            });  
            sumDetaG2();
          }
        }
      });
    }      
  }

  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", "cantd", "cosuq", "totq", "distrib", "gastos", "dai", "total", "cosunit", "ctacos", "ctainv"];

    colDetag1 = ["acciones","codg1", "descg1", "valg1"];

    colDetag2 = ["acciones","codg2", "descg2", "valg2"];

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

    const parametros = new FormData();

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

    parametros.append("nuevo", nuevo);
    parametros.append("numNum", numNum.value);
    parametros.append("dtFec", dtFec.value);
    parametros.append("selTdoci", selTdoci.value);
    parametros.append("TdociNom", $("#selTdoci option:selected").text());
    parametros.append("numImpor", numImpor.value);
    parametros.append("numTcam", numTcam.value);
    parametros.append("bodega", bodega);
    parametros.append("tblDetao", tblToJson(colDetao, "tblDetao", 0));
    parametros.append("tblDetaG1", tblToJson(colDetag1, "tblDetaG1", 0));
    parametros.append("tblDetaG2", tblToJson(colDetag2, "tblDetaG2", 0));
    parametros.append("tblPol", tblToJson(colPol, "tblPol", 0));


    numNum.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);
            }
            limpiar();
            tblClear("tblDetao");
            sumDetao();
            tblClear("tblDetaG1");
            sumDetaG1();
            tblClear("tblDetaG2");
            sumDetaG2();
            tblClear("tblPol");
            sumPol();
            alSuccess(jsonJS);
          }  
        }

        }), 0;
      }
    });
  }

  function imprimirDoc(numdoc){

    const getnumdoc = "?numdoc="+numdoc;
    const getTdociNom = "&TdociNom="+$('#selTdoci').find('option:selected').text();

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

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


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

  function limpiarModalDetao(){
    txtCoddm.value = "";
    txtDescdm.value = "";
    numCantdm.value = "";
    numCosuqm.value = "";
    numTotqm.value = "";
    numDistribm.value = "";
    numGastosm.value="";
    numDaim.value="";
    numTotalm.value="";
    numCosunitm.value=""
  }

  function limpiarModalDetag1(){
    txtDescg1.value = "";
    numValg1.value = "";
  }

  function limpiarModalDetag2(){
    txtDescg2.value = "";
    numValg2.value = "";
  }

  function limpiar(todo = false){
    selTdoci.value = "0070";
    numImpor.value = "";
    dtFec.value= '<?php echo $dtFec; ?>';
    numTcam.value = (1).toFixed(6);
    txtStat.value="";
  }

  function limpiarDetao(){
    txtDescd.value = "";
    txtMedid.value = "";
    numCantd.value = (0).toFixed(2);
    numCosud.value = (0).toFixed(5);
    numTotd.value = (0).toFixed(5);
    numBonid.value = (0).toFixed(2);
    cbExentod.checked = 0;
  }

  function sumDetao(){
    $("#tblDetao #dataTotCant").text(tblSumCol("tblDetao", "dataCantd").toFixed(2));
    $("#tblDetao #dataTotTFob").text(tblSumCol("tblDetao", "dataTotq").toFixed(6));
    $("#tblDetao #dataTotTDis").text(tblSumCol("tblDetao", "dataDistrib"));
    $("#tblDetao #dataTotTGas").text(tblSumCol("tblDetao", "dataGastos").toFixed(6));
    $("#tblDetao #dataTotTDai").text(tblSumCol("tblDetao", "dataDai").toFixed(6));
    $("#tblDetao #dataTotTTot").text(tblSumCol("tblDetao", "dataTotal").toFixed(5));
  }

  function sumDetaG1(){
    $("#tblDetaG1 #dataTotGdolar").text(tblSumCol("tblDetaG1", "dataValg1").toFixed(2));
  }

  function sumDetaG2(){
    $("#tblDetaG2 #dataTotGQuet").text(tblSumCol("tblDetaG2", "dataValg2").toFixed(2));
  }

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

  function recalculaCosto(){
    var rgastos1 = 0;
    var rgastos2 = 0;
    var rgastot=0;
    var rgastos=0;
    var rtotal=0;
    var rcosu=0;
    rgastos1 = round(parseFloat($("#tblDetaG1 #dataTotGdolar").text())*numTcam.value,6);
    rgastos2 = parseFloat($("#tblDetaG2 #dataTotGQuet").text());
    rgastot=rgastos1+rgastos2;

    $("#tblDetao").find('tbody tr').each(function () {
      if (parseFloat($(this).find('#dataDistrib').text()) == "0.00000") {
         $(this).find('#dataGastos').text("0.0000");
         $(this).find('#dataTotal').text("0.0000");
         $(this).find('#dataCosunit').text("0.0000");
      } else {
         rgastos=rgastot*parseFloat($(this).find('#dataDistrib').text())/100;
         rtotal=rgastos+parseFloat($(this).find('#dataDai').text())+parseFloat($(this).find('#dataTotq').text());
         rcosu=rtotal/parseFloat($(this).find('#dataCantd').text());
         $(this).find('#dataGastos').text(rgastos.toFixed(6));
         $(this).find('#dataTotal').text(rtotal.toFixed(6));
         $(this).find('#dataCosunit').text(rcosu.toFixed(5));
      } 
    });
//    $("#tblDocp #dataTotSal").text(acum.toFixed(2));
  }

  $(document).ready(function() {
    $(this).find('input:visible:first').focus();
    //document.thisform.dtFec.value = '<?php echo $dtFec; ?>';
    //document.thisform.dtFvalida.value = '<?php echo $dtFec; ?>';
    numTcam.value = 1.000000.toFixed(6);
    dtFec.value = dateToday();

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

    // SHOW MODAL Gastos 1
    $('#modalGastos1').on('shown.bs.modal', function() {
      if (!isMobile()) {
        numValg1.focus();
        //$(this).find('input:visible:first').focus();
      }
    });
    // SHOW MODAL Gastos 2
    $('#modalGastos2').on('shown.bs.modal', function() {
      if (!isMobile()) {
        numValg2.focus();
        //$(this).find('input:visible:first').focus();
      }
    });

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

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

      $.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";
              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;
              nuevoArtic = false;
            }
          }
        }
      });
    });


    // INICIO NUMERO DE PRORRATEO
    $("#numNum").init(function() {
      tblClear("tblDetao");
      tblClear("tblDetaG1");
      tblClear("tblDetaG2");
      tblClear("tblPol");
      limpiar();

      txtThis = this;
      const parametros = new FormData();
      parametros.append("action", "consultarcorr");
      $.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 (isNullPer(jsonJS.prtcorr)) {
              numNum.value=1;
            } else {
              numNum.value = jsonJS.prtcorr.pc_corr;
            }
          }
        }
      });
    });

    // INICIO NUMERO DE PRORRATEO
    $("#numNum").focus(function() {
      tblClear("tblDetao");
      tblClear("tblDetaG1");
      tblClear("tblDetaG2");
      tblClear("tblPol");
      sumDetao();
      sumDetaG1();
      sumDetaG2();
      sumPol();
      limpiar();

      txtThis = this;
      const parametros = new FormData();
      parametros.append("action", "consultarcorr");
      $.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 (isNullPer(jsonJS.prtcorr)) {
              numNum.value=1;
            } else {
              numNum.value = jsonJS.prtcorr.pc_corr;
            }
          }
        }
      });
    });

    // VALID NUMERO
    $("#numNum")
    .blur(function (){
      consultarDoc();
    });


    // FOCUS FECHA
    $("#txtDescd").focus(function (){
      if (restriccionCamposVacios()) {return};
      if (condicionesobligatorias()) {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;
      }
    });

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

    // FOCUS ORDEN DE COMPRA
    $("#numImpor")
    .focus(function(e){
       inputDocimp=$(this).attr('id');
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-1-tab").click(); }
    })
    .change(function (){
      consultarimpor();
    });

    // VALID CODIGO MODAL
    $("#txtCoddm")
    .focus(function() {
      inputArtic = $(this).attr('id');
    })
    .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";
              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;
              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;
      }
    });

    // VALID Cantidad detalle modal
    $("#numCantdm")
    .blur(function (){
      numTotdm.value = round(numCantdm.value*numCosudm.value,5).toFixed(5);
    })

    // VALID Costo Unitario Modal
    $("#numCosudm")
    .blur(function (){
      numTotdm.value = round(numCantdm.value*numCosudm.value,5).toFixed(5);
    })

    // CLICK BORRAR
    $("#btnBorrar").click(function (){
      if (prtstatus=='P'){
         alWarning({"msg":{"title":"YA PROCESADO","text":"Este prorrateo ya fue procesado, no puede borrarlo."}});
         return true;
      }

      const numDoc = numNum.value;

      numNum.focus();

      const fnT = function(){

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

        $.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("tblDetaG1");
              sumDetaG1();
              tblClear("tblDetaG2");
              sumDetaG2();
              tblClear("tblPol");
              sumPol();
              alSuccess(jsonJS);
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });


    // CLICK ANULAR
    $("#btnAnular").click(function (){
      const numDoc = numNum.value;

      numNum.focus();

      const fnT = function(){

        const parametros = new FormData();
        parametros.append("action", "anular");
        parametros.append("numImporant", numImporant);
        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();
              alSuccess(jsonJS);
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

    
    // CLICK DETALLE ORDEN DE COMPRA
    $("#btnCargadet").click(function (){
      if (isNullPer(numImpor.value)) {
        numImpor.focus();
        alWarning({"msg":{"title":"FALTA ASIGNAR DOCUMENTO","text":"No ha seleccionado ningun documento, revise."}});
        return true;
      }
      if ($("#tblDetao tbody").children().length != 0) {
        alWarning({"msg":{"title":"YA TIENE INFORMACION EN EL DETALLE","text":"No puede cargar el documento, porque ya tiene informacion asignada en el detalle."}});
        return true;
      }
      if (!isNullPer(numImpor.value)) {
        const parametros = new FormData();
        parametros.append("action", "consultarimpor");

        parametros.append("numNum", numImpor.value);
        parametros.append("selTdoci", selTdoci.value);

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

            if(jsonJS.error == true){
              alError(jsonJS);
            } else {
            if (isNullPer(jsonJS.doctose)) {
              numImpor.value="";
              numImpor.focus();
              alWarning({"msg":{"title":"DOCUMENTO NO REGISTRADO","text":"Este Documento no ha sido registrado, revise."}});
              return true;
            } else {
              if (jsonJS.doctose.de_prorsn == 'N') {
                numImpor.value="";
                numImpor.focus();
                alWarning({"msg":{"title":"NO ES PARA PRORRATEAR","text":"Este Documento no fue marcado para hacerle prorrateo"}});
                return true;
              }
              if (jsonJS.doctose.de_proya == 'S') {
                numImpor.value="";
                numImpor.focus();
                alWarning({"msg":{"title":"YA FUE PRORRATEADO","text":"Este Documento ya fue prorrateado don el prorrateo Numero:"}});
                return true;
              }
                sumcant=jsonJS.doce_detsum.ded_sumcant;
                jsonJS.doce_det.forEach(function(i){
                  if (i.ded_cant>0 && i.ded_cost>0) {
                    icostq=round(i.ded_cost*numTcam.value,6);
                    icosu=round(icostq/i.ded_cant,6);
                    ipord=((i.ded_cant*100)/sumcant);
                  } else {
                    icostq=(0).toFixed(6);
                    icosu=(0).toFixed(6);
                    ipord=(0).toFixed(6);
                  } 
                  addRowDetao(i.ded_cod, i.ded_desc, Number(i.ded_cant).toFixed(2), Number(icosu).toFixed(6), Number(icostq).toFixed(6), Number(ipord).toFixed(6), Number(0).toFixed(6), Number(0).toFixed(6), Number(icostq).toFixed(6), Number(icosu).toFixed(6), i.ded_ctacos, i.ded_ctainv);

              // addRowDetao(i.pd1_codpro, i.pd1_desc, i.pd1_cant, i.pd1_cosu, i.pd1_tfobq, i.pd1_pord, i.pd1_gasq, i.pd1_dai, i.pd1_vtotal, i.pd1_costuq);

                });  
                sumDetao();
                alWarning({"msg":{"title":"SE CARGO DETALLE","text":"Se cargo el detalle del documento para prorratear, puede continuar"}});
                return true;
              }
            }
          }
        });
      }
    });

    // CLICK GUARDAR
    $("#btnGuardar").click(function (){
      restriccion();
      if (condicionesobligatorias()) {return};
      if ($("#tblDetao tbody").children().length == 0) {
        alWarning({"msg":{"title":"NO HA REGISTRADO DETALLE","text":"Primero debe registrar detalle para el documento"}});
        return;
      }
      if (ctaInc){
         txtCodd.focus();
         alWarning({"msg":{"title":"HAY UN PROBLEMA CON LA PARTIDA","text":"Alguna de las cuentas de la partida, no esta bien asignada."}});
         return true;
      }
      if ($("#tblPol tbody").children().length == 0) {
        alWarning({"msg":{"title":"NO HA GENERADO PARTIDA","text":"A este dodumento debe registrarle partida"}});
        return;
      }
      if (prtstatus=='P'){
         alWarning({"msg":{"title":"YA PROCESADO","text":"Este prorrateo ya fue procesado, no puede hacerle cambios."}});
         return true;
      }

      guardarDoc();
    });

    // CLICK GRABAR E IMPRIMIR
    $("#btnGuardarImprimir").click(function (){
      if (condicionesobligatorias()) {return};
      if ($("#tblDetao tbody").children().length == 0) {
        alWarning({"msg":{"title":"NO HA REGISTRADO DETALLE","text":"Primero debe registrar detalle para el documento"}});
        return;
      }
      if (prtstatus=='P') {
        numdoc=numNum.value;
        imprimirDoc(numdoc);
      } else {
        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();
    });

    $("#btnProcesar").click(function (){
      restriccion();
      if (condicionesobligatorias()) {return};
      if ($("#tblDetao tbody").children().length == 0) {
        alWarning({"msg":{"title":"NO HA REGISTRADO DETALLE","text":"Primero debe registrar detalle para el documento"}});
        return;
      }
      if (ctaInc){
         txtCodd.focus();
         alWarning({"msg":{"title":"HAY UN PROBLEMA CON LA PARTIDA","text":"Alguna de las cuentas de la partida, no esta bien asignada."}});
         return true;
      }
      if ($("#tblPol tbody").children().length == 0) {
        alWarning({"msg":{"title":"NO HA GENERADO PARTIDA","text":"A este dodumento debe registrarle partida"}});
        return;
      }
      if (prtstatus=='P'){
         alWarning({"msg":{"title":"YA PROCESADO","text":"Este prorrateo ya fue procesado, no puede hacer este proceso otra vez."}});
         return true;
      }
      if (nuevo){
         alWarning({"msg":{"title":"PRIMERO DEBE GRABARSE","text":"Antes de poder PROCESAR EL PRORRATEO, debe grabarlo y le aconsejamos imprimirlo, luego de hacerlo intente nuevamente."}});
         return true;
      }

      numdoc=numNum.value;

      const fnT = function(){

        const parametros = new FormData();

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

        parametros.append("numNum", numdoc);
        parametros.append("dtFec", dtFec.value);
      
        $.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 {
              limpiar();
              tblClear("tblDetao");
              sumDetao();
              tblClear("tblDetaG1");
              sumDetaG1();
              tblClear("tblDetaG2");
              sumDetaG2();
              tblClear("tblPol");
              sumPol();
              //alSuccess(jsonJS);
            }
            }), 0;
          }
        });
        //numNum.focus();
      }
      const fnF = function(){
        return true;
      }
      usuClave(fnT, fnF);
    });
  });

  // CLICK ADD
  $("body").on("click", "#btnAddp", function () {
    if (restriccionCamposVacios()) {return};
    if (restriccionMesCerrado()) {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 (condicionesobligatorias()) {return};
    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 (cbExentod.checked == 0) {
      var exentosn = 'N';
    } else {
      var exentosn = 'S';
    } 
    addRowDetao(txtCodd.value, txtDescd.value, unimed, txtMedid.value, isNullNumber(numCantd.value).toFixed(2), isNullNumber(numCosud.value).toFixed(5), isNullNumber(numTotd.value).toFixed(5), isNullNumber(numBonid.value).toFixed(2), exentosn, ctacos, ctainv);
    sumDetao();
    txtCodd.value="";
    txtCodd.focus();
  });

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

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

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

  // 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 dataCantd = $(this).parents("tr").find("#dataCantd");
    const dataCosuq = $(this).parents("tr").find("#dataCosuq");
    const dataTotq = $(this).parents("tr").find("#dataTotq");
    const dataDistrib = $(this).parents("tr").find("#dataDistrib");
    const dataGastos = $(this).parents("tr").find("#dataGastos");
    const dataDai = $(this).parents("tr").find("#dataDai");
    const dataTotal = $(this).parents("tr").find("#dataTotal");
    const dataCosunit = $(this).parents("tr").find("#dataCosunit");

    txtCoddm.value = dataCodd.text();
    txtDescdm.value = dataDescd.text();
    numCantdm.value = dataCantd.text();
    numCosuqm.value = dataCosuq.text();
    numTotqm.value = dataTotq.text();
    numDistribm.value = dataDistrib.text();
    numGastosm.value = dataGastos.text();
    numDaim.value = dataDai.text();
    numTotalm.value = dataTotal.text();
    numCosunitm.value = dataCosunit.text();


    $("body").on("click", "#btnModificar", function() {
      if (restriccionModal()) {return};
      dataDai.text(isNullNumber(numDaim.value).toFixed(6));
      limpiarModalDetao();
      recalculaCosto();
      sumDetao();
    });
  });

  // CLICK EDIT GASTOS 1
  $("body").on("click", "#btnEditg1", function() {
    $('#pills-000-tab').text("Moificar Datos de este Rubro (Dolares)");
    $('#btnAgregarg1').hide();
    $('#btnModificarg1').show();

    const dataCodg1 = $(this).parents("tr").find("#dataCodg1");
    const dataDescg1 = $(this).parents("tr").find("#dataDescg1");
    const dataValg1 = $(this).parents("tr").find("#dataValg1");
    //const dataTcg1 = $(this).parents("tr").find("#dataTcg1");

    //txtCodg1.value = dataCodg1.text();
    txtDescg1.value = dataDescg1.text();
    numValg1.value = dataValg1.text();
    /*if (dataTcg1.text()==1) {
       numTcamg1.value = numTcam.value;
    } else {
      numTcamg1.value = dataTcg1.text();
    } */ 
    $("body").on("click", "#btnModificarg1", function() {
      $('#modalGastos1').modal('toggle');
      //dataCodg1.text(txtCodg1.value);
      //dataDescg1.text(txtDescg1.value);
      dataValg1.text(isNullNumber(numValg1.value).toFixed(2));
      //dataTcg1.text(isNullNumber(numTcamg1.value).toFixed(6));

      limpiarModalDetag1();
      sumDetaG1();
      recalculaCosto();
      sumDetao();
    });
  });

  // CLICK EDIT GASTOS 2
  $("body").on("click", "#btnEditg2", function() {
    $('#pills-0000-tab').text("Moificar Datos de este Rubro (Quetzales)");
    $('#btnAgregarg2').hide();
    $('#btnModificarg2').show();

    const dataCodg2 = $(this).parents("tr").find("#dataCodg2");
    const dataDescg2 = $(this).parents("tr").find("#dataDescg2");
    const dataValg2 = $(this).parents("tr").find("#dataValg2");

    //txtCodg1.value = dataCodg1.text();
    txtDescg2.value = dataDescg2.text();
    numValg2.value = dataValg2.text();
    $("body").on("click", "#btnModificarg2", function() {
      $('#modalGastos2').modal('toggle');
      //dataCodg1.text(txtCodg1.value);
      //dataDescg1.text(txtDescg1.value);
      dataValg2.text(isNullNumber(numValg2.value).toFixed(2));

      limpiarModalDetag2();
      sumDetaG2();
      recalculaCosto();
      sumDetao();
    });
  });

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

  // MODAL Gastos1 HIDDEN
  $('#modalGastos1').on('hidden.bs.modal', function (e) {
    $("body").off("click", "#btnModificarg1");
  });

  // MODAL Gastos2 HIDDEN
  $('#modalGastos2').on('hidden.bs.modal', function (e) {
    $("body").off("click", "#btnModificarg2");
  });

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

      colDetao = ["acciones","codd", "descd", "cantd", "cosuq", "totq", "distrib", "gastos", "dai", "total", "cosunit", "ctacos", "ctainv"];


      const parametros = new FormData();
      parametros.append("action", "generarPartida");
      parametros.append("tblDetao", tblToJson(colDetao, "tblDetao", 0));
      parametros.append("numTcam", numTcam.value);

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

</script>
