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

# QUERYS
$sTipoc = "SELECT * FROM tipoc";
$sMeses = "SELECT * FROM meses";
$sTipopol = "SELECT * FROM tipopol WHERE tp_bansn='S' AND tp_cod!='004'";
$sBancos = "SELECT *, 
              TRIM(ban_nom) as ban_nom,
              TRIM(ban_ctab) as ban_ctab,
              TRIM(ban_ctac) as ban_ctac
            FROM bancos WHERE ban_emp='$empCod'";
$sCiemes = "SELECT ciem_stat FROM ciemes WHERE ciem_emp='$empCod' AND ciem_ano=$nAnio AND ciem_mes=$nMes";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["tipoc"] = $db->query($sTipoc);
$select["meses"] = $db->query($sMeses);
$select["tipopol"] = $db->query($sTipopol);
$select["bancos"] = $db->query($sBancos);
$select["bancos2"] = $db->query($sBancos);
$mesCerrado = ($db->sFetchAssoc($sCiemes)["ciem_stat"] == "C") ? "true" : "false";
$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 POLIZA -->
      <div class="modal fade" id="modalPol" tabindex="-1" role="dialog" aria-labelledby="modalPolTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
          <div class="modal-content bg-dark">
            <div class="modal-header">
              <ul class="nav nav-pills" id="pills-tab" role="tablist">
                <li class="nav-item">
                  <a class="nav-link active" id="pills-00-tab" data-toggle="pill" href="#pills-00" role="tab" aria-controls="pills-00" aria-selected="true"></a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" id="pills-01-tab" data-toggle="pill" href="#pills-01" role="tab" aria-controls="pills-01" aria-selected="false">Buscar Cuentas</a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-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-4">
                          <label for="txtCta">Cuenta</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtCta" placeholder="">
                        </div>
                        <div class="col-md-8">
                          <label for="txtCtaNom">Nombre Cuenta</label>
                          <input type="text" class="form-control form-control-sm form-control-as form-info" id="txtCtaNom" placeholder="" disabled>
                        </div>
                      </div>
                      <div class="form-row">
                        <div class="col-md-6">
                          <label for="numDebe">Debe</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numDebe" placeholder="0.00">
                        </div>
                        <div class="col-md-6">
                          <label for="numHaber">Haber</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numHaber" placeholder="0.00">
                        </div>
                      </div>
                    </div>

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

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

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

      <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>
            </ul>
            <div class="tab-content bg-transparent border-0" id="pills-tabContent">
              <div class="tab-pane fade show active" id="pills-0" role="tabpanel" aria-labelledby="pills-0-tab">

                <form action="" name="thisform" autocomplete="off" enctype="multipart/form-data">
                  <div class="form-row">
                    <div class="col-12 col-sm-10">
                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-md-5">
                            <label for="selBan">Banco</label>
                            <select class="form-control form-control-sm form-control-as font-size-lg" name="selBan" id="selBan">
                              <?php
                                while ($rec = $db->fetchAssoc($select['bancos'])) {
                                  echo  '<option value="'.$rec['ban_num'].'" data-mon="'.$rec['ban_mon'].'" data-ctab="'.$rec['ban_ctab'].'" data-ctac="'.$rec['ban_ctac'].'" data-ctadif="'.$rec['ban_ctadif'].'">'.utf8_encode($rec['ban_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-md-4">
                            <label for="selTipo">Tipo Documento</label>
                            <select class="form-control form-control-sm form-control-as font-size-lg" name="selTipo" id="selTipo">
                              <?php
                                while ($rec = $db->fetchAssoc($select['tipopol'])) {
                                  echo  '<option value="'.$rec['tp_cod'].'" data-deha="'.$rec['tp_deha'].'">'.utf8_encode($rec['tp_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>


                          <div class="col-md-3">
                            <label for="numNum">No. Documento</label>
                            <input type="number" class="form-control form-control-sm form-control-as font-size-lg" id="numNum" placeholder="0">
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-6 col-md-3">
                            <label for="dtFec">Fecha Documento</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFec" placeholder="">
                          </div>
                          <div class="col-6 col-md-3">
                            <label for="numTot">Valor del Documento</label>
                            <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numTot" placeholder="0.00" min="0">
                          </div>
                          <div class="col-6 col-md-2">
                            <label for="numTcam">Tasa de Cambio</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numTcam">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-5">
                            <label class="pr-1"></label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crDH1" name="crDH" class="custom-control-input" value="D" disabled>
                              <label class="custom-control-label" for="crDH1">Suma al Banco</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crDH2" name="crDH" class="custom-control-input" value="A" disabled>
                              <label class="custom-control-label" for="crDH2">Resta al Banco</label>
                            </div>
                          </div>
                          <div class="col-md-6">
                            <label for="selBana">Solo si es transferencia ingrese banco al que sumara:</label>
                            <select class="form-control form-control-sm form-control-as font-size-lg" name="selBana" id="selBana">
                              <?php
                                while ($rec = $db->fetchAssoc($select['bancos2'])) {
                                  echo  '<option value="'.$rec['ban_num'].'" data-mon="'.$rec['ban_mon'].'" data-ctab="'.$rec['ban_ctab'].'" data-ctac="'.$rec['ban_ctac'].'">'.utf8_encode($rec['ban_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                        </div>
                        <div class="form-row">
                        </div>
                        <div class="form-row">
                          <div class="col-12">
                            <label for="txtCon">Concepto</label>
                            <textarea class="form-control form-control-sm form-control-as" id="txtCon" rows="2"></textarea>
                          </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-success" id="btnAdd">
                              <i class="fas fa-plus-circle"></i> Agregar
                            </button>
                          </div>
                          <div class="col-7 text-right">
                            <button class="btn btn-primary" id="btnPartida" type="button"><i class="fas fa-poll-h"></i> Generar Partida</button>
                          </div>
                        </div>
                        <h3 class="text-light"></h3>
                        <div class="form-row">
                          <div class="col-md-12">
                            <div class="table-responsive">
                              <table class="table table-hover table-bordered table-dark table-sm" id="tblPol">
                                <thead>
                                  <tr>
                                    <th scope="col" class="text-center 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-12 col-sm-2">
                      <div class="form-group position-fixed-sm">

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

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

              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var totant = 0;
  var dhant = "";
  var banaant=0;
  var inputDoc = "numNum";
  var tblPolAnt;
  var mesCerrado = <?php echo $mesCerrado ?>;
  var mesCerradoI = <?php echo $mesCerrado ?>;
  var btnAddEdit = "00";
  var inputCtaMov = "txtCta";

  const numNum = document.thisform.numNum;
  const selBan = document.thisform.selBan;
  const selBana = document.thisform.selBana;
  const selTipo = document.thisform.selTipo;
  const dtFec = document.thisform.dtFec;
  const numTot = document.thisform.numTot;
  const numTcam = document.thisform.numTcam;
  const txtCon = document.thisform.txtCon;
  const crDH = document.thisform.crDH;

  const txtCta = document.getElementById("txtCta");
  const txtCtaNom = document.getElementById("txtCtaNom");
  const numDebe = document.getElementById("numDebe");
  const numHaber = document.getElementById("numHaber");

  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(selBan.value)) {
        selBan.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el Banco"}});
        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;
      }
      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 && selTipo.value != "001.01") {
        alWarning({"msg":{"title":"Partida Vacía","text":"Es necesario Generar Partida"}});
        return true;
      }
      // RECORRER PARTIDA PARA BUSCAR UNA CUENTA INCORRECTA
      var ctaInc = false;
      var ctaIncBan = true;
      //var ctaIncBan = false;
      var debInc = false;
      var acrInc = false;
      $("#tblPol tbody tr").each(function(){
        if ($(this).find("td:eq(1)").text().includes('XXXX')) { ctaInc = true }
        if (selTipo.value== "003") {
          if ($(this).find("td:eq(1)").text() == $('#selBan').find('option:selected').data('ctac').toString()) {
            ctaIncBan = false;
          }
        } else {
          if ($(this).find("td:eq(1)").text() == $('#selBan').find('option:selected').data('ctac').toString()) {
            /*|| $(this).find("td:eq(1)").text() == $('#selBana').find('option:selected').data('ctac').toString()) {*/
            ctaIncBan = false;
            if ($(this).find("td:eq(3)").text() != numTot.value) { acrInc = true }
            if ($(this).find("td:eq(4)").text() != numTot.value) { debInc = true }
          }
        } 
      });
      if ((ctaInc || ctaIncBan) && selTipo.value != "001.01") {
        alWarning({"msg":{"title":"Cuenta Incorrecta","text":"Alguna cuenta de la partida no está asignada correctamente, verifique"}});
        return true;
      }
      if (selTipo.value == "003") {
        if (acrInc) {
          alWarning({"msg":{"title":"Crédito Incorrecto","text":"Lo que quiere acreditar en la cuenta de banco NO COINCIDE CON EL VALOR DEL DOCUMENTO, verifique."}});
          return true;
        }
        if (debInc) {
          alWarning({"msg":{"title":"Débito Incorrecto","text":"Lo que quiere debitar en la cuenta de banco NO COINCIDE CON EL VALOR DEL DOCUMENTO, verifique. 1"}});
          return true;
        }
      } else if (selTipo.value!="003" && $("#selTipo option:selected").data('deha') == "D") {
        if (acrInc && selTipo.value != "001.01") {
          alWarning({"msg":{"title":"Crédito Incorrecto","text":"Lo que quiere acreditar en la cuenta de banco NO COINCIDE CON EL VALOR DEL DOCUMENTO, verifique."}});
          return true;
        }
      } else if (selTipo.value!="003" && $("#selTipo option:selected").data('deha') == "A") {
        if (debInc && selTipo.value != "001.01") {
          alWarning({"msg":{"title":"Debito Incorrecto","text":"Lo que quiere debitar en la cuenta de banco NO COINCIDE CON EL VALOR DEL DOCUMENTO, verifique. 2"}});
          return true;
        }
      }
    } else {
      if (isNullPer(selBan.value) || isNullPer(numNum.value)) {
        return true;
      }
    }
    return false;
  }


  function restriccionCamposVacios() {
    if (isNullPer(selBan.value)) {
      selBan.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el BANCO"}});
      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 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;
    }
    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 restriccionModal() {
    if (restriccionCta()) {
      txtCta.focus();
      alWarningTimer({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar la CUENTA","timer":timeOutWarningSm}});
      return true;
    }
    $('#modalPol').modal('toggle');
    return false;
  }

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

  function consultarMov(){
    if (restriccion(true)) {return};
    
    //txtNext = dtFec;

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

    parametros.append("selTipoCod", selTipo.value);
    parametros.append("numNum", numNum.value);
    parametros.append("selBanCod", selBan.value);

    //txtNext.focus()

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

        if(jsonJS.error == true){
          alError(jsonJS);
        } else {
          limpiar();
          tblClear("tblPol");
          sumPol();

         
          if (jsonJS.movi === null) {
            nuevo = true;
            totant=0;
            dhant="";
            banaant=0;
          } else {
            dtFec.value = jsonJS.movi.mov_fec;
            numTot.value = jsonJS.movi.mov_tot;
            numTcam.value = jsonJS.movi.mov_tcam;
            txtCon.value = jsonJS.movi.mov_con;
            if (jsonJS.movi.mov_debacr == "D") {
              crDH1.checked = true;
              crDH2.checked = false;
            } else {
              crDH1.checked = false;
              crDH2.checked = true;
            }
            selBana.value = jsonJS.movi.mov_bana;
            movmod = jsonJS.movi.mov_mod;
            jsonJS.poli_det.forEach(function(i){
              addRowPol(i.pold_cta, i.pold_ctan, i.pold_debe, i.pold_haber);
            });
            sumPol();
            nuevo = false;
            totant = jsonJS.movi.mov_tot;
            dhant = jsonJS.movi.mov_debacr;
            banaant = jsonJS.movi.mov_bana;
          }
          //(pressEnter) ? alClose() : alCloseFocus(txtNext);
          //pressEnter = false; 
          //alClose();
          //dtFec.focus();
        }
      }
    });
  }

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

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

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

    parametros.append("nuevo", nuevo);
    parametros.append("numNum", numDoc);
    parametros.append("selTipoCod", selTipo.value);
    parametros.append("selTipoNom", $("#selTipo option:selected").text());
    parametros.append("selBanCod", selBan.value);
    parametros.append("selBanNom", $("#selBan option:selected").text());
    parametros.append("selBanMon", $("#selBan option:selected").data('mon'));
    parametros.append("selBanaCod", selBana.value);
    parametros.append("selBanaNom", $("#selBana option:selected").text());
    parametros.append("selBanaMon", $("#selBana option:selected").data('mon'));
    parametros.append("dtFec", dtFec.value);
    parametros.append("numTot", numTot.value);
    parametros.append("totant", totant);
    parametros.append("dhant", dhant);
    parametros.append("banaant", banaant);
    parametros.append("numTcam", numTcam.value);
    parametros.append("crDH", crDH.value);
    parametros.append("txtCon", txtCon.value);
    parametros.append("tblPol", tblToJson(colPol, "tblPol", 0));
    parametros.append("tblPolAnt", tblPolAnt);


    //numNum.focus();
    
    $.ajax({
      data:  parametros,
      url:   window.location.origin+window.location.pathname+"actions.php",
      type:  "post",
      contentType: false,
      processData: false,
      async: false,
      beforeSend: function () {
        //alLoad("Cargando...")
      },
      success: function (jsonPhp) {
        console.log(jsonPhp);        
        //alClose();
      //  setTimeout(function () {

        const jsonJS = JSON.parse(jsonPhp);

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

          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 (jsonJS.probpol2 != "X") {
            alError({"msg":{"type":"error","title":"CUENTA DEL BANCO","text":"No tiene asignada la cuenta del banco correctamente, verifique.", "ok":"Aceptar"}});
              var snhacer = false;
                     return true;
          }
          if (jsonJS.probpol3 != "X") {
            alError({"msg":{"type":"error","title":"VALOR CUENTA DEL BANCO","text":"Lo que quiere asignar a la cuenta del Bnco NO COINCIDE CON EL VALOR DEL DOCUMENTO, verifique.", "ok":"Aceptar"}});
              var snhacer = false;
                     return true;
          }*/
          if (snhacer) {
            if (imprimir) {
              imprimirPoliza(true, jsonJS.dtGrabado, numDoc);
            }
            alSuccess(jsonJS);
            numNum.value = "";
            limpiar();
            tblClear("tblPol");
            sumPol();
            $("#btnGuardar, #btnGuardarImprimir").focus(function (){
              //numNum.focus();
            });
          }  
        }
       // }), 0;
      }
    });
  }

  function imprimirPoliza(guardar = true, dtGrabado = "", numDoc){
    //if (restriccion(false, false)) {return};
    colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

    const getTipoCod = "?selTipoCod="+selTipo.value;
    const getTipoNom = "&selTipoNom="+$("#selTipo option:selected").text();
    const getBanCod = "&selBanCod="+selBan.value;
    const getBanNom = "&selBanNom="+$("#selBan option:selected").text();
    const getBanaCod = "&selBanaCod="+selBana.value;
    const getBanaNom = "&selBanaNom="+$("#selBana option:selected").text();
    const getNum = "&numNum="+numDoc;
    const getFec = "&dtFec="+dtFec.value;
    const getTot = "&numTot="+numTot.value;
    const getTcam = "&numTcam="+numTcam.value;
    const getDH = "&crDH="+crDH.value;
    const getCon = "&txtCon="+txtCon.value;
    //const getDtGrabado = "&dtGrabado="+dtGrabado;
    const getTblPol = "&tblPol="+tblToJson(colPol, "tblPol", 0);
    //const getBtn = (guardar) ? "&btn=Fecha y hora de Impresión y Grabado:" : "&btn=Fecha y hora de Impresión:";
   
    var url = window.location.origin+window.location.pathname+"print.php"+getTipoCod+getTipoNom+getBanCod+getBanNom+getBanaCod+getBanaNom+getNum+getFec+getTot+getTcam+getDH+getCon+getTblPol;

    window.open(url, '_blank');

  }

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

  function limpiar(todo = false){
    dtFec.value= '<?php echo $dtFec; ?>';    
  //  numTcam.value = (1).toFixed(5);
  //  crDH1.checked = true;
  //  crDH2.checked = false;
    numTot.value = (0).toFixed(2);
    txtCon.value = "";
  }

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


  $(document).ready(function() {
    $(this).find('select:visible:first').focus();
    document.thisform.dtFec.value = '<?php echo $dtFec; ?>';
    crDH1.checked = true;
    crDH2.checked = false;
    selBan.value = 1;
    selTipo.value = "002";

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

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

    // FOCUS TIPO DE DOCUMENTO
    $("#selTipo").focus(function() {
      limpiar();
      tblClear("tblPol");
      sumPol();

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

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

      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        success: function (jsonPhp) {
          const jsonJS = JSON.parse(jsonPhp);
            if (jsonJS.bancos === null) {
            } else {
              if (jsonJS.bancos.ban_mon == 1) {
                numTcam.value = (1).toFixed(5);
                numTcam.disabled = true;
              } else {
                numTcam.value = '<?php echo $_SESSION["empTasa"] ?>';
                numTcam.disabled = false;
              }
            }
          }
      });
    });

    // FOCUS TIPO DE DOCUMENTO
    $("#numNum").focus(function() {
      numNum.value="";
      if (selTipo.value == "001.01") {
        crDH1.disabled = false;
        crDH2.disabled = false;
      } else {
        crDH1.disabled = true;
        crDH2.disabled = true;
      }

      limpiar();
      tblClear("tblPol");
      sumPol();

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

      parametros.append("numNum", numNum.value);
      parametros.append("selBanCod", selBan.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.bancos === null) {
            } else {
            if (jsonJS.bancos.ban_mon == 1) {
              numTcam.value = (1).toFixed(5);
              numTcam.disabled = true;
            } else {
              numTcam.value = '<?php echo $_SESSION["empTasa"] ?>';
              numTcam.disabled = false;
            }
          }
        }
      }); 

      if ($("#selTipo option:selected").data('deha') == "A" ) {
        crDH1.checked = false;
        crDH2.checked = true;
      } else {
        crDH1.checked = true;
        crDH2.checked = false;
      }  
      if (selTipo.value == "003") {
        selBana.value=1;        
        selBana.disabled = false;
      } else {
        selBana.value=0;
        selBana.disabled = true;
      }
    });


    // VALID NUMERO
    $("#numNum")
    .blur(function (){
      setTimeout(function(){
        if (!$('#selBan').is(':focus')) {
          consultarMov();
        }
      },0);
    })
    .change(function (){
      consultarMov();
    });

    // VALID FECHAS
    $("#dtFec")
    .blur(function (){
      if (restriccionCamposVacios()) {return};
        txtThis = dtFec;

        const parametros = new FormData();
        parametros.append("action", "mCerrado");
        parametros.append("dtFec", txtThis.value);

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

            if(jsonJS.error == true){
              alError(jsonJS);
            } else {
              if (jsonJS.ciemes === null) {
                mesCerrado = false;
              } else {
                if (jsonJS.ciemes.ciem_stat == "C") {
                  mesCerrado = true;
                  setTimeout(function(){
                    if (!$('#numNum').is(':focus') && !$('#selBan').is(':focus')) {
                      if ($('input, textarea').is(':focus')) {
                        restriccionMesCerrado();
                      }
                    }
                  },0);
                } else {
                  mesCerrado = false;
                }
              }
            }
          }
        });
    }); 

    // CHANGE TIPO
    $("#selTipo").change(function (){
      if ($("#selTipo option:selected").data('deha') == "A" ) {
        crDH1.checked = false;
        crDH2.checked = true;
      } else {
        crDH1.checked = true;
        crDH2.checked = false;
      }  
      if (selTipo.value == "003") {
        selBana.disabled = false;
      } else {
        selBana.disabled = true;
      }
    });

    // FOCUS VALOR CHEQUE, BENEFICIARIO, CONCEPTO
    $("#dtFec, #numTot, #txtCon").focus(function (){
      if (restriccionCamposVacios()) {return};
    });

    // VALID CUENTA
    $("#txtCta")
    .focus(function() {
      inputCtaMov = $(this).attr('id');
    })
    .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-01-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      txtGetValue = document.getElementById("txtCtaNom");
      txtNext = document.getElementById("numDebe");

      $(txtThis).off("blur");
      if (restriccionCta()) {return};

      const parametros = new FormData();
      parametros.append("action", "consultarCta");
      parametros.append("txtCod", txtThis.value);

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (jsonJS.cuentas === null) {
              txtGetValue.value = "";
              alErrorFocusTimer({"msg":{"type":"error","title":"No existe","text":"La cuenta "+txtThis.value+" no ha sido registrada", "ok":"Aceptar", "timer":timeOutErrorSm}}, txtThis);
            } else {
              if (jsonJS.cuentas.cta_con != "N") {
                txtGetValue.value = "";
                alErrorFocusTimer({"msg":{"type":"error","title":"No puede usar esta cuenta","text":"La cuenta "+txtThis.value+" no es de movimiento, no la puede usar", "ok":"Aceptar", "timer":timeOutErrorSm}}, txtThis);
              } else {
                txtGetValue.value = jsonJS.cuentas.cta_nom;
                (pressEnter) ? alClose() : alCloseFocus(txtNext);
              }
            }
            pressEnter = false;
            blurOn(txtThis, txtGetValue);
          }
        }
      });
    });

    // CLICK BORRAR
    $("#btnBorrar").click(function (){
      if (restriccion()) {return};
      if (movmod == 'cxp') {
        numNum.focus();
        alWarning({"msg":{"title":"GRABADO EN OTRO MODULO","text":"Este Documento fue registrado en Cuentas por Pagar, solo puede borrarlo desde ese modulo"}});
        return true;
      }
      if (movmod == 'cxc') {
        numNum.focus();
        alWarning({"msg":{"title":"GRABADO EN OTRO MODULO","text":"Este Documento fue registrado en Cuentas por Cobrar, solo puede borrarlo desde ese modulo"}});
        return true;
      }
      const numDoc = numNum.value;
      //numNum.focus();
      const fnT = function(){
        colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

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

        parametros.append("selBanCod", selBan.value);
        parametros.append("selBanaCod", selBana.value);
        parametros.append("selTipoCod", selTipo.value);
        parametros.append("numNum", numDoc);
        parametros.append("dtFec", dtFec.value);
        parametros.append("tblPolAnt", tblPolAnt);
        parametros.append("totant", totant);
        parametros.append("dhant", dhant);
        parametros.append("banaant", banaant);

        $.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) {
            const jsonJS = JSON.parse(jsonPhp);

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

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

    // CLICK ANULAR
    $("#btnAnular").click(function (){
      if (restriccion()) {return};
      if (movmod == 'cxp') {
        numNum.focus();
        alWarning({"msg":{"title":"GRABADO EN OTRO MODULO","text":"Este Documento fue registrado en Cuentas por Pagar, solo puede anularlo desde ese modulo"}});
        return true;
      }
      if (movmod == 'cxc') {
        numNum.focus();
        alWarning({"msg":{"title":"GRABADO EN OTRO MODULO","text":"Este Documento fue registrado en Cuentas por Cobrar, solo puede anularlo desde ese modulo"}});
        return true;
      }

      var numDoc=numNum.value;
      //numNum.focus();
      
      const fnT = function(){
        colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

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

        parametros.append("selBanCod", selBan.value);
        parametros.append("selBanaCod", selBana.value);
        parametros.append("selTipoCod", selTipo.value);
        parametros.append("numNum", numDoc);
        parametros.append("dtFec", dtFec.value);
        parametros.append("tblPolAnt", tblPolAnt);
        parametros.append("totant", totant);
        parametros.append("dhant", dhant);
        parametros.append("banaant", banaant);

        $.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 {
              alSuccess(jsonJS);
              numNum.value = "";
              limpiar();
              tblClear("tblPol");
              sumPol();
              $("#btnAnular").focus(function (){
                numNum.focus();
              });
            }
          }
        });
      }
      const fnF = function(){
        return true;
      }
      usuClave(fnT, fnF);
    });

    /*$("#btnImprimir").click(function (){
      var numDoc = numNum.value
      colPol = ["acciones", "cta", "ctaNom", "debe", "haber"];

      const getTipoCod = "?selTipoCod="+selTipo.value;
      const getTipoNom = "&selTipoNom="+$("#selTipo option:selected").text();
      const getBanCod = "&selBanCod="+selBan.value;
      const getBanNom = "&selBanNom="+$("#selBan option:selected").text();
      const getBanaCod = "&selBanaCod="+selBana.value;
      const getBanaNom = "&selBanaNom="+$("#selBana option:selected").text();
      const getNum = "&numNum="+numDoc;
      const getFec = "&dtFec="+dtFec.value;
      const getTot = "&numTot="+numTot.value;
      const getTcam = "&numTcam="+numTcam.value;
      const getDH = "&crDH="+crDH.value;
      const getCon = "&txtCon="+txtCon.value;
      //const getDtGrabado = "&dtGrabado="+dtGrabado;
      const getTblPol = "&tblPol="+tblToJson(colPol, "tblPol", 0);
      //const getBtn = (guardar) ? "&btn=Fecha y hora de Impresión y Grabado:" : "&btn=Fecha y hora de Impresión:";
     
      var url = window.location.origin+window.location.pathname+"print.php"+getTipoCod+getTipoNom+getBanCod+getBanNom+getBanaCod+getBanaNom+getNum+getFec+getTot+getTcam+getDH+getCon+getTblPol;

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

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

    // CLICK GRABAR E IMPRIMIR
    $("#btnGuardarImprimir").click(function (){
      guardarPoliza(true);
    });
    
    // CLICK AGREGAR
    $("#btnAgregar").click(function () {
      if (restriccionModal()) {return};
      addRowPol(txtCta.value, txtCtaNom.value, isNullNumber(numDebe.value).toFixed(2), isNullNumber(numHaber.value).toFixed(2));
      limpiarModalPol();
      sumPol();
      $("#btnAdd").focus();
    });
  });

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

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

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

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

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

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

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


    // 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 (selTipo.value == '001.01') {
        alWarning({"msg":{"title":"NO NECESITA PARTIDA","text":"Como esta para asignar saldo inicial, no necesita partida"}});
        return;
      }

      var totQ = round(numTot.value*numTcam.value,2);
      var valch = Number(numTot.value);
      var totdif = round((totQ-Number(numTot.value)),2);

      if (($('#selBan').find('option:selected').data('mon') == 1 && $('#selBana').find('option:selected').data('mon') == 1) || ($('#selBan').find('option:selected').data('mon') == 2 && $('#selBana').find('option:selected').data('mon') == 2)) {
          var totQa = round(numTot.value*numTcam.value,2);
          var valcha = Number(numTot.value);
          var totdifa = round((totQa-Number(numTot.value)),2);
      }

      if (($('#selBan').find('option:selected').data('mon') == 1 && $('#selBana').find('option:selected').data('mon') == 2)) {
          var tcama = '<?php echo $_SESSION["empTasa"] ?>';
          var totQa = round(numTot.value/tcama,2);
          var valcha = round(numTot.value/tcama,2);
          var totdifa = round((Number(numTot.value)-totQa),2);
      }

      if (($('#selBan').find('option:selected').data('mon') == 2 && $('#selBana').find('option:selected').data('mon') == 1)) {
          var totQa = round(numTot.value*numTcam.value,2);
          var valcha = Number(totQa);
          var totdifa = 0;
      }

      const parametros = new FormData();

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

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

      parametros.append("selTipoCod", selTipo.value);
      parametros.append("selBanCod", selBan.value);
      parametros.append("selBanaCod", selBana.value);
      parametros.append("numNum", numNum.value);
      parametros.append("dtFec", dtFec.value);
      parametros.append("numTot", numTot.value);
      parametros.append("numTcam", numTcam);
      parametros.append("tblPol", tblToJson(colPol, "tblPol", 0));

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

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            //tblClear("tblPol");
            //sumPol();
            
            if (selTipo.value == "003") {
              // Cuenta BANCOS
              if (!isNullPer(jsonJS.ctaBanac)) {
                addRowPol(jsonJS.ctaBanac.cta, jsonJS.ctaBanac.cta_nom, valcha.toFixed(2),"0.00");
                } else {
                addRowPol("XXXXXXX", "Ingrese Cuenta del Banco a Acreditar", valcha.toFixed(2),"0.00");
              }
              if (totdifa>0) {
                if (!isNullPer(jsonJS.ctaBanacdif)) {
                  addRowPol(jsonJS.ctaBanacdif.cta, jsonJS.ctaBanacdif.cta_nom,totdifa.toFixed(2), "0.00");
                  } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta del Diferencial",totdifa.toFixed(2), "0.00");
                }
              }
              if (!isNullPer(jsonJS.ctaBanc)) {
                addRowPol(jsonJS.ctaBanc.cta, jsonJS.ctaBanc.cta_nom, "0.00",valch.toFixed(2));
                } else {
                addRowPol("XXXXXXX", "Ingrese Cuenta del Banco a Debitar", "0.00",valch.toFixed(2));
              }
              if (totdif>0) {
                if (!isNullPer(jsonJS.ctaBandif)) {
                  addRowPol(jsonJS.ctaBandif.cta, jsonJS.ctaBandif.cta_nom, "0.00",totdif.toFixed(2));
                  } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta del Diferencial", "0.00",totdif.toFixed(2));
                }
              }
            } 
            if (selTipo.value!="003"  && $("#selTipo option:selected").data('deha') == "A") {
              if (selTipo.value != "001.01") {
                addRowPol("XXXXXXX", "Ingrese Cuenta a Acreditar", totQ.toFixed(2),"0.00");
                // Cuenta BANCOS
                if (!isNullPer(jsonJS.ctaBanc)) {
                  addRowPol(jsonJS.ctaBanc.cta, jsonJS.ctaBanc.cta_nom, "0.00",valch.toFixed(2));
                  } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta del Banco a Debitar", "0.00",valch.toFixed(2));
                }
                if (totdif>0) {
                  if (!isNullPer(jsonJS.ctaBandif)) {
                    addRowPol(jsonJS.ctaBandif.cta, jsonJS.ctaBandif.cta_nom, "0.00",totdif.toFixed(2));
                    } else {
                    addRowPol("XXXXXXX", "Ingrese cuenta del Diferencial", "0.00",totdif.toFixed(2));
                  }
                }
              } else {
                if (!isNullPer(jsonJS.ctaBanc)) {
                  addRowPol(jsonJS.ctaBanc.cta, jsonJS.ctaBanc.cta_nom, "0.00","0.00");
                  } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta del Banco a Debitar", "0.00","0.00");
                }
              }
            } 
            if (selTipo.value!="003"  && $("#selTipo option:selected").data('deha') == "D") {
              if (selTipo.value != "001.01") {
                // Cuenta BANCOS
                if (!isNullPer(jsonJS.ctaBanc)) {
                  addRowPol(jsonJS.ctaBanc.cta, jsonJS.ctaBanc.cta_nom, valch.toFixed(2),"0.00");
                  } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta del Banco a Debitar", valch.toFixed(2),"0.00");
                }
                if (totdif>0) {
                  if (!isNullPer(jsonJS.ctaBandif)) {
                    addRowPol(jsonJS.ctaBandif.cta, jsonJS.ctaBandif.cta_nom,totdif.toFixed(2), "0.00");
                    } else {
                    addRowPol("XXXXXXX", "Ingrese cuenta del Diferencial",totdif.toFixed(2), "0.00");
                  }
                }
                if (!isNullPer(jsonJS.ctaClien)) {
                  addRowPol(jsonJS.ctaClien.cta, jsonJS.ctaClien.cta_nom, "0.00",totQ.toFixed(2));
                  } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta a Debitar", "0.00",totQ.toFixed(2));
                }
              } else {
                if (!isNullPer(jsonJS.ctaBanc)) {
                  addRowPol(jsonJS.ctaBanc.cta, jsonJS.ctaBanc.cta_nom,"0.00","0.00");
                  } else {
                  addRowPol("XXXXXXX", "Ingrese cuenta del Banco a Debitar", "0.00","0.00");
                }
              }
            }
            sumPol();
            alClose();
          }
        }
      });
    });



    // VALID CUENTAS
    $("input[id*='txtCta']:not(#txtCta)")
    .focus(function() {
      inputCtaMov = $(this).attr('id');
    })
    .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-12-tab").click(); }
    })
    .change(function (){
      var inputs = $(this).closest('form').find(':input');

      txtThis = this;
      txtGetValue = document.getElementById($(this).attr('id')+"Nom");
      txtNext = inputs.eq(inputs.index(this)+2);

      $(txtThis).off("blur");
      if (restriccionCtaCod()) {return};

      const parametros = new FormData();
      parametros.append("action", "consultarCta");
      parametros.append("txtCod", txtThis.value);

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (jsonJS.cuentas === null) {
              txtGetValue.value = "";
              alErrorFocusTimer({"msg":{"type":"error","title":"No existe","text":"La cuenta "+txtThis.value+" no ha sido registrada", "ok":"Aceptar", "timer":timeOutErrorSm}}, txtThis);
            } else {
              if (jsonJS.cuentas.cta_con != "N") {
                txtGetValue.value = "";
                alErrorFocusTimer({"msg":{"type":"error","title":"No puede usar esta cuenta","text":"La cuenta "+txtThis.value+" no es de movimiento, no la puede usar", "ok":"Aceptar", "timer":timeOutErrorSm}}, txtThis);
              } else {
                txtGetValue.value = jsonJS.cuentas.cta_nom;
                (pressEnter) ? alClose() : alCloseFocus(txtNext);
              }
            }
            pressEnter = false;
            blurOn(txtThis, txtGetValue);
          }
        }
      });
    });


  // FOCUS PILL SHOWN
  $('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" && isNullPer(numNum.value)) || target != "#pills-0") {
       /* if (target == "#pills-10" && isNullPer(txtSerieI.value)) { txtSerieI.focus();
        } else if (target == "#pills-10" && isNullPer(numNumI.value)) { numNumI.focus();
        } else if (target == "#pills-10" && isNullPer(txtNitI.value)) { txtNitI.focus();
        } else if (relatedTarget == "#pills-12") { $("#"+inputCtaMov).focus();
        } else {*/
          ($(target+' select:visible:first').length) ? $(target+' select:visible:first').focus() : $(target+' input:visible:first').focus();
        //}
      }
    }
  });


</script>

