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

$pCaja = $_SESSION['pCaja'];

# QUERYS
$sTipov = "SELECT 
            TRIM(tv.tv_cod) AS tv_cod,
            TRIM(tv.tv_nom) AS tv_nom,
            TRIM(tv.tv_abrev) AS tv_abrev,
            TRIM(tv.tv_codasiste) AS tv_codasiste,
            tv_librosn,
            tv_impues,
            TRIM(td.td_cod) AS td_cod
           FROM tipov tv LEFT JOIN tipodoci td ON tv.tv_cod=td.td_relatv WHERE tv_pone='P' AND LEFT(tv_cod,1)='5'";
$sVendedor = "SELECT * FROM vendedor where vend_caja='$pCaja' OR vend_caja='999'";
$sBodegas = "SELECT * FROM bodegas";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["tipov"] = $db->query($sTipov);
$select["vendedor"] = $db->query($sVendedor);
$select["bodegas"] = $db->query($sBodegas);
$db->close();

$anoTrab=date("Y", strtotime($_SESSION['empFtrab']));
$mesTrab=date("m", strtotime($_SESSION['empFtrab']));
?>
<?php include_once('../includes/htmlOpenPov.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');
      ?>

      <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-9">
                      <div class="form-group">

                        <div class="form-row">
                          <div class="col-3">
                            <label class="font-size-md" for="selTipo">Tipo</label>
                            <select class="form-control form-control-md form-control-as" name="selTipo" id="selTipo" disabled>
                              <?php
                                while ($rec = $db->fetchAssoc($select['tipov'])) {
                                  //echo  "<option value={$rec['tv_cod']} data-librosn={$rec['tv_librosn']} data-relatd={$rec['td_cod']} data-impues={$rec['tv_impues']} data-abrev={$rec['tv_abrev']}>".utf8_encode($rec['tv_nom']).'</option>';
                                  echo  '<option value="'.$rec['tv_cod'].'" data-librosn="'.$rec['tv_librosn'].'" data-relatd="'.$rec['td_cod'].'" data-impues="'.$rec['tv_impues'].'" data-seriesn="'.$rec['tv_seriesn'].'" data-abrev="'.$rec['tv_abrev'].'">'.utf8_encode($rec['tv_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                          <div class="col-3">
                            <label class="font-size-md" for="numInterno">ID Interno</label>
                            <input type="text" class="form-control form-control-md form-control-as" id="numInterno">
                          </div>
                          <div class="col-3">
                            <label class="font-size-md" for="txtSerie">Serie</label>
                            <input type="text" class="form-control form-control-md form-control-as" id="txtSerie" maxlength="20" disabled>
                          </div>
                          <div class="col-3">
                            <label class="font-size-md" for="numNum">Número</label>
                            <input type="number" class="form-control form-control-md form-control-as dec-0" id="numNum" placeholder="0" disabled>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-6 col-md-4">
                            <label class="font-size-md" for="dtFec">Fecha del Documento</label>
                            <input type="date" class="form-control form-control-md form-control-as" id="dtFec" placeholder="" disabled>
                          </div>
                          <div class="col-md-8">
                            <label class="font-size-md" for="selBodSal">Bodega Salida</label>
                            <select class="form-control form-control-md form-control-as" name="selBodSal" id="selBodSal" disabled>
                              <?php
                                while ($rec = $db->fetchAssoc($select['bodegas'])) {
                                  echo  "<option value={$rec['bod_cod']}>".utf8_encode($rec['bod_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-md-3">
                            <label class="font-size-md" for="txtCliCod">Código Cliente</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtCliCod" disabled>
                          </div>
                          <div class="col-md-9">
                            <label class="font-size-md" for="txtCliNom"></label>
                            <input type="text" class="form-control form-control-md form-control-as form-info limpiar" id="txtCliNom" disabled>
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-md-9">
                            <label class="font-size-md" for="txtNomFac">A nombre de</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtNomFac" disabled>
                          </div>
                          <div class="col-md-3">
                            <label class="font-size-md" for="txtNit">NIT</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtNit" disabled>
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-12">
                            <label class="font-size-md" for="txtDir">Dirección</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtDir" disabled>
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-md-4">
                            <label class="font-size-md" for="txtTel">Teléfono</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtTel" disabled>
                          </div>
                          <div class="col-4 col-md-2">
                            <label class="font-size-md" for="numDcre">Días Crédito</label>
                            <input type="number" class="form-control form-control-md form-control-as dec-0 limpiar" id="numDcre" placeholder="0" disabled>
                          </div>
                          <div class="col-8 col-md-2">
                            <label class="font-size-md" for="numTcam">Tipo de Cambio</span></label>
                            <input type="number" class="form-control form-control-md form-control-as dec-5" id="numTcam" placeholder="0.00000" disabled>
                          </div>
                          <div class="col-md-4">
                            <label class="font-size-md" for="selVend">Vendedor</label>
                            <select class="form-control form-control-md form-control-as" name="selVend" id="selVend" disabled>
                              <?php
                                while ($rec = $db->fetchAssoc($select['vendedor'])) {
                                  echo  '<option value="'.TRIM($rec['vend_cod']).'">'.utf8_encode($rec['vend_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
                        </div>

                        <div class="form-row align-items-end">
                          <div class="col-md-12">
                            <label class="font-size-md" for="txtMotAnu">Motivo de Anulación</label>
                            <input type="text" class="form-control form-control-md form-control-as limpiar" id="txtMotAnu">
                          </div>
                        </div>
                      </div>

                      <div class="form-group">
                        <div class="form-row">
                        </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-md" id="tblDet">
                                <thead>
                                  <tr>
                                    <th scope="col" class="text-center ignore" width="40">ACCIONES</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" width="90">CODIGO</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" width="200">DESCRIPCIÓN</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" width="70">MEDIDA</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" width="70">FEC/VENC</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" width="70">CANTIDAD</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" width="70">PRECIO UNIT.</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" width="90">SUB-TOTAL</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" width="50">DESCU. %</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" width="90">VALOR DESCU.</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" width="90">TOTAL</th>
                                    <th scope="col" class="text-center" style="font-size:16px;" width="10">EXENTO</th>
                                  </tr>
                                </thead>
                                <tbody>
                                </tbody>
                                <tfoot>
                                  <th scope="col" class="ignore"></th>
                                  <th scope="col"></th>
                                  <th scope="col"></th>
                                  <th scope="col"></th>
                                  <th scope="col"></th>
                                  <th scope="col"></th>
                                  <th scope="col" class="text-right" style="font-size:26px;">Totales</th>
                                  <th scope="col" id="dataTotSub" class="text-right" style="font-size:18px;">0.00</th>
                                  <th scope="col"></th>
                                  <th scope="col" id="dataTotDescuv" class="text-right" style="font-size:18px;">0.00</th>
                                  <th scope="col" id="dataTotTot" class="text-right" style="font-size:18px;">0.00</th>
                                </tfoot>
                              </table>
                            </div>
                          </div>
                        </div>
                      </div>

                    </div>
                    <div class="col-12 col-sm-3">
                      <div class="form-group position-fixed-sm">

                        <div class="form-row align-items-center ml-2">
                          <div class="col-6">
                            <label class="text-success" for="numSub" style="font-size:25px; font-weight:bold;">Sub-Total</label>
                          </div>
                          <div class="col-6">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar text-right" style="font-size:25px; font-weight:bold;" id="numSub" placeholder="0.00" min="0" disabled>
                          </div>
                          <div class="col-6">
                            <label class="text-danger" for="numDescuv" style="font-size:25px; font-weight:bold;">Descuento</label>
                          </div>
                          <div class="col-6">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar text-right" style="font-size:25px; font-weight:bold;" id="numDescuv" placeholder="0.00" min="0" disabled>
                          </div>
                          <div class="col-6">
                            <label class="text-success" for="numTot" style="font-size:35px; font-weight:bold;">Total</label>
                          </div>
                          <div class="col-6">
                            <input type="number" class="form-control form-control-sm form-control-as form-info limpiar text-right" style="font-size:33px; font-weight:bold;" id="numTot" placeholder="0.00" min="0" disabled>
                          </div>
                        </div>

                        <div class="form-row">
                          <div class="col-12 mt-2">
                            <button class="btn btn-danger btn-block" style="font-size:35px; font-weight:bold;" id="btnAnular" type="button">Anular</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 mesCerrado = false;

  var tblDetAnt;
  var tblPolAnt;

  var inputCtaMov = "txtCta";
  var inputClienccCod = "txtCliCod";
  var inputArtic = "txtCodd";

  var cliCta = "";
  var medid = "";
  var cantAnt = 0;
  var bienser = "";
  var bienserm = "";
  var DocumentGUID = "";

  var pcaja = '<?php echo $_SESSION['pCaja']; ?>';
  
  const colDet = ["acciones", "codd", "descd", "medid", "unimed", "loted", "fvenced", "cantd", "preud", "subd", "descud", "descuvd", "totd", "exensnd", "bienserd", "ctacos", "cosud"];

  // Valores
  var tot = 0;
  var ret = 0;
  var reti = 0;
  var iva = 0;
  var sub = 0;


  function limpiar() {
    DocumentGUID = "";
    ctaCli = "";
    $(".limpiar").val("");
    dtFec.value = dateToday();
    numTcam.value = (1).toFixed(5);

    tblClear("tblDet");
    sumDet();
  }

  function addRowDetao(codd, descd, medid, unimed, loted, fvenced, cantd, preud, subd, descud, descuvd, totd, exentod, bienserd, ctacos, cosud){
    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='btnDelDet'><i class='fas fa-trash-alt'></i></button>"
                    +"<button type='button' class='btn btn-primary btn-sm btn-actions' id='btnEditDet' data-toggle='modal' data-target='#modalDet'><i class='fas fa-edit'></i></button>"
                  +"</div>"
                +"</td>"
                +"<td id='dataCodd' style='font-size:16px;'>"+codd+"</td>"
                +"<td id='dataDescd' style='font-size:16px;'>"+descd+"</td>"
                +"<td id='dataMedid' class='d-none' style='font-size:16px;'>"+medid+"</td>"
                +"<td id='dataUnimed' style='font-size:16px;'>"+unimed+"</td>"
                +"<td id='dataLoted' class='d-none' style='font-size:16px;'>"+loted+"</td>"
                +"<td id='dataFvenced' class='text-center' style='font-size:16px;'>"+fvenced+"</td>"
                +"<td id='dataCantd' class='text-right' style='font-size:16px;'>"+cantd+"</td>"
                +"<td id='dataPreud' class='text-right' style='font-size:16px;'>"+preud+"</td>"
                +"<td id='dataSubd' class='text-right' style='font-size:16px;'>"+subd+"</td>"
                +"<td id='dataDescud' class='text-right' style='font-size:16px;'>"+descud+"</td>"
                +"<td id='dataDescuvd' class='text-right' style='font-size:16px;'>"+descuvd+"</td>"
                +"<td id='dataTotd' class='text-right' style='font-size:16px;'>"+totd+"</td>"
                +"<td id='dataExentod' class='text-center' style='font-size:16px;'>"+exentod+"</td>"
                +"<td id='dataBienserd' class='d-none'>"+bienserd+"</td>"
                +"</tr>";
    $("#tblDet tbody").append(row);
  }

  function sumDet(){
    $("#tblDet #dataTotSub").text(tblSumCol("tblDet", "dataSubd").toFixed(2));
    $("#tblDet #dataTotDescuv").text(tblSumCol("tblDet", "dataDescuvd").toFixed(2));
    $("#tblDet #dataTotTot").text(tblSumCol("tblDet", "dataTotd").toFixed(2));

    numSub.value=$("#tblDet #dataTotSub").text();
    numDescuv.value=$("#tblDet #dataTotDescuv").text();
    numTot.value=$("#tblDet #dataTotTot").text();
  }

  function sumCantDetAnt(cod){
    acumCant = 0;
    JSON.parse(tblDetAnt).forEach(function(i){
      if (i.factd_cod==cod) {
        acumCant += parseFloat(i.factd_cant);
      }
    });
    return acumCant;
  }

  function sumCant(cod) {
    acumCant = 0;
    $("#tblDet").find('tbody tr').each(function () {
      if ($(this).find('#dataCodd').text() == cod) {
        acumCant += parseFloat($(this).find('#dataCantd').text());
      }
    });
    return acumCant;
  }

  function getElements(locationPHP) {
    return window.location.origin+window.location.pathname+locationPHP+".php";
  }


  $(document).ready(function() {
    $(this).find('input:visible:first').focus();
    //selTipo.value = "020";
    date = new Date();
    dtFec.value = dateToday();
    numTcam.value = (1).toFixed(5);

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


    function calcularTotPorcentaje(txtThis) {
      const subFijo = (txtThis.substr(-1)=='m') ? 'm' : '';

      const cant = $('#numCantd'+subFijo);
      const preu = $('#numPreud'+subFijo);
      const sub = $('#numSubd'+subFijo);
      const descu = $('#numDescud'+subFijo);
      const descuv = $('#numDescuvd'+subFijo);
      const tot = $('#numTotd'+subFijo);

      sub.val(round(cant.val()*preu.val(),5).toFixed(2));
      descuv.val(round((sub.val()*descu.val())/100,5).toFixed(2));
      tot.val(round(sub.val()-descuv.val(),5).toFixed(2));
    }

    function calcularTotValor(txtThis) {
      const subFijo = (txtThis.substr(-1)=='m') ? 'm' : '';

      const cant = $('#numCantd'+subFijo);
      const preu = $('#numPreud'+subFijo);
      const sub = $('#numSubd'+subFijo);
      const descu = $('#numDescud'+subFijo);
      const descuv = $('#numDescuvd'+subFijo);
      const tot = $('#numTotd'+subFijo);

      sub.val(round(cant.val()*preu.val(),5).toFixed(2));
      descu.val(round((descuv.val()*100)/sub.val(),5).toFixed(2));
      tot.val(round(sub.val()-descuv.val(),5).toFixed(2));
    }

    // FOCUS INPUT
    $("form[name='thisform'] input, select, textarea, #btnPartida").focus(function (){
      if (!($("input:visible:first").is(":focus")) && !($("#numNum").is(":focus")) && !($("#selTipo").is(":focus"))) {
//        if (restriccionCamposVacios()) {return};
      }
    });

    // VALID TIPOV
    $("#selTipo")
    .init(function() {
      const parametros = new FormData();
      parametros.append("action", "consultarCaja");

      $.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 {
            if (jsonJS.caja === null) {
              alWarning({"msg":{"title":"NO EXISTE","text":"Este codigo no ha sido registrado"}});
              return true;
            } else {
              selTipo.value = jsonJS.caja.caj_tipofac;
              selBodSal.value = jsonJS.caja.caj_bodega;
              selVend.value = jsonJS.usuarios.usu_vend;
              //console.log(jsonJS.usuarios.usu_vend);
            }
          }
        }
      });
    });


    // VALID NUM
    $("#selTipo, #numInterno")
    .focus(function() {
      txtSerie.value="";
      numNum.value="";
      numInterno.value="";
      limpiar();
    });

    // VALID INTERNO
    $("#numInterno")
    .change(function (){

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

      parametros.append("selTipoCod", selTipo.value);
      parametros.append("selTipoAbrev", $('#selTipo').find('option:selected').data('abrev'));
      parametros.append("numInterno", numInterno.value);


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

          if(jsonJS.error == true){
            alError(jsonJS);
            return;
          }

          limpiar();
          tblClear("tblDet");
          sumDet();

          if (isNullPer(jsonJS.facturas)) {
            mesCerrado = false;
          } else {
            if (jsonJS.facturas.ciem_stat === "C") {
              mesCerrado = true;
            } else {
              mesCerrado = false;
            }
          }
          
          if (isNullPer(jsonJS.facturas)) {
            nuevo = true;
            numInterno.focus();
            fechaemision="";
            alWarning({"msg":{"title":"NO REGISTRADO","text":"Este documento no ha sido registrado"}});
            return true;
          } else {
            if (jsonJS.facturas.fact_caja!=pcaja) {
              numInterno.focus();
              alWarning({"msg":{"title":"NO CORRESPONDE A ESTA SUCURSAL","text":"Este documento no es de esta sucursal, debe anularlo en la sucursal donde lo grabo."}});
              return true;
            }            
            if (jsonJS.facturas.fact_documentguid!="") {
              numInterno.focus();
              alWarning({"msg":{"title":"NO ES ENVIO","text":"Este documento no es tipo ENVIO, no lo puede anular aqui."}});
              return true;
            }            
            nuevo = false;
            selTipo.value = jsonJS.facturas.fact_tipo;
            txtSerie.value = jsonJS.facturas.fact_serie;
            numNum.value = jsonJS.facturas.fact_num;
            cliCta = jsonJS.facturas.cli_cta;
            DocumentGUID = jsonJS.facturas.fact_documentguid;
            dtFec.value = jsonJS.facturas.fact_fec;
            selBodSal.value = jsonJS.facturas.fact_bodsal;
            txtCliCod.value = jsonJS.facturas.fact_codp;
            txtCliNom.value = jsonJS.facturas.cli_nom;
            txtNomFac.value = jsonJS.facturas.fact_nom;
            txtDir.value = jsonJS.facturas.fact_dir;
            txtNit.value = jsonJS.facturas.fact_nit;
            txtTel.value = jsonJS.facturas.fact_tel;
            numDcre.value = jsonJS.facturas.fact_dcre;
            numTcam.value = jsonJS.facturas.fact_tcam;
            selVend.value = jsonJS.facturas.fact_vend;
            txtMotAnu.value = jsonJS.facturas.fact_motanu;
            fechaemision=jsonJS.facturas.fact_guardado;
            jsonJS.fact_det.forEach(function(i){
              addRowDetao(i.factd_cod, i.factd_desc, i.factd_med, i.factd_unimed, i.factd_lote, i.factd_fvence,i.factd_cant, i.factd_preu, i.factd_sub, i.factd_descu, i.factd_descuv, i.factd_tot, i.factd_exensn, i.factd_bienser);
            });
            sumDet();
          }
        }
      });
    })
    .focus(function() {
      limpiar();
    });
    
    // VALID TIPO
    $("#selTipo")
    .change(function (){
      limpiar();
      /*tblClear("tblDet");
      sumDet();
      tblClear("tblPol");
      sumPol();*/
    });

    // CLICK ANULAR
    $("#btnAnular").click(function (){
      if (nuevo) {
        alWarning({"msg":{"title":"No Existe","text":"No puede anular este documento porque no ha sido registrado"}});
        return;
      }
      if (isNullPer(txtMotAnu.value)) {
        txtMotAnu.focus();
        alWarning({"msg":{"title":"MOTIVO ANULACION","text":"Debe registrar el motivo de la anulacion."}});
        return;
      }

      const fnT = function(){
        const parametros = new FormData();
        parametros.append("action", "anular");
        parametros.append("selTipoCod", selTipo.value);
        parametros.append("selTipoAbrev", $('#selTipo').find('option:selected').data('abrev'));
        parametros.append("txtSerie", txtSerie.value);
        parametros.append("numNum", numNum.value);
        parametros.append("numInterno", numInterno.value);
        parametros.append("tblDetAnt", tblDetAnt);
        parametros.append("tblPolAnt", tblPolAnt);
        parametros.append("txtNit", txtNit.value);
        parametros.append("txtMotAnu", txtMotAnu.value);
        parametros.append("DocumentGUID", DocumentGUID);
        parametros.append("fechaemision", fechaemision);

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

            if(jsonJS.error==true){
              alError(jsonJS);
            } else {
//              $("#btnAnular").focus(function (){
//                numInterno.focus();
                location.reload(true);
//              });
              //alSuccess(jsonJS);
            }
          }
        });
      }

      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") {
        $(target+' input:visible:first').focus();
      }
    //}
  });
</script>
