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

# QUERYS
$sDeptosi = "SELECT *, TRIM(dep_cod) AS dep_cod FROM deptosi";
$sSubdeptosi = "SELECT *, sdep_dep+sdep_cod AS sdep_codpas, TRIM(sdep_cod) AS sdep_cod FROM subdeptosi";
$sUnimed = "SELECT * FROM unimed";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["deptosi"] = $db->query($sDeptosi);
$select["subdeptosi"] = $db->query($sSubdeptosi);
$select["unimed"] = $db->query($sUnimed);
$db->close();
?>
<?php include_once('../includes/htmlOpen.php'); ?>
    <style type="text/css">
      .
    </style>
    <main class="main" style="">
      <?php 
        $li[0] = '<i class="fas fa-file-invoice"></i>';
        $li[1] = $_GET["opcNom"];
        include_once('../../../php/includes/ol.php');
      ?>

      <div class="container-as">
        <div class="row">
          <div class="col">
            <ul class="nav nav-pills mb-1" id="pills-tab" role="tablist">
              <li class="nav-item">
                <a class="nav-link active" id="pills-0-tab" data-toggle="pill" href="#pills-0" role="tab" aria-controls="pills-0" aria-selected="true">Mantenimiento</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" id="pills-1-tab" data-toggle="pill" href="#pills-1" role="tab" aria-controls="pills-1" aria-selected="true">Buscar Artículo</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 Cuenta</a>
              </li>
<!----              
              <li class="nav-item">
                <a class="nav-link" id="pills-3-tab" data-toggle="pill" href="#pills-3" role="tab" aria-controls="pills-3" aria-selected="true">Buscar Proveedor</a>
              </li>
--->              
            </ul>
            <div class="tab-content bg-transparent border-0" id="pills-tabContent">
              <div class="tab-pane fade show active" id="pills-0" role="tabpanel" aria-labelledby="pills-0-tab">

                <form action="" name="thisform" autocomplete="off" enctype="multipart/form-data">
                  <div class="form-row">
                    <div class="col-12 col-sm-9">

                      <div class="form-group">
                        <div class="form-row align-items-end">
                          <div class="col-md-4 col-lg-8">
                            <div class="form-row align-items-end">
                              <div class="col-4">
                                <label for="txtCod">Código</label>
                                <input type="text" class="form-control form-control-sm form-control-as" id="txtCod" placeholder="" maxlength="30">
                              </div>
                              <div class="col-4">
                                <label for="txtCodf">Código Fábrica</label>
                                <input type="text" class="form-control form-control-sm form-control-as limpiar" id="txtCodf" placeholder="" maxlength="30">
                              </div>
                            </div>
                            <div class="form-row align-items-end">
                              <div class="col-md-12">
                                <label for="txtDesc">Descripción Corta</label>
                                <input type="text" class="form-control form-control-sm form-control-as limpiar" id="txtDesc" placeholder="">
                              </div>
                            </div>
                            <div class="form-row align-items-end">
                              <div class="col-md-12">
                                <label for="txtDesd">Descripción Larga</label>
                                <textarea class="form-control form-control-sm form-control-as limpiar" id="txtDesd" rows="2"></textarea>
                              </div>
                            </div>
                          </div>
                          <div class="col-md-5 col-lg-4 text-center mt-3">
                            <div class="upload-btn-wrapper text-center" style="height: 200px; width: 75%;">
                              <img class="rounded-lg" name="imgArtic" width="100%" height="100%" style="object-fit: cover;" />
                              <input type="file" id="fileImg" name="file" onchange="imgSelect(this, document.thisform.imgArtic, imgPhoto); return false;" />
                            </div>
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-md-2">
                            <label for="txtCtaCos">Cuenta de Costos</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiar" id="txtCtaCos" placeholder="" maxlength="14">
                          </div>
                          <div class="col-md-4">
                            <label for="txtCtaCosNom">Nombre de Cuenta de Costos</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiar form-info" id="txtCtaCosNom" placeholder="Cuenta no definida" disabled>
                          </div>
<!---                          
                          <div class="col-md-2">
                            <label for="txtCtaInv">Cuenta Inventario</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiar" id="txtCtaInv" placeholder="" maxlength="14">
                          </div>
                          <div class="col-md-4">
                            <label for="txtCtaInvNom">Nombre de Cuenta de Inventarios</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiar form-info" id="txtCtaInvNom" placeholder="Cuenta no definida" disabled>
                          </div>
--->
                        </div>
                        <div class="form-row align-items-end">
<!---                          
                          <div class="col-md-2">
                            <label for="txtCtaVen">Cuenta de Ventas</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiar" id="txtCtaVen" placeholder="" maxlength="14">
                          </div>
                          <div class="col-md-4">
                            <label for="txtCtaVenNom">Nombre de Cuenta de Ventas</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiar form-info" id="txtCtaVenNom" placeholder="Cuenta no definida" disabled>
                          </div>
--->                          
                          <div class="col-md-8">
                            <label for="txtProv">Generico</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiar" id="txtProv" placeholder="">
                          </div>
<!--                          
                          <div class="col-md-4">
                            <label for="txtProvNom">Nombre Proveedor</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiar form-info" id="txtProvNom" placeholder="Juan Ejemplo" disabled>
                          </div>
--->                          
                          <div class="col-3">
                            <label for="txtMarca">Marca</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiar" id="txtMarca" placeholder="">
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-sm-6 col-md-3">
                            <label for="selDepto">Familia</label>
                            <select class="form-control form-control-sm form-control-as" name="selDepto" id="selDepto">
                              <?php
                                while ($rec = $db->fetchAssoc($select['deptosi'])) {
                                  echo  "<option value={$rec['dep_cod']}>".utf8_encode($rec['dep_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-sm-6 col-md-3">
                            <label for="selSubDepto">Sub-Familia</label>
                            <select class="form-control form-control-sm form-control-as" name="selSubDepto" id="selSubDepto">
                              <?php
                                while ($rec = $db->fetchAssoc($select['subdeptosi'])) {
                                  echo  "<option data-dep={$rec['sdep_dep']} value={$rec['sdep_cod']}>".utf8_encode($rec['sdep_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-sm-6 col-md-3">
                            <label for="selMedida">Unidad de Medida</label>
                            <select class="form-control form-control-sm form-control-as" name="selMedida" id="selMedida">
                              <?php
                                while ($rec = $db->fetchAssoc($select['unimed'])) {
                                  echo  "<option value={$rec['um_cod']}>".utf8_encode($rec['um_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-sm-6 col-md-3">
                            <label for="numMini">Minimo</label>
                            <input type="number" class="form-control form-control-sm form-control-as limpiar dec-2" id="numMini" placeholder="">
                          </div>
                          <div class="col-sm-6 col-md-3">
                            <label for="numMaxi">Maximo</label>
                            <input type="number" class="form-control form-control-sm form-control-as limpiar dec-2" id="numMaxi" placeholder="">
                          </div>
                        </div>
                        <div class="form-row align-items-end">
                          <div class="col-2">
                            <label for="txtCodBarr">Código de Barras</label>
                            <input type="text" class="form-control form-control-sm form-control-as limpiar" id="txtCodBarr" placeholder="" maxlength="30">
                          </div>
                          <div class="col-2">
                            <button type="button" class="btn btn-primary" id="btnAddDetbarr">
                              <i class="fas fa-plus-circle"></i> Agregar
                            </button>
                          </div>
                          <div class="col-2">
                            <label class="text-success" for="numPre1">Precio1 en Q.</label>
                            <input type="number" class="form-control form-control-sm form-control-as limpiar dec-2" id="numPre1" placeholder="0.00" min="0">
                          </div>
                          <div class="col-2">
                            <label class="text-success" for="numPre2">Precio2 en Q.</label>
                            <input type="number" class="form-control form-control-sm form-control-as limpiar dec-2" id="numPre2" placeholder="0.00" min="0">
                          </div>
                          <div class="col-2">
                            <label class="text-success" for="numCosp">Costo Uniario Q.</label>
                            <input type="number" class="form-control form-control-sm form-control-as limpiar dec-2" id="numCosp" placeholder="0.00" min="0">
                          </div>
<!---                          
                          <div class="col-2">
                            <label class="text-success" for="numCosr">Costo Ult/Compra (sin Iva)Q.</label>
                            <input type="number" class="form-control form-control-sm form-control-as limpiar dec-2" id="numCosr" placeholder="0.00" min="0">
                          </div>
--->                        

                        </div>
                        <div class="form-group">
                          <h3 class="text-light"></h3>
                          <div class="form-row">
                            <div class="col-md-3">
                              <div class="table-responsive">
                                <table class="table table-hover table-bordered table-dark table-sm" id="tblDetbarr">
                                  <thead>
                                    <tr>
                                      <th scope="col" class="text-center ignore" width="10">ACCIONES</th>
                                      <th scope="col" class="text-center" width="200">CODIGO BARRAS</th>
                                    </tr>
                                  </thead>
                                  <tbody>
                                  </tbody>
                                  <tfoot>
                                    <th scope="col" class="ignore"></th>
                                    <th scope="col"></th>
                                  </tfoot>
                                </table>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="form-row mt-3">
                          <div class="col-6 col-lg-3">
<!---                            
                            <h4 class="text-success">Precio Unitario</h4>
                            <div class="form-row align-items-end">
                              <div class="col-12">
                                <label class="text-success" for="numPre1">Precio en Q.</label>
                                <input type="number" class="form-control form-control-sm form-control-as limpiar dec-2" id="numPre1" placeholder="0.00" min="0">
                              </div>
                              <div class="col-12">
                                <label class="text-success" for="numPre2">Precio 2 en Q.</label>
                                <input type="number" class="form-control form-control-sm form-control-as limpiar dec-2" id="numPre2" placeholder="0.00" min="0">
                              </div>
                              <div class="col-12">
                                <label class="text-success" for="numPre3">Precio 3 en Q.</label>
                                <input type="number" class="form-control form-control-sm form-control-as limpiar dec-2" id="numPre3" placeholder="0.00" min="0">
                              </div>
                              <div class="col-12">
                                <label class="text-success" for="numPre4">Precio 4 en Q.</label>
                                <input type="number" class="form-control form-control-sm form-control-as limpiar dec-2" id="numPre4" placeholder="0.00" min="0">
                              </div>
                            </div>
---->                              

                          </div>
<!---                          
                          <div class="col-6 col-lg-3">
                            <h4 class="text-info">Costos</h4>
                            <div class="form-row align-items-end">
                              <div class="col-12">
                                <label class="text-info" for="numCosp">Promedio</label>
                                <input type="number" class="form-control form-control-sm form-control-as limpiar dec-5" id="numCosp" placeholder="0.00" min="0" disabled>
                              </div>
                              <div class="col-12">
                                <label class="text-info" for="numCosr">Última Compra</label>
                                <input type="number" class="form-control form-control-sm form-control-as limpiar dec-5" id="numCosr" placeholder="0.00" min="0" disabled>
                              </div>
                              <div class="col-12">
                                <label class="text-info" for="numCosa">Anterior</label>
                                <input type="number" class="form-control form-control-sm form-control-as limpiar dec-5" id="numCosa" placeholder="0.00" min="0" disabled>
                              </div>
                            </div>
                          </div>
                          <div class="col-6 col-lg-3">
                            <h4 class="text-primary">Fechas</h4>
                            <div class="form-row align-items-end">
                              <div class="col-9">
                                <label class="text-primary" for="dtUent">Última Entrada</label>
                                <input type="date" class="form-control form-control-sm form-control-as limpiar" id="dtUent" placeholder="" disabled>
                              </div>
                              <div class="col-9">
                                <label class="text-primary" for="dtUsal">Última Salida</label>
                                <input type="date" class="form-control form-control-sm form-control-as limpiar" id="dtUsal" placeholder="" disabled>
                              </div>
                            </div>
                          </div>
--->                          
                        </div>

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

                        <div class="form-row align-items-center">
                          <div class="col-md-4 text-center">
                            <label class="pr-1">Tipo</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crBienSer1" name="crBienSer" class="custom-control-input" value="B">
                              <label class="custom-control-label" for="crBienSer1">Bien</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crBienSer2" name="crBienSer" class="custom-control-input" value="S">
                              <label class="custom-control-label" for="crBienSer2">Servicio</label>
                            </div>
                          </div>
                          <div class="col-md-4 text-center">
                            <label class="pr-1">Exento</label><br>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crExen1" name="crExen" class="custom-control-input" value="S">
                              <label class="custom-control-label" for="crExen1">Si</label>
                            </div>
                            <div class="custom-control custom-radio custom-control-inline">
                              <input type="radio" id="crExen2" name="crExen" class="custom-control-input" value="N">
                              <label class="custom-control-label" for="crExen2">No</label>
                            </div>
                          </div>
                          <div class="col-md-4 text-center">
                            <div class="custom-control custom-switch">
                              <input type="checkbox" class="custom-control-input" name="cbBloqueado" id="cbBloqueado">
                              <label class="custom-control-label" for="cbBloqueado">Bloqueado</label>
                            </div>
                          </div>
                        </div>

                      </div>

                    </div>
                    <div class="col-12 col-lg-3">
                      <div class="form-group position-fixed-xs">
                        <div class="form-row">
                          <div class="col-12 mt-2">
                            <button class="btn btn-success btn-block" style='font-size:20px;' id="btnGuardar" type="button">Guardar</button>
                          </div>
                          <div class="col-12 mt-2">
                            <button class="btn btn-danger btn-block" style='font-size:20px;' id="btnBorrar" type="button">Borrar</button>
                          </div>
                        </div>
                        <div class="form-row">

                        </div>

                        <div class="form-row-12">
                          <div class="col-12 mt-4">
                            <div class="table-responsive">
                              <table class="table table-hover table-bordered table-dark table-md" style="font-size: 18px;" id="tblExi">
                                <thead>
                                  <tr>
                                    <th scope="col" class="text-center" width="100">UBICACIÓN</th>
                                    <th scope="col" class="text-center" width="10">EXISTENCIA</th>
                                  </tr>
                                </thead>
                                <tbody>
                                </tbody>
                                <tfoot>
                                  <th scope="col" class="text-right">TOTAL</th>
                                  <th scope="col" id="dataTotExist" class="text-right">0.00</th>
                                </tfoot>
                              </table>
                            </div>
                          </div>
                        </div>

                      </div>

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

              </div>

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

              <div class="tab-pane fade" id="pills-2" role="tabpanel" aria-labelledby="pills-2-tab">
                <?php
                  $a='0';
                  $b='2';
                  include('../busCuentasMov/index.html');
                ?>
              </div>
<!---
              <div class="tab-pane fade" id="pills-3" role="tabpanel" aria-labelledby="pills-3-tab">
                <?php
                  $a='0';
                  $b='3';
                  $provcpNomTF=true;
                  include('../busProvcp/index.html');
                ?>
              </div>
--->              
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var inputArtic = "txtCod";
  var inputCtaMov = "txtCtaCos";
  var inputProvcp = "txtProv";
  var cospant = 0;

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

  const txtCod = document.thisform.txtCod;
  const crExen = document.thisform.crExen;
  const crBienSer = document.thisform.crBienSer;
  const colDetbarr = ["acciones", "codbarr"];

  function restriccion(consultar = false){
    if (!consultar) {
      if (isNullPer(txtCod.value)) {
        txtCod.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el CÓDIGO"}});
        return true;
      }
    } else {
      if (isNullPer(txtCod.value)) {
        return true;
      }
    }
    return false;
  }

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

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

  function limpiar(){
    $('.limpiar').val('');
    selDepto.value = '9999';
    selSubDepto.value = '9999';
    selMedida.value = $("#selMedida option:first").val();
    txtCodBarr.value = "";
    cbBloqueado.checked = 0;
    crExen.value = 'N';
    crBienSer.value = 'B';
    fileImg.value = "";
    numMini.value=(0).toFixed(2);
    numMaxi.value=(0).toFixed(2);
    txtCtaCos.value="50102";
    txtCtaCosNom.value="Compras de Medicamentos y Abarrotes";
/*    numCosp.value=(0).toFixed(5);
    numCosr.value=(0).toFixed(5);
    numCosa.value=(0).toFixed(5);
    dtUent.value = dateToday();
    dtUsal.value = dateToday();  */
    tblClear("tblExi");
    sumExi();
  }

  function sumExi(){
    $("#dataTotExist").text(tblSumCol("tblExi", "dataExist").toFixed(2));
  }

  function addRowExi(nom, exist){
    const row = "<tr>"
                +"<td id='dataNom'>"+nom+"</td>"
                +"<td id='dataExist' class='text-right'>"+exist+"</td>"
              +"</tr>";
    $("#tblExi tbody").append(row);
  }

  function addRowDetbarr(codbarr){
    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='btnDelDetbarr'><i class='fas fa-trash-alt'></i></button>"
                  +"</div>"
                +"</td>"
                +"<td id='dataCodbarr'>"+codbarr+"</td>"
                +"</tr>";
    $("#tblDetbarr tbody").append(row);
  }

  $(document).ready(function() {
    $(this).find('input:visible:first').focus();
    imgArtic.src = imgPhoto;
    limpiar();

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

    $("#txtCod").focus(function() {
      this.value = "";
      imgArtic.src = imgPhoto;
      limpiar();
    })

    // VALID DEPARTAMENTOS
    $("#selDepto").change(function(){
      var filter = this.value;
      if (filter=='9999') {
        $('#selSubDepto option').show();
        if (nuevo) {
          selSubDepto.value = $("#selSubDepto option:first").val();
        }
      } else {
        $('#selSubDepto option').each(function() {
          ($(this).data('dep')==filter) ? $(this).show() : $(this).hide();
        });
        if (nuevo) {
          $('#selSubDepto option').each(function() {
            if ($(this).data('dep')==filter) {
              selSubDepto.value = $(this).val();
              return false;
            }
          });
        }
      }
      console.log("Departamento: "+selDepto.value);
    });

    // FOCUS DESCRIPCION LARGA
    $("#txtDesd").focus(function(){
      if (isNullPer(txtDesd.value)) {
        txtDesd.value = txtDesc.value;
      }
    });

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

    // CLICK ADD CODIGO BARRAS
    $("body").on("click", "#btnAddDetbarr", function () {
      if (isNullPer(txtCodBarr.value)) {
        txtCodBarr.focus();
        alWarning({"msg":{"title":"NO INGRESO CODIGO DE BARRAS","text":"Debe ingresar el codigo de barras"}});
      }  
      addRowDetbarr(txtCodBarr.value);
      txtCodBarr.value = "";
      txtCodBarr.focus();
    });


    // VALID PROVEEDOR
/*    
    $("#txtProv")
    .focus(function() {
      inputProvcp = $(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-3-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 (restriccionProvcpCod()) {return};

      const parametros = new FormData();
      parametros.append("action", "consultarProvcp");
      parametros.append("txtProv", 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.provcp === null) {
              txtGetValue.value = "";
              alErrorFocusTimer({"msg":{"type":"error","title":"No existe","text":"El proveedor "+txtThis.value+" no ha sido registrado", "ok":"Aceptar", "timer":timeOutErrorSm}}, txtThis);
            } else {
              txtGetValue.value = jsonJS.provcp.pro_nom;
              (pressEnter) ? alClose() : alCloseFocus(txtNext);
            }
            pressEnter = false;
            blurOn(txtThis, txtGetValue);
          }
        }
      });
    });

*/

    // VALID CUENTAS
    $("input[id*='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-2-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("txtCta", 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);
          }
        }
      });
    });

    // VALID CODIGO
    $("form[name='thisform'] #txtCod")
    .focus(function() {
      inputArtic = $(this).attr('id');
      tblClear("tblDetbarr");
    })
    .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-1-tab").click(); }
    })
    .change(function (){
      if (restriccion(true)) {return};

      txtNext = txtCodf;
      txtCod.value = txtCod.value.toUpperCase();

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

      txtNext.focus()

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

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            limpiar();
            
            if (jsonJS.artic === null) {
              nuevo = true;
              imgArtic.src = imgPhoto;
              cospant = 0;
            } else {
              nuevo = false;
              txtCod.value = jsonJS.artic.art_cod;
              txtCodf.value = jsonJS.artic.art_codf;
              txtDesc.value = jsonJS.artic.art_desc;
              txtDesd.value = jsonJS.artic.art_desd;
              txtCtaCos.value = jsonJS.artic.art_ctacos;
              txtCtaCosNom.value = jsonJS.artic.art_ctacosnom;
/*              txtCtaInv.value = jsonJS.artic.art_ctainv;
              txtCtaInvNom.value = jsonJS.artic.art_ctainvnom;
              txtCtaVen.value = jsonJS.artic.art_ctaven;
              txtCtaVenNom.value = jsonJS.artic.art_ctavennom;  */
              txtProv.value = jsonJS.artic.art_prov;
//              txtProvNom.value = jsonJS.artic.art_provnom;
              txtMarca.value = jsonJS.artic.art_marca;
              selDepto.value = jsonJS.artic.art_dep;
              selSubDepto.value = jsonJS.artic.art_subdep;
              selMedida.value = jsonJS.artic.art_medi;
              numPre1.value = jsonJS.artic.art_pre1;
              numPre2.value = jsonJS.artic.art_pre2;
              numCosp.value = jsonJS.artic.art_cosp;
              cospant = jsonJS.artic.art_cosp;
//              numCosr.value = jsonJS.artic.art_cosr;
              /*numPre2.value = jsonJS.artic.art_pre2;
              numPre3.value = jsonJS.artic.art_pre3;
              numPre4.value = jsonJS.artic.art_pre4;
              numCosp.value = jsonJS.artic.art_cosp;
              numCosr.value = jsonJS.artic.art_cosr;
              numCosa.value = jsonJS.artic.art_cosa;  */
              crBienSer.value = jsonJS.artic.art_bienser;
              crExen.value = jsonJS.artic.art_exen;
              cbBloqueado.checked = Number(jsonJS.artic.art_bloqueado);
              numMini.value = jsonJS.artic.art_mini;
              numMaxi.value = jsonJS.artic.art_maxi;
//              dtUent.value = jsonJS.artic.art_uent;
//              dtUsal.value = jsonJS.artic.art_usal;
              jsonJS.exiart.forEach(function(i){
                addRowExi(i.bod_nom, i.ea_existb);
              });
              sumExi();

              jsonJS.cod_barr.forEach(function(i){
                addRowDetbarr(i.cb_barr);
              });

              imgExist(imgArtic, jsonJS.imgArtic, imgPhoto);

              $("#selDepto").trigger("change");
            }
            (pressEnter) ? alClose() : alCloseFocus(txtNext);
            pressEnter = false;
          }
        }
      });
    });

    // CLICK GUARDAR
    $("#btnGuardar").click(function (){
      if (restriccion()) {return};
      if (Number(numCosp.value) >= Number(numPre1.value) || Number(numCosp.value) >= Number(numPre2.value)) {
        alWarning({"msg":{"title":"COSTO MAYOR A ALGUNO DE LOS PRECIOS DE VENTA","text":"El costo, no puede ser mayor al precio de venta, revise"}});
        return;
      }
/*      
      if (numCosp.value >= numPre1.value || numCosp.value >= numPre2.value) {
        alWarning({"msg":{"title":"COSTO PROMEDIO ES MAYOR A ALGUNO DE LOS PRECIOS DE VENTA","text":"El costo, no puede ser mayor al precio de venta, revise"}});
        return;
      }
*/
      const parametros = new FormData();
      parametros.append("action", "guardar");

      parametros.append("file", document.thisform.file.files[0]);
      parametros.append("nuevo", nuevo);
      parametros.append("txtCod", txtCod.value);
      parametros.append("txtCodf", txtCodf.value);
//      parametros.append("txtCodBarr", txtCodBarr.value);
      parametros.append("txtDesc", txtDesc.value);
      parametros.append("txtDesd", txtDesd.value);
      parametros.append("txtCtaCos", txtCtaCos.value);
      parametros.append("txtCtaInv", "");
        //txtCtaInv.value);
      parametros.append("txtCtaVen", "");
        //txtCtaVen.value);
      parametros.append("txtProv", txtProv.value);
      parametros.append("txtMarca", txtMarca.value);
      parametros.append("selDeptoCod", selDepto.value);
      parametros.append("selSubDeptoCod", selSubDepto.value);
      console.log("Depto:  "+selDepto.value+"  Subd depto:  "+selSubDepto.value)
      parametros.append("selMedidaCod", selMedida.value);
      parametros.append("numPre1", numPre1.value);
      parametros.append("numPre2", numPre2.value);
      parametros.append("numPre3", 0);
      //numPre3.value);
      parametros.append("numPre4", 0);
        //numPre4.value);
      parametros.append("numCosp", numCosp.value);
      parametros.append("numCosr", 0);
        //numCosr.value);
      parametros.append("numCosa", 0);
      parametros.append("cospant", cospant);
        //numCosa.value);
      parametros.append("numMini", numMini.value);
      parametros.append("numMaxi", numMaxi.value);
      parametros.append("crBienSer", crBienSer.value);
      parametros.append("crExen", crExen.value);
      parametros.append("cbBloqueado", cbBloqueado.checked);
      parametros.append("tblDetbarr", tblToJson(colDetbarr, "tblDetbarr", 0));


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

          if(jsonJS.error==true){
            alError(jsonJS);
          } else {
            alSuccess(jsonJS);
            limpiar();
            imgArtic.src = imgPhoto;
            txtCod.value = "";
            txtCod.focus();
          }
        }
      });
    });

    // CLICK BORRAR
    $("#btnBorrar").click(function (){
      if (restriccion()) {return};
      const fnT = function(){
        const parametros = new FormData();
        parametros.append("action", "borrar");
        parametros.append("txtCod", txtCod.value);
        
        $.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);
              limpiar();
              imgArtic.src = imgPhoto;
              txtCod.value = "";
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

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

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

      if ((target == "#pills-0" && isNullPer(txtCod.value)) || target != "#pills-0") {
        $(target+' input:visible:first').focus();
      } else {
        (relatedTarget == "#pills-1") ? $('#txtCodf').focus() : 0;
        (relatedTarget == "#pills-2") ? $('#'+inputCtaMov).focus() : 0;
        (relatedTarget == "#pills-3") ? $('#'+inputProvcp).focus() : 0;
      }
    //}
  });

</script>