<?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";
$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']));
?>
<?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 Fecha Anula -->
      <div class="modal fade" id="modalfeca" tabindex="-1" role="dialog" aria-labelledby="modalfaTitle" 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">FECHA ANULACION</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="dtFecAnu">Fecha Anulacion</label>
                          <input type="date" class="form-control form-control-sm form-control-as" id="dtFecAnu" placeholder="">
                        </div>
                      </div>
                      <div class="form-row">
                        <div class="col-md-12">
                          <label for="txtConAnu">Concepto anulacion</label>
                        <textarea class="form-control form-control-sm form-control-as" id="txtConAnu" rows="3"></textarea>
                        </div>
                      </div>
                    </div>

                    <button type="button" class="btn btn-success btn-block" id="btnContinuar">Proceder a la Anulacion</button>
                  </form>
                </div>
              </div>

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

      <!-- MODAL Poliza Anular -->
      <div class="modal fade" id="modalpolAnu" tabindex="-1" role="dialog" aria-labelledby="modalpaTitle" 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-001-tab" data-toggle="pill" href="#pills-001" role="tab" aria-controls="pills-001" aria-selected="true">POLIZA ANULACION</a>
                </li>
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-black" 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-001" role="tabpanel" aria-labelledby="pills-001-tab">
                  
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">
                      <div class="form-row">
                        <div class="col-5">
                          <label for="anudtFec">Fecha</label>
                          <input type="date" class="form-control form-control-sm form-control-as" id="anudtFec" placeholder="" disabled>
                        </div>
                        <div class="col-md-7">
                          <label for="anuselTipo">Tipo de Poliza</label>
                          <select class="form-control form-control-sm form-control-as" name="anuselTipo" id="anuselTipo" disabled>
                            <option value="0">Seleccionar...</option>
                            <?php
                              while ($rec = $db->fetchAssoc($select['tipopol'])) {
                                echo  '<option value="'.$rec['tp_cod'].'">'.utf8_encode($rec['tp_nom']).'</option>';
                              }
                            ?>
                          </select>
                        </div>
                      </div>

                      <div class="form-row">

                        <div class="col-md-6">
                          <label for="anuselBan">Banco</label>
                          <select class="form-control form-control-sm form-control-as" name="anuselBan" id="anuselBan" disabled>
                            <option value="0">Sin Banco</option>
                            <?php
                              while ($recanu = $db->fetchAssoc($select['bancos2'])) {
                                echo  '<option value="'.$recanu['ban_num'].'">'.utf8_encode($recanu['ban_nom']).'</option>';
                              }
                            ?>
                          </select>
                        </div>

                        <div class="col-md-6">
                          <label for="anunumNum">No. Poliza</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="anunumNum" placeholder="0">
                        </div>
                      </div>

                      <div class="form-row">
                        <div class="col-12">
                          <label for="anutxtCon">Concepto</label>
                          <textarea class="form-control form-control-sm form-control-as" id="anutxtCon" rows="3"></textarea>
                        </div>
                      </div>
                    </div>

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

                    <div class="form-group">
                      <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="anutblPol">
                              <thead>
                                <tr>
                                  <th scope="col" class="text-center">CUENTA</th>
                                  <th scope="col" class="text-center">DESCRIPCIÓN</th>
                                  <th scope="col" class="text-center">DEBE</th>
                                  <th scope="col" class="text-center">HABER</th>
                                </tr>
                              </thead>
                              <tbody>
                              </tbody>
                              <tfoot>
                                <th scope="col"></th>
                                <th scope="col" class="text-right">Totales</th>
                                <th scope="col" id="anudataTotDebe" class="text-right">0.00</th>
                                <th scope="col" id="anudataTotHaber" class="text-right">0.00</th>
                              </tfoot>
                            </table>
                          </div>
                        </div>
                      </div>
                    </div>
                    <button type="button" class="btn btn-success btn-block" id="anubtnGrabar">Grabar Poliza Reversion</button>
                  </form>
                </div>
              </div>

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


      <div class="container-as">
        <div class="row">
          <div class="col">
            <ul class="nav nav-pills mb-1" id="pills-tab" role="tablist">
              <li class="nav-item">
                <a class="nav-link active" id="pills-0-tab" data-toggle="pill" href="#pills-0" role="tab" aria-controls="pills-0" aria-selected="true">Anular/Borrar Cheques de Proveedores</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" id="pills-2-tab" data-toggle="pill" href="#pills-2" role="tab" aria-controls="pills-2" aria-selected="true">Buscar Cheques</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-6">
                            <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-ctab="'.$rec['ban_ctab'].'" data-ctac="'.$rec['ban_ctac'].'" data-forma="'.$rec['ban_forma'].'">'.utf8_encode($rec['ban_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-md-3">
                            <label for="numNum">No. Cheque</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 Cheque</label>
                            <input type="date" class="form-control form-control-sm form-control-as" id="dtFec" placeholder="" disabled>
                          </div>
                          <div class="col-6 col-md-3">
                            <label for="numTot">Valor del Cheque</label>
                            <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numTot" placeholder="0.00" min="0" disabled>
                          </div>
                          <div class="col-6 col-md-3">
                            <label for="numTcam">Tasa de Cambio</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numTcam" disabled>
                          </div>
                          <div class="col-6 col-md-3 text-center">
                            <div class="custom-control custom-switch">
                              <input type="checkbox" class="custom-control-input" name="cbNego" id="cbNego" disabled>
                              <label class="custom-control-label" for="cbNego">No negociable </label>
                            </div>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-12">
                            <label for="txtBene">Beneficiario</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtBene" disabled>
                          </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" disabled></textarea>
                          </div>
                        </div>
                      </div>

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

                      <div class="form-group">
                        <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">CUENTA</th>
                                    <th scope="col" class="text-center">DESCRIPCIÓN</th>
                                    <th scope="col" class="text-center">DEBE</th>
                                    <th scope="col" class="text-center">HABER</th>
                                  </tr>
                                </thead>
                                <tbody>
                                </tbody>
                                <tfoot>
                                  <th scope="col"></th>
                                  <th scope="col" 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-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 class="tab-pane fade" id="pills-2" role="tabpanel" aria-labelledby="pills-2-tab">
                <?php
                  $a='0';
                  $b='2';
                  include('../busCheques/index.html')
                ?>
              </div>

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

<script>
  var pressEnter = false;
  var nuevo = true;
  var totant = 0;
  var nuevoiva = true;
  var rfecAntI = "0000-00-00";
  var inputCheques = "numNum";
  var tblPolAnt;
  var mesCerrado = <?php echo $mesCerrado ?>;
  var mesCerradoI = <?php echo $mesCerrado ?>;
  var btnAddEdit = "00";
  var nuevoProvee = true;
  var inputCtaMov = "txtCta";
  var inputProvee = "txtNit"

  var sumcta=0;
  var falcta=0;

  const numNum = document.thisform.numNum;
  const selBan = document.thisform.selBan;
  const dtFec = document.thisform.dtFec;
  const numTot = document.thisform.numTot;
  const numTcam = document.thisform.numTcam;
  const cbNego = document.thisform.cbNego;
  const txtBene = document.thisform.txtBene;
  const txtCon = document.thisform.txtCon;

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

  const dtFecAnu = document.getElementById("dtFecAnu");
  const txtConAnu = document.getElementById("txtConAnu");


  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 CHEQUE"}});
        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 CHEQUE"}});
      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 anurestriccionMesCerrado() {
    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 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 addRowAnuPol(cta, ctaNom, debe, haber){
    const row = "<tr>"
                +"<td id='anudataCta'>"+cta+"</td>"
                +"<td id='anudataCtaNom'>"+ctaNom+"</td>"
                +"<td id='anudataDebe' class='text-right'>"+debe+"</td>"
                +"<td id='anudataHaber' class='text-right'>"+haber+"</td>"
                +"</tr>";
    $("#anutblPol tbody").append(row);
  }

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

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

    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.cheques === null) {
            nuevo = true;
            totant = 0;
            chmod='cxp';
            alWarning({"msg":{"title":"NO EXISTE EL CHEQUE","text":"Este cheque no ha sido registrado"}});
            return true;
          } else {
            dtFec.value = jsonJS.cheques.ch_fec;
            numTot.value = jsonJS.cheques.ch_tot;
            numTcam.value = jsonJS.cheques.ch_tcam;
            txtBene.value = jsonJS.cheques.ch_bene;
            txtCon.value = jsonJS.cheques.ch_con;
            cbNego.checked = (jsonJS.cheques.ch_nego == "N") ? 1 : 0;
            chmod = jsonJS.cheques.ch_mod;
            jsonJS.poli_det.forEach(function(i){
              addRowPol(i.pold_cta, i.pold_ctan, i.pold_debe, i.pold_haber);
            });
            sumPol();
            totant = jsonJS.cheques.ch_tot;            
            nuevo = false;
          }
          //(pressEnter) ? alClose() : alCloseFocus(txtNext);
          //pressEnter = false; 
          //alClose();
          //dtFec.focus();
        }
      }
    });
  }


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

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

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

  function sumAnuPol(){
    $("#anudataTotDebe").text(tblSumCol("anutblPol", "anudataDebe").toFixed(2));
    $("#anudataTotHaber").text(tblSumCol("anutblPol", "anudataHaber").toFixed(2));
  }

  $(document).ready(function() {
    $(this).find('select:visible:first').focus();
    document.thisform.dtFec.value = '<?php echo $dtFec; ?>';
    cbNego.checked = 1;
    selBan.value = 1;


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

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

    // FOCUS NUMERO DE CHEQUE
    $("#selBan").focus(function() {
      limpiar();
      tblClear("tblPol");
      sumPol();
    });

    // FOCUS NUMERO DE CHEQUE
    $("#numNum").focus(function() {
      numNum.value="";
      limpiar();
      tblClear("tblPol");
      sumPol();
    });

    // VALID NUMERO
    $("#numNum")
    .blur(function (){
      setTimeout(function(){
        if (!$('#selBan').is(':focus') && $("#tblPol tbody").children().length == 0) {
          consultarCheques();
        }
      },0);
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-2-tab").click(); }
    })
    .change(function (){
      consultarCheques();
    });

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

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

    // FOCUS VALOR CHEQUE, BENEFICIARIO, CONCEPTO
    $("#numTot, #txtBene, #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 (chmod != 'cxp') {
        numNum.focus();
        alWarning({"msg":{"title":"GRABADO EN OTRO MODULO","text":"Este cheque no fue registrado en Cuentas por Pagar, intente borrarlo desde bancos"}});
        return true;
      }
      if (nuevo) {
        numNum.focus();
        alWarning({"msg":{"title":"NO REGISTRADO","text":"Este cheque no ha sido registrado."}});
        return true;
      }
      const fnT = function(){
        colPol = ["cta", "ctaNom", "debe", "haber"];

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

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

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

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

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

    // CLICK ANULAR
    $("#btnAnular").click(function (){
     // if (restriccion()) {return};
      if (chmod != 'cxp') {
        numNum.focus();
        alWarning({"msg":{"title":"GRABADO EN OTRO MODULO","text":"Este cheque no fue registrado en Cuentas por Pagar, intente borrarlo desde bancos"}});
        return true;
      }
      if (nuevo) {
        numNum.focus();
        alWarning({"msg":{"title":"NO REGISTRADO","text":"Este cheque no ha sido registrado."}});
        return true;
      }
      
      const fnT = function(){
        dtFecAnu.value = dateToday();
        txtConAnu.value = "ANULACION DE CHEQUE No. "+numNum.value;
        $('#modalfeca').modal('toggle');

      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

    // CLICK GUARDAR POLIZA DE ANULACION
    $("#anubtnGrabar").click(function (){
      anugrabarPoliza();
    });

    // CLICK GRABAR E IMPRIMIR
    $("#btnGuardarImprimir").click(function (){
      guardarPoliza(true);
    });
    
  });

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

      var totQ = round(numTot.value*numTcam.value,2);

      const parametros = new FormData();
      parametros.append("action", "generarPartida");
      parametros.append("cta", $('#selBan').find('option:selected').data('ctac'));

      $('#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();
            
            addRowPol("XXXXXXX", "Ingrese cuenta de gastos", totQ.toFixed(2), "0.00");
            // Cuenta BANCOS
            if (!isNullPer(jsonJS.ctaBanc)) {
              addRowPol(jsonJS.ctaBanc.cta, jsonJS.ctaBanc.cta_nom, "0.00", totQ.toFixed(2));
            } else {
              addRowPol("XXXXXXX", "Ingrese cuenta de Bancos", "0.00", totQ.toFixed(2));
            }
            sumPol();
            alClose();
          }
        }
      });
    });


  // CLICK CONTINUAR
  $("#btnContinuar").click(function () {

    txtThis = dtFecAnu;

    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,
      success: function (jsonPhp) {
        const jsonJS = JSON.parse(jsonPhp);

        if(jsonJS.error == true){
          alError(jsonJS);
        } else {
          if (jsonJS.ciemes === null) {
            mesCerrado = false;
            anuContinuar();
          } else { 
            if (jsonJS.ciemes.ciem_stat == "C") {
              mesCerrado = true;
              restriccionMesCerrado();
              $('#modalfeca').modal('toggle');
              numNum.focus();
            } else {
              mesCerrado = false;
              anuContinuar();
            } 
          }
        }
      }
    });

  });

  function anuContinuar() {
    anuselTipo.value="005";
    // Para vefificar correlativo de polizas
    const parametros = new FormData();
    parametros.append("action", "consultarCorrPol");

    parametros.append("anuselTipo", anuselTipo.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);
          anunumNum.value = jsonJS.corrpol.cp_num;
      }            
    });

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

    //const parametros = new FormData();

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

    parametros.append("totant", totant);
    parametros.append("selBanCod", selBan.value);
    parametros.append("numNum", numNum.value);
    parametros.append("dtFec", dtFec.value);
    parametros.append("dtFecAnu", dtFecAnu.value);
    parametros.append("txtConAnu", txtConAnu.value);
    parametros.append("tblPolAnt", tblPolAnt);
    
    //numNum.focus();

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

        if(jsonJS.error==true){
          alError(jsonJS);
        } else {
          alSuccess(jsonJS);
          // Para que pregunte fecha de anulacion
          $('#modalfeca').modal('toggle');
          //
          // Para que genere la poliza de reversion cuando es otro mes
          if (jsonJS.otromes) {
            anuselTipo.value="005";
            anudtFec.value=dtFecAnu.value;
            anutxtCon.value=txtConAnu.value;
            JSON.parse(tblPolAnt).forEach(function(i){
              addRowAnuPol(i.pold_cta, i.pold_ctan, i.pold_haber, i.pold_debe);
            });
            sumAnuPol();
            $('#modalpolAnu').modal('toggle');
          }                
          //
          numNum.value = "";
          limpiar();
          tblClear("tblPol");
          sumPol();
          numNum.focus();
        }
      }
    });
  }

  function anugrabarPoliza() {
    if (restriccion()) {return};

    colanuPol = ["cta", "ctaNom", "debe", "haber"];

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

    //parametros.append("nuevo", nuevo);
    parametros.append("anunumNum", anunumNum.value);
    parametros.append("anuselTipoCod", anuselTipo.value);
    parametros.append("anuselBanCod", anuselBan.value);
    parametros.append("anudtFec", anudtFec.value);
    parametros.append("anutxtCon", anutxtCon.value);
    parametros.append("anutblPol", tblToJson(colanuPol, "anutblPol", 5));

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

        if(jsonJS.error==true){
          alError(jsonJS);
        } else {
          if (jsonJS.msgWarning.error) {
            alWarning(jsonJS.msgWarning);
            alSuccess(jsonJS);
            numNum.value = "";
            limpiar();
            tblClear("anutblPol");
            sumAnuPol();
            $('#modalpolAnu').modal('toggle');
            numNum.focus();
          } else {
            alWarning(jsonJS.msgWarning);
          }
        }
      }
    }); 
  }



    // 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 INPUT
    $("form[name='thisformfac'] input, select, textarea").focus(function (){
      if (!($("input:visible:first").is(":focus")) && !($("#numNumI").is(":focus")) && !($("#txtNitI").is(":focus"))) {
        if (restriccionCamposVaciosiva()) {return};
      }
    });
*/

  // FOCUS PILL SHOW
  $('a[data-toggle="pill"]').on('show.bs.tab', function (e) {
      const target = e.target.attributes.href.value;
      const relatedTarget = e.relatedTarget.attributes.href.value;

      if (target == "#pills-11" && (isNullPer(txtSerieI.value) || isNullPer(numNumI.value))) {
        if(restriccionCamposVaciosiva(false)) {return false}
      } else if (target == "#pills-12" && (isNullPer(txtSerieI.value) || isNullPer(numNumI.value) || isNullPer(txtNitI.value))) {
        if(restriccionCamposVaciosiva()) {return false}
      }
  });

  // 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();
        }
      } else {
        (target == "#pills-2") ? dtFec.focus() : 0;
      }
    }
  });
</script>
