
/////////////////////////
//   QR CODE READER
/////////////////////////
function domReady(fn) { 
	if ( 
		document.readyState === "complete" || 
		document.readyState === "interactive"
	) { 
		setTimeout(fn, 1000); 
	} else { 
		document.addEventListener("DOMContentLoaded", fn); 
	} 
} 

domReady(function ()
{ 
	// If found you qr code 
	function onScanSuccess(decodeText, decodeResult){alert("You Qr is : " + decodeText, decodeResult);} 

// 	let htmlscanner = new Html5QrcodeScanner("my-qr-reader",{ fps: 10, qrbos: 250 }); 
// 	htmlscanner.render(onScanSuccess); 
});
/////////////////////////
/////////////////////////

     



function isNumber(value){return !isNaN(value);}

function isAllChr(value)
{
     var xchar;
     value=value.toUpperCase();
     for(var idx = 0; idx < value.length; idx++)
     {
       xchar=value.charAt(idx).charCodeAt();
       if(xchar<65 || xchar>90){return false;}
     }
     return true;
}

function vali_plvh(id)
{
     var codigo=document.getElementById(id).value;
     var xlet,xnum;
     
     codigo=codigo.trim();
     codigo=codigo.replace('-','');
     codigo=codigo.toUpperCase();
     if(codigo.length==6)
     {
          xlet=codigo.substr(0,3);
          xnum=codigo.substr(3,3);
          if(isNumber(xnum) && isAllChr(xlet))
          {codigo=codigo.substr(0,3)+'0'+codigo.substr(3,3);}
     }

     //valida numero inicial
//      if(!isNaN(codigo.substr(0,1))){codigo='';}

     document.getElementById(id).value=codigo;
}

function alltrim(string)
{
     string=string.trim();
     
     string=replace_all(" ,",",",string);
     string=replace_all(" ;",";",string);
     string=replace_all("/ ","/",string);
     
     string=replace_all("  "," ",string);
     
     string=string.replace(",",", ");
     string=string.replace(";","; ");
     string=string.replace("/"," /");
     
     var idx;
     for(idx=0;idx<=9;idx++)
     {string=string.replace(idx+" /",idx+"/");}
     
     return string;
}

function replace_all(search,replace,string)
{
     if(search==replace){return string;}
     while(string.indexOf(search)>=0){string=string.replace(search,replace);}
     return string;
}

function clrscr(id)
{
     if(!id){id='html';}
     document.getElementById(id).innerHTML='Wait...';
}

function save_docu(event)
{
     var datapost,dato;
     datapost=new_FormData('filtros','post');
     datapost.append('script','save_docu');
     
// for (let pair of datapost.entries())
// {console.log(pair[0] + ':', pair[1]);}     
     
     dato=exe_ajax(datapost,'','fn_consulta();',true);
//      dato=exe_ajax(datapost,'','');
//      fn_consulta();
//      window.location.reload();
//      console.log(dato);
//      set_idvalue('numero',$(dato).find("numero").html());
     
}


// function save_jwrv(rowid)
// function save_jwrv(cong,publicador,fecha,trty,bloq,ndpto,visita,rowid)
function save_jwrv(fecha,trty,bloq,ndpto,visita,rowid)
{
     
//      Swal.fire({
//        title: 'Actualizar Estado ?',
//        text: 'Actualizar Estado',
//        icon: 'question',
//        focusCancel: true,
//        showCancelButton: true,
//        confirmButtonColor: color1,
//        cancelButtonColor: 'darkred',
//        confirmButtonText: 'SI, Actualizar!'
//      }).then((result) =>
//      {
//           if (result.isConfirmed){
//                var data;
//                {
//                }
//           }
//      })
     
     
     
     
     const ahora = new Date();
     const hoy = ahora.toISOString().split('T')[0];     
     
     var datapost,dato;
//      datapost=new_FormData('filtros','post');
     datapost=new FormData();
     datapost.append('script','save_docu');
     datapost.append('trty',trty);
     datapost.append('fecha',fecha);
     datapost.append('bloq',bloq);
     datapost.append('ndpto',ndpto);
     datapost.append('visita',visita);
     
//      alert(visita);
     
     if(document.getElementById('cong'))
     {datapost.append('cong',document.getElementById('cong').value);}
     if(document.getElementById('docu'))
     {datapost.append('docu',document.getElementById('docu').value);}
     if(document.getElementById('hora'))
     {datapost.append('hora',document.getElementById('hora').value);}
     if(document.getElementById('publicador'))
     {datapost.append('publicador',document.getElementById('publicador').value);}
     if(document.getElementById('campana'))
     {datapost.append('campana',document.getElementById('campana').value);}
     
// for (let pair of datapost.entries())
// {console.log(pair[0] + ':', pair[1]);}     
     
// Obtener la URL actual
let url = new URL(window.location.href);
// Agregar o actualizar un parámetro GET
url.searchParams.set("idrow", rowid) ;
     
//      dato=exe_ajax(datapost,'','window.location.reload();',true);
     dato=exe_ajax(datapost,'','window.location.href = "'+url.toString()+'"',true);

}


function vali_docu(docu,idnum)
{
     var datapost,dato;
//      datapost=new_FormData('filtros','post');
     datapost= new FormData();
     datapost.append('docu',docu);
     datapost.append('idnum',idnum);
     datapost.append('script','save_docu');
     
//      dato=exe_ajax(datapost,'','fn_consulta();',true);
     dato=exe_ajax(datapost);
}



function save_maes(event)
{
     var datapost,dato;
     datapost=new_FormData('filtros','post');
     datapost.append('script','save_maes');
//      dato=exe_ajax(datapost,'','fn_consulta()',true);
     dato=exe_ajax(datapost,'','set_idvalue("codigo",$(dato).find("codigo").html());fn_consulta()',true);
//      fn_consulta();
//      window.location.reload();
//      console.log(dato);
//      set_idvalue('numero',$(dato).find("numero").html());
     
}


function save_chkbox(tabla,colu,fila,valor)
{
     var datapost,dato;
//      var table,col,row,val;
//      datapost=new_FormData('filtros','post');
//     alert(valor);
     if(valor==true){valor=1;}
     datapost=new FormData();
     datapost.append('script','save_chkbox');
     datapost.append('tabla',tabla);
     datapost.append('colu',colu);
     datapost.append('fila',fila);
     datapost.append('valorc',valor);
     
//      document.getElementById("main2").innerHTML='Espere...';
      dato=exe_ajax(datapost,'','',true);
     
//      alert(tabla+colu+fila+valor);
     
     
//      fn_consulta();
//      window.location.reload();
//      console.log(dato);
//      set_idvalue('numero',$(dato).find("numero").html());
     
}

function prcs_docu(docu,idnum,iddet,tconfirm='',refresh='')
{
     var color1=document.getElementById('color1').innerHTML;
     var color2=document.getElementById('color2').innerHTML;
     var datapost,title1,text1,input1,status,status2,timer1;

     input1='text';
     status=iddet;
     status2='';
     
     title1='Procesar';
     if(status=='A'){title1='Aprobar';}
     if(status=='R'){title1='Procesar';}
//      if(iddet=='X'){title1='Eliminar';}
     if(parseInt(iddet)>0){input1=''; status=''; status2='X'; timer1=10000;}
     
     datapost=new FormData();
     datapost.append('script','prcs_docu');
     datapost.append('docu',docu);
     datapost.append('idnum',idnum);
     datapost.append('iddet',iddet);
     datapost.append('status',status);
     datapost.append('refresh',refresh);
//      datapost.append('status2',status2);
//      datapost.append('divhide',divhide);

     swal.fire({
          icon:'warning',
          title:title1,
          text:' '+tconfirm+' ?',
          confirmButtonText:title1,
          confirmButtonColor:color1,
          focusCancel:true,
          showCancelButton:true,
          cancelButtonColor: 'darkred',
          timer:timer1
     }).then((result) => 
        {if(result.isConfirmed)
          {
               exe_ajax(datapost);
//                exe_ajax(datapost,'','location.reload();');
//                if(divhide){document.getElementById(divhide).setAttribute('linethr','');}
//                if(divhide && iddet!="N"){document.getElementById(divhide).setAttribute('linethr',''); location.reload();}
//                if(divhide && iddet=="X"){document.getElementById(divhide).setAttribute('hide','');}
//                if(refresh!=""){location.reload();}
               
          }})
     
     
//      }).then((result) => {if(result.isConfirmed){alert(document.getElementById('swal2-input').value);}})
}



function anul_docu(docu,idnum,iddet,tconfirm='',divhide='')
{
     var color1=document.getElementById('color1').innerHTML;
     var color2=document.getElementById('color2').innerHTML;
     var datapost,title1,text1,input1,status,status2,timer1;

     input1='text';
     status=iddet;
     status2='';
     
     title1='Remover';
     if(iddet=='O'){title1='Anular';}
     if(iddet=='X'){title1='Eliminar';}
     if(iddet=='N'){title1='Nota de Crédito';}
     if(iddet=='ALL'){title1='Borrar'; tconfirm='Borrar TODO el DETALLE'; status2='X';}
     if(parseInt(iddet)>0){input1=''; status=''; status2='X'; timer1=10000;}
     
     datapost=new FormData();
     datapost.append('script','anul_docu');
     datapost.append('docu',docu);
     datapost.append('idnum',idnum);
     datapost.append('iddet',iddet);
     datapost.append('status',status);
     datapost.append('status2',status2);
     datapost.append('divhide',divhide);

     swal.fire({
          icon:'warning',
          title:title1,
          text:' '+tconfirm+' ?',
          confirmButtonText:title1,
          confirmButtonColor:color1,
          focusCancel:true,
          showCancelButton:true,
          cancelButtonColor: 'darkred',
          
          input:input1,
          inputLabel: 'Motivo', 
          inputPlaceholder: 'Motivo...',          
          inputValidator: (value) => 
          {if(value){datapost.append('motivo',document.getElementById('swal2-input').value)}
           else {return 'Debe Especificar Motivo';}},      
          
          timer:timer1
     }).then((result) => 
        {if(result.isConfirmed)
          {
               exe_ajax(datapost);
//                if(divhide){document.getElementById(divhide).setAttribute('linethr','');}
               if(divhide && iddet!="N"){document.getElementById(divhide).setAttribute('linethr',''); location.reload();}
               if(divhide && iddet=="X"){document.getElementById(divhide).setAttribute('hide','');}
               
          }})
     
     
//      }).then((result) => {if(result.isConfirmed){alert(document.getElementById('swal2-input').value);}})
}

function dele_deta(docu,idnum,iddet,tconfirm='',divhide='')
{
     var color1=document.getElementById('color1').innerHTML;
     var color2=document.getElementById('color2').innerHTML;
     var datapost,title1,text1,input1,status,status2,timer1;

     input1='text';
     status=iddet;
     status2='';
     
     title1='Remover';
     if(iddet=='O'){title1='Anular';}
     if(iddet=='X'){title1='Eliminar';}
     if(parseInt(iddet)>0){input1=''; status=''; status2='X'; timer1=10000;}
     
     datapost=new FormData();
     datapost.append('script','anul_docu');
     datapost.append('docu',docu);
     datapost.append('idnum',idnum);
     datapost.append('iddet',iddet);
     datapost.append('status',status);
     datapost.append('status2',status2);
     datapost.append('divhide',divhide);

//        title: 'Eliminar Foto ?',
//        text: "Esta operación NO es reversible",
     
     
     swal.fire({
          icon:'warning',
          title:title1,
          text:' '+tconfirm+' ?',
          confirmButtonText:title1,
          confirmButtonColor:color1,
          focusCancel:true,
          showCancelButton:true,
          cancelButtonColor: 'darkred',
          
          input:input1,
          inputLabel: 'Motivo', 
          inputPlaceholder: 'Motivo...',          
          inputValidator: (value) => 
          {if (value){datapost.append('motivo',document.getElementById('swal2-input').value)}
           else {return 'Debe Especificar Motivo';}},      
          
          timer:timer1
     }).then((result) => 
        {if(result.isConfirmed)
          {
               exe_ajax(datapost);
               if(divhide){document.getElementById(divhide).setAttribute('linethr','');}
               if(divhide && iddet=="X"){document.getElementById(divhide).setAttribute('hide','');}
          }})
     
     
//      }).then((result) => {if(result.isConfirmed){alert(document.getElementById('swal2-input').value);}})
}




function sri1(a)
{
// https://srienlinea.sri.gob.ec/sri-catastro-sujeto-servicio-internet/rest/ConsolidadoContribuyente/existePorNumeroRuc?numeroRuc=0915379374001     
}

function set_noback()
{
// 	window.location.hash="no-back-button";
// 	window.location.hash="Again-No-back-button";
// 	window.onhashchange=function(){window.location.hash="no-back-button";}
}


function getHDDSerialNumber() {
    var sys = require('util')
    var exec = require('child_process').exec;
    function puts(error, stdout, stderr) {            
        console.log(sys.inspect(stdout, {showHidden: true, depth: null}))
    }
    exec("wmic DISKDRIVE get SerialNumber", puts);
}

function date_now(format)
{
//      1:    
     var curDate=new Date();
     var nowDate
     
     var month = new Array(12);
     month[0] = "Ene";
     month[1] = "Feb";
     month[2] = "Mar";
     month[3] = "Abr";
     month[4] = "May";
     month[5] = "Jun";
     month[6] = "Jul";
     month[7] = "Ago";
     month[8] = "Sep";
     month[9] = "Oct";
     month[10] = "Nov";
     month[11] = "Dec";     
     
     var weekday = new Array(7);
     weekday[0] = "Dom";
     weekday[1] = "Lun";
     weekday[2] = "Mar";
     weekday[3] = "Mie";
     weekday[4] = "Jue";
     weekday[5] = "Vie";
     weekday[6] = "Sab";

     var xyear=curDate.getFullYear();
     var xmonth=('0'+curDate.getMonth()).slice(-2);
     var xdate =('0'+curDate.getDate()).slice(-2);
     var xweekday = weekday[curDate.getDay()];     
     var xmonthname = month[curDate.getUTCMonth()];  
     
     nowDate=xyear+'-'+xmonth+'-'+xdate;
     
     return nowDate;
     
}

function time_now(obj=2)
{
     var curTime=new Date();
     var nowTime;
     nowTime=('0'+curTime.getHours()).slice(-2);
     if(obj>=2){nowTime=nowTime+':'+('0'+curTime.getMinutes()).slice(-2);}
     if(obj>=3){nowTime=nowTime+':'+('0'+curTime.getSeconds()).slice(-2);}
     if(obj>=4){nowTime=nowTime+'.'+('00'+curTime.getMilliseconds()).slice(-3);}
     return nowTime;
}

function user_login1()
{
//      alert(document.getElementById('empr').innerHTML);
     var data=new_FormData('login0');	
     data.append('script','user_login1');
     data.append('empr',document.getElementById('empr').innerHTML);
     data.append('locahref',location.href);
     exe_ajax(data,'','');
}

function usrt_confirm1()
{
     var data=new_FormData('confirm0');	
     data.append('script','usrt_confirm1');
     exe_ajax(data,'','');
}

function user_confirm1()
{
     var data=new_FormData('confirm0');	
     data.append('script','user_confirm1');
     exe_ajax(data,'','');
}

function user_logout(logout=1)
{
     var color1=document.getElementById('color1').innerHTML;
     var color2=document.getElementById('color2').innerHTML;
     var user_descri=document.getElementById('user_descri').innerHTML;
     
     var xtitle='Salir';
     var xtext='Salir de la Sesión '+user_descri+' ?';
     var xconfi='Salir';
     if(logout==3)
     {
          xtitle='Resetea';
          xtext='Resetear la Clave ?';
          xconfi='Resetea';
     }
     swal.fire({
          icon:'warning',
          title:xtitle,
          text:xtext,
          confirmButtonText:xconfi,
          confirmButtonColor:color1,
          focusCancel:true,
          showCancelButton:true,
          cancelButtonColor: 'darkred',
          timer:10000
     }).then((result) => {if(result.isConfirmed){window.location.href="?logout="+logout;}})
}

function user_nuevo1()
{     
     var data=new_FormData('usernew1');
     data.append('script','user_nuevo1');
     exe_ajax(data,'','');
}

function user_reset1()
{     
     var data=new_FormData('usernew1');
     data.append('script','user_reset1');
     exe_ajax(data,'','');
}



function ele_input_onkey(event,id)
{
//      return;
     var onenter=document.getElementById(id).getAttribute('onenter');
     var xdefa=document.getElementById(id).getAttribute('defa');
     var xvalue=document.getElementById(id).value.trim();
     var xtype=document.getElementById(id).getAttribute('type');
     var xlist=document.getElementById(id).getAttribute('list');

//      if(xlist==='')
     if(event.keyCode===9 || event.keyCode===13)
     if(xtype=='text' || xtype=='search')
     {if(document.getElementById(id).value===''){document.getElementById(id).value=xdefa;}}
     
     if(document.getElementById(id).tagName=='TEXTAREA')
     {
          var xwidth=document.getElementById(id).style.width;
          var xrows,xbrln;
          xrows=Math.ceil(xvalue.length/ parseInt(xwidth) /2)+1;
          if(xrows<2){xrows=2;}
          document.getElementById(id).setAttribute('rows',xrows)
          
          xbrln=xvalue.split("\n");
          if(xbrln.length>xrows){document.getElementById(id).setAttribute('rows',xbrln.length)}
          
          if(event.keyCode===13)
          {document.getElementById(id).value=document.getElementById(id).value+"\n";}
          
     }
     
     if(event.keyCode===13 && onenter){eval(onenter);}
     
     
     
}


function swal_fire(msgswal,peval='')
{
     if(!$(msgswal).find("text").text()){return;}
//      if(!$(msgswal).find("html").text()){return;}
//      if(!$(msgswal).find("text").text() && !$(msgswal).find("html").text()){return;}

     var color1=document.getElementById('color1').innerHTML;
     var color2=document.getElementById('color2').innerHTML;
     
     var icon=$(msgswal).find("icon").text();
     var title=$(msgswal).find("title").text();
     var html=$(msgswal).find("html").text();
     
     var confirmButton=$(msgswal).find("confirmButtonText").text();
     var denyButton=$(msgswal).find("denyButtonText").text();
     var showDeny=$(msgswal).find("showDenyButton").text();
     
     var isConfirmed=$(msgswal).find("isConfirmed").text();
     var isDenied=$(msgswal).find("isDenied").text();
     var dismiss=$(msgswal).find("dismiss").text();
     
     
     if(!icon){icon='warning';}
     if(!title){title='Alerta';}
     if(!confirmButton){confirmButton='Aceptar';}
     
     var timer1=$(msgswal).find("timer").text();
     if(!timer1){timer1=0;}
     
//      console.log(dismiss);
//      const { value: ipAddress } = await 
//      console.log("*/*/*/*/*/*");
//      console.log(msgswal);
     
     swal.fire({
          icon:icon,
          title:title,
          html:$(msgswal).find("text").text(),
          confirmButtonText:confirmButton,
          denyButtonText:denyButton,
          showDenyButton:denyButton,
          confirmButtonColor:color1,
          showCancelButton:$(msgswal).find("showCancel").text(),
          cancelButtonColor: 'darkred',
          timer:timer1
     }).then((result) => {
          if(result.isConfirmed){eval(isConfirmed);}
          if(result.dismiss === Swal.DismissReason.timer){eval(dismiss);}          
     })

     
// if (result.isConfirmed)
// {Swal.fire('Saved!', '', 'success')}
// else if (result.isDenied)
// {Swal.fire('Changes are not saved', '', 'info')}     
     
     
}

function new_FormData(pdiv='html',tipo='post',pdatap='')
{
     var xdate1 = new Date();
     var xms1 = xdate1.getTime();  
     var datax,datapost,dataget,xtags,ctag,cpdiv,xvalue,xvalnum,cradio=0;
     
     if(pdatap==='')
     {datapost=new FormData();}
     else
     {datapost=pdatap;}
     
     
     dataget='';
     if(document.getElementById(pdiv))
     {
          xtags=document.getElementById(pdiv).getElementsByTagName("select");
          for(ctag=0;ctag<xtags.length;ctag++)
          {
               xvalue=document.getElementById(xtags[ctag].id).value;
               xvalnum='';
               if(xvalue.trim().length>0){xvalnum=parseFloat(xvalue);}
               
               xvalue=alltrim(xvalue);
               if(xvalue!="")
               {
               datapost.append(xtags[ctag].id,xvalue);
               dataget=dataget+'&'+xtags[ctag].id+'='+xvalue;
               }
          } 
          
          xtags=document.getElementById(pdiv).getElementsByTagName("input");  
          for(ctag=0;ctag<xtags.length;ctag++)
          {
               if(!"checkbox.file.button.radio".includes(document.getElementById(xtags[ctag].id).type))
               {
                    xvalue=document.getElementById(xtags[ctag].id).value.trim();
                    xvalnum='';
                    if(xvalue.trim().length>0){xvalnum=parseFloat(xvalue);}

                    xvalue=alltrim(xvalue);
                    if(xvalue.length>1000){xvalue="==>1000";}
                    
//                     if(xvalue!="")
                    if(xvalue!="" && xvalue!=".")
                    {
                         if(xtags[ctag].id=='docu' || xtags[ctag].id=='docum')
                         {xvalue=xvalue.toUpperCase();}
                         datapost.append(xtags[ctag].id,xvalue);
                         dataget=dataget+'&'+xtags[ctag].id+'='+ encodeURIComponent(xvalue);
                    }
               }

               if(document.getElementById(xtags[ctag].id).type=="checkbox")
               {
                    xvalue=document.getElementById(xtags[ctag].id).checked;
                    
//                     if(xvalue)
                    {
                    datapost.append(xtags[ctag].id,xvalue);
                    dataget=dataget+'&'+xtags[ctag].id+'='+xvalue;
                    }
               }

               if(document.getElementById(xtags[ctag].id).type=="radio")
               {
                    xvalue=document.getElementById(xtags[ctag].id).checked;
                    if(xvalue)
                    {
                    datapost.append(xtags[ctag].id,xvalue);
                    dataget=dataget+'&'+xtags[ctag].id+'='+xvalue;
                    }
               }
               
               if(document.getElementById(xtags[ctag].id).type=="file")
               {
                    var inputfiles=document.getElementById(xtags[ctag].id);
                    for(var idx=0; idx<inputfiles.files.length; idx++)
                    {datapost.append(xtags[ctag].id+'['+idx+']',inputfiles.files[idx]);}
               }
               
          }
          
          xtags=document.getElementById(pdiv).getElementsByTagName("textarea");
          for(ctag=0;ctag<xtags.length;ctag++)
          {
               xvalue=document.getElementById(xtags[ctag].id).value.trim();
               xvalnum='';
               if(xvalue.trim().length>0){xvalnum=parseFloat(xvalue);}
               
               xvalue=alltrim(xvalue);
               if(xvalue!="")
               {
               datapost.append(xtags[ctag].id,xvalue);
//                dataget=dataget+'&'+xtags[ctag].id+'='+xvalue;
               dataget=dataget+'&'+xtags[ctag].id+'='+ encodeURIComponent(xvalue);
               }
          }

     }
    
     var xdate2 = new Date();
     var xms2 = xdate2.getTime();  
     console.log('new_FormData');
     console.log((xms2-xms1)/1000);

//      dataget=encode(dataget);
     datax=datapost;
     if(tipo=='get'){datax=dataget; }
 
     
     return datax;
}


function set_txtrow(e,pidtxt)
{
     var xvar=document.getElementById(pidtxt).value;
     if(e.keyCode==32){document.getElementById(pidtxt).value=xvar.replace('  ',' ');}

     var cols=document.getElementById(pidtxt).getAttribute('cols');
     var lentxt=xvar.trim().length;
     var rows=Math.ceil(lentxt/cols)+0;
     if(lentxt===0){rows=1;}
     document.getElementById(pidtxt).setAttribute('rows',rows);
}

function get_color(color,destino)
{
  var xurl,json,obj,colordescri;
  color=color.replace('#','');
    xurl='https://www.thecolorapi.com/id?format=json&hex='+color;
          $.ajax({
               url:xurl,
               async:true, 
               type:'GET',
               success:function(dato, textStatus, jqXHR)
               {
                    console.log(dato);
                    colordescri=dato.name.value;
                    if(document.getElementById(destino))
                    {if(document.getElementById(destino).value=='')
                    {document.getElementById(destino).value=colordescri;}}
               },
               error:function(jqXHR,textStatus,errorThrown )
               {console.log(jqXHR.status);}
          });	
  
  
  return colordescri;
}

function getOS()
{
  var userAgent = window.navigator.userAgent,
      platform = window.navigator.platform,
      macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
      windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'],
      iosPlatforms = ['iPhone', 'iPad', 'iPod'],
      os = null;

          if (macosPlatforms.indexOf(platform) !== -1) {os = 'Mac OS';}
     else if (iosPlatforms.indexOf(platform) !== -1) {os = 'iOS';}
     else if (windowsPlatforms.indexOf(platform) !== -1) {os = 'Windows';}
     else if (/Android/.test(userAgent)) {os = 'Android';}
     else if (!os && /Linux/.test(platform)) {os = 'Linux';}

  return os;
}

function sleep(milliseconds)
{
     const date = Date.now();
     let currentDate = null;
     do {currentDate = Date.now();}
     while (currentDate - date < milliseconds);
}

function get_para()
{
   getappv = navigator.appVersion;
   getempr = window.location.hostname.substring(0,4);
   gethost = window.location.hostname;
   getini = window.location.search.substring(1);
   if(getini.indexOf('=')>0){getini='';}	
   if(getini.indexOf('#')>0){getini=getini.substring(1,getini.indexOf('#'));}	

   var params = window.location.search.substr(1).split("&");
   $get={};
   for (var idx=0; idx<params.length; idx++)
   {
      var parat = params[idx].split("=");
      $get[decodeURIComponent(parat[0])] = decodeURIComponent(parat[1]);
   }
     
}


function sortTable(micelda,n,tipo='C')
{
//      return;
     //▲▼↑↓▬
	
     var table, body, rows,cols, i,j, x,y, a,b;
     var xv,yv,av,bv;
     var xorden,cswitch,contaw,totfilas;
     var xconfir=true;
     var mrca;
     var arrow1='▼', arrow2='▲';

     table = document.getElementById(micelda.parentElement.parentElement.parentElement.id);
     body = table.getElementsByTagName("tbody");
     rows = body[0].getElementsByTagName("tr");
     totfilas=rows.length
     if(document.body.innerHTML.indexOf("logomarcas")>=0){totfilas-=1;}
     if(micelda.innerHTML.indexOf(arrow2)<0 && micelda.innerHTML.indexOf(arrow1)<0)
     {if(totfilas>400){if(confirm('Reordenar ?')){xconfir=true;}else{xconfir=false;}}}
     if(xconfir && totfilas>1)
     {
          body = table.getElementsByTagName("tbody");
          rows = body[0].getElementsByTagName("tr");
          x = rows[1].getElementsByTagName("td")[n];
          y = rows[0].getElementsByTagName("td")[n];
          a = rows[1].getElementsByTagName("td")[0];
          b = rows[0].getElementsByTagName("td")[0];

          xorden='A';
          if(micelda.innerHTML.indexOf(arrow1)>=0){xorden='D';}
          if(micelda.innerHTML.indexOf(arrow2)>=0){xorden='A';}

          cols = micelda.parentElement.getElementsByTagName("th");
          for (i=0; i<(cols.length); i++)
          {
               cols[i].innerHTML=cols[i].innerHTML.replace(arrow1,'');
               cols[i].innerHTML=cols[i].innerHTML.replace(arrow2,'');
          }

          if(xorden=='A')
          {
               micelda.innerHTML=arrow1+' '+micelda.innerHTML;
               for(i=0; i<totfilas; i++)
               {
                    body = table.getElementsByTagName("tbody");
                    rows = body[0].getElementsByTagName("tr");
                    x = rows[i].getElementsByTagName("td")[n];
                    y = rows[0].getElementsByTagName("td")[n];

                    // valores de la columna inicial. utiles como segunda clave de indice.
                    a = rows[i].getElementsByTagName("td")[0];
                    b = rows[0].getElementsByTagName("td")[0];

                    //A
                    contaw=0;
                    if(x && y && a && b)
                    {
                         xv=""+x.innerHTML.toLowerCase();
                         av=a.innerHTML.toLowerCase();
                         yv=""+y.innerHTML.toLowerCase();
                         bv=b.innerHTML.toLowerCase();

                         xv=xv+av;
                         yv=yv+bv;

                         if(tipo=='N')
                         {
                              xv=""+x.textContent;
                              yv=""+y.textContent;
                              xv=xv.replace(',','');
                              xv=xv.replace(',','');
                              xv=xv.replace(',','');
                              xv=xv.replace('--','0');
                              xv=xv.replace('▬','0');
                              xv=parseFloat(xv);
                              yv=yv.replace(',','');
                              yv=yv.replace(',','');
                              yv=yv.replace(',','');
                              yv=yv.replace('--','0');
                              yv=yv.replace('▬','0');
                              yv=parseFloat(yv);
                              
                         }

                         while(xv > yv)
                         {
                              contaw++;
                              y = rows[contaw].getElementsByTagName("td")[n];
                              b = rows[contaw].getElementsByTagName("td")[0];

                              xv=""+x.innerHTML.toLowerCase();
                              av=a.innerHTML.toLowerCase();
                              yv=""+y.innerHTML.toLowerCase();
                              bv=b.innerHTML.toLowerCase();
                              xv=xv+av;
                              yv=yv+bv;
                              if(tipo=='N')
                              {
                                   xv=""+x.textContent;
                                   yv=""+y.textContent;
                                   xv=xv.replace(',','');
                                   xv=xv.replace(',','');
                                   xv=xv.replace(',','');
                                   xv=xv.replace('--','0');
                                   xv=xv.replace('▬','0');
                                   xv=parseFloat(xv);
                                   yv=yv.replace(',','');
                                   yv=yv.replace(',','');
                                   yv=yv.replace(',','');
                                   yv=yv.replace('--','0');
                                   yv=yv.replace('▬','0');
                                   yv=parseFloat(yv);
                                   
                              }
                         }
                    }
                    if(i!=contaw){rows[contaw].parentNode.insertBefore(rows[i], rows[contaw]);}
               }
          }

          if(xorden=='D')
          {
               micelda.innerHTML=micelda.innerHTML+' '+arrow2;
               for (i=0; i<totfilas; i++)
               {
                    body = table.getElementsByTagName("tbody");
                    rows = body[0].getElementsByTagName("tr");
                    x = rows[i].getElementsByTagName("td")[n];
                    y = rows[0].getElementsByTagName("td")[n];

                    a = rows[i].getElementsByTagName("td")[0];
                    b = rows[0].getElementsByTagName("td")[0];

                    //D
                    contaw=0;
                    if(x && y && a && b)
                    {
                         xv=""+x.innerHTML.toLowerCase();
                         av=a.innerHTML.toLowerCase();
                         yv=""+y.innerHTML.toLowerCase();
                         bv=b.innerHTML.toLowerCase();
                         xv=xv+av;
                         yv=yv+bv;
                         if(tipo=='N')
                         {
                              xv=""+x.textContent;
                              yv=""+y.textContent;
                              xv=xv.replace(',','');
                              xv=xv.replace(',','');
                              xv=xv.replace(',','');
                              xv=xv.replace('--','0');
                              xv=xv.replace('▬','0');
                              xv=parseFloat(xv);
                              yv=yv.replace(',','');
                              yv=yv.replace(',','');
                              yv=yv.replace(',','');
                              yv=yv.replace('--','0');
                              yv=yv.replace('▬','0');
                              yv=parseFloat(yv);
                              
                         }

                         while(xv < yv)
                         {
                              contaw++;
                              y = rows[contaw].getElementsByTagName("td")[n];
                              b = rows[contaw].getElementsByTagName("td")[0];

                              xv=""+x.innerHTML.toLowerCase();
                              av=a.innerHTML.toLowerCase();
                              yv=""+y.innerHTML.toLowerCase();
                              bv=b.innerHTML.toLowerCase();
                              xv=xv+av;
                              yv=yv+bv;
                              if(tipo=='N')
                              {
                                   xv=""+x.textContent;
                                   yv=""+y.textContent;
                                   xv=xv.replace(',','');
                                   xv=xv.replace(',','');
                                   xv=xv.replace(',','');
                                   xv=xv.replace('--','0');
                                   xv=xv.replace('▬','0');
                                   xv=parseFloat(xv);
                                   yv=yv.replace(',','');
                                   yv=yv.replace(',','');
                                   yv=yv.replace(',','');
                                   yv=yv.replace('--','0');
                                   yv=yv.replace('▬','0');
                                   yv=parseFloat(yv);
                                   
                              }
                         }
                    }
                    if(i!=contaw){rows[contaw].parentNode.insertBefore(rows[i], rows[contaw]);}
               }
          }

     }

//      dottedTable(table);
//   resizeTab(table);
}

function dottedTable(mitabla,clin=5)
{
//      return;
     console.log('Dotted : '+Date());
     console.log(mitabla);

     var table,rows,idx,borderbott;
//      var blockrows=document.getElementById(mitabla).getAttribute('blockrows');
//      var blockbott=document.getElementById(mitabla).getAttribute('blockbott');
     var blockrows=mitabla.getAttribute('blockrows');
     var blockbott=mitabla.getAttribute('blockbott');
     var heightrow=mitabla.getAttribute('heightrow');
     clin=blockrows
     borderbott=blockbott;
     
     if(blockbott===null){borderbott='dotted 1px';}
     if(clin===0 || clin===undefined || clin===null){clin=5;}
     rows = mitabla.getElementsByTagName("tr");
     
//      var tHead = mitabla.getElementsByTagName('thead')[0];
//      var headrows = tHead.getElementsByTagName('tr');
     var rowini;
     var tBody = mitabla.getElementsByTagName('tbody')[0];
     rows = tBody.getElementsByTagName('tr');

     rowini=0;
     for (idx = rowini; idx < (rows.length - 0); idx++)
     {
          rows[idx].removeAttribute('bb-do1','');
          rows[idx].removeAttribute('bb-da1','');
          rows[idx].style.borderBottom="";
     }
     
     rowini=0;
     for (idx = rowini; idx < (rows.length - 1); idx++)
     {
          if(((idx+1) % clin)===0)
          {rows[idx].setAttribute('bb-do1','');}
          else
          {rows[idx].style.borderBottom="";}
          
          rows[idx].style.height=heightrow; 
     }
     
     rows[idx].style.borderBottom="solid 1px";
     
     console.log('Dotted : '+Date());
     
}

function _clickfdoc(docu,idnum,iddet)
{
// https://gmny.vcrxol.com/index4.php?scri=show_image&maes=item&codigo=20100704&prnt=1     
	var xurl;
//      xurl = document.getElementById(pidtxt).src;
     xurl='?scri=show_filedocu&docu='+docu+'&idnum='+idnum+'&iddet='+iddet+'&prnt=1';
	xtop=Math.ceil(screen.height*0.08);
	xleft=Math.ceil(screen.width*0.1);
	width=Math.ceil(screen.width*0.75);
	height=Math.ceil(screen.height*0.75);
	imgwindow=window.open(xurl,"Imagen","top="+xtop+",left="+xleft+",width="+width+",height="+height+",toolbar=no,location=no,menubar=no,status=no,");
// 	imgwindow=window.open(xurl,"Imagen","toolbar=no,location=no,menubar=no,status=no,");
}

function _clickimg(codigo,maes='item')
{
// https://gmny.vcrxol.com/index4.php?scri=show_image&maes=item&codigo=20100704&prnt=1     
	var xurl;
//      xurl = document.getElementById(pidtxt).src;
//      xurl='?scri=show_image&maes=item&codigo='+codigo+'&prnt=1';
     xurl='?scri=show_image&maes='+maes+'&codigo='+codigo+'&prnt=12';
	xtop=Math.ceil(screen.height*0.08);
	xleft=Math.ceil(screen.width*0.1);
	width=Math.ceil(screen.width*0.75);
	height=Math.ceil(screen.height*0.75);
	imgwindow=window.open(xurl,"Imagen","top="+xtop+",left="+xleft+",width="+width+",height="+height+",toolbar=no,location=no,menubar=no,status=no,");
// 	imgwindow=window.open(xurl,"Imagen","toolbar=no,location=no,menubar=no,status=no,");
}

function _clickdispon(iddescri,dispon)
{
     var color=document.getElementById('color1').innerHTML;
     var descri=document.getElementById(iddescri).innerHTML;
     swal.fire({
          icon:"info",
          title:descri,
          text:"DISPONIBLE : "+dispon,
          confirmButtonColor:color,
          timer:10000
     });
     
}


function fnExcelReport(tablaId, btndown, filename='')
{
    $('.hidden').remove();
    $('.noxls').remove();
    filename = filename?filename+'':'excel_data';
    var filenamexls = filename?filename+'.xls':'excel_data.xls';
  
    var tab_orig=$('#'+tablaId).html();
    tab_orig=tab_orig.replace(/<br>/g,'');
     
//      alert(tab_orig);
  
    var tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
    tab_text = tab_text + '<head><xml>';
    tab_text = tab_text + '<x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';
    tab_text = tab_text + '<x:Name>'+filename+'</x:Name>';
    tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions>';
    tab_text = tab_text + '</x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook>';
    tab_text = tab_text + '</xml></head>';
    
    tab_text = tab_text + '<body>';
    tab_text = tab_text + "<table border='1px'>";
    tab_text = tab_text + tab_orig;
    tab_text = tab_text + '</table>';
    tab_text = tab_text + '</body>';

    tab_text = tab_text + '</html>';

  // falta remover los <span>
  
    var data_type = 'data:application/vnd.ms-excel';
    
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");
     
    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))
    {
        if (window.navigator.msSaveBlob)
        {
            var blob = new Blob([tab_text],{
                type: "application/csv;charset=utf-8;"
            });
            navigator.msSaveBlob(blob, filenamexls);
        }
    }else{
//         $('#test').attr('href', data_type + ', ' + encodeURIComponent(tab_text));
//         $('#test').attr('download', 'Test file.xls');
      
        $('#'+btndown.id).attr('href', data_type + ', ' + encodeURIComponent(tab_text));
        $('#'+btndown.id).attr('download', filenamexls);
    }

}



function print_selec(nombre)
{
     var ficha = document.getElementById(nombre);
     var ventimp = window.open(' ', 'popimpr');
     ventimp.document.write( ficha.innerHTML );
     ventimp.document.close();
     ventimp.print( );
     ventimp.close();
}

function print_url(url)
{
     var ventimp = window.open(url, 'popimpr');
     ventimp.print();
}






function _okuptxt(e,pidtxt)
{
     var xvar=document.getElementById(pidtxt).value;
     var cols=document.getElementById(pidtxt).getAttribute('cols');
     if(e.keyCode==32){document.getElementById(pidtxt).value=xvar.replace('  ',' ');}
     var lentxt=xvar.trim().length;
     var rows=Math.ceil(lentxt/cols)+0;
     if(lentxt===0 || rows<2){rows=2;}
     document.getElementById(pidtxt).setAttribute('rows',rows);
}


function val_minmax(id)
{
//      return;     
     var min,max,step,value;
     var mins,seco,dife;
     if(document.getElementById(id).getAttribute('min')){min=document.getElementById(id).getAttribute('min');}
     if(document.getElementById(id).getAttribute('max')){max=document.getElementById(id).getAttribute('max');}
     if(document.getElementById(id).getAttribute('step')){step=document.getElementById(id).getAttribute('step');}

     value=document.getElementById(id).value;
     
     if(value===''){document.getElementById(id).value=min;}
//      if(value===''){return;}
     
     dife=0;
     if(document.getElementById(id).type=='time')
     {
          step=parseFloat(step);
          mins=parseFloat(value.substring(3,5));
          seco=mins*60;
//           dife=seco % step;
//           if(dife != 0)
//           {document.getElementById(id).value=value.substring(0,3)+ (seco-dife)/60;}
     }
     
     if(document.getElementById(id).type=='number')
     {
          min=parseFloat(min);
          max=parseFloat(max);
     }
     
     
     if(value<min || value>max || dife!=0)
     {
          Swal.fire({
            title: 'Error! '+id,
            text: 'Valor : '+value+' *** NO Permitido *** ',
            icon: 'error',
            timer:5000
          })
          if(value>max){document.getElementById(id).value=max;}
          if(value<min){document.getElementById(id).value=min;}
          if(dife != 0)
          {document.getElementById(id).value=value.substring(0,3)+ (seco-dife)/60;}
     }
     
     
     return
}


function set_cookie(cname, cvalue, exdays)
{
  const d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  let expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
//      alert(document.cookie);
}


function get_cookie(cname)
{
  let name = cname + "=";
  let decodedCookie = decodeURIComponent(document.cookie);
  let ca = decodedCookie.split(';');
  for(let i = 0; i <ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}


function check_cookie() 
{
//   let username = getCookie("username");
//   if (username != "") {
//    alert("Welcome again " + username);
//   } else {
//     username = prompt("Please enter your name:", "");
//     if (username != "" && username != null) {
//       setCookie("username", username, 365);
//     }
//   }
}



function set_arearows(id)
{
     var xleng;
     xleng=document.getElementById(id).value.trim.length();
//      consolelog('*/*/*/*/*/');
//      console.log(xleng);
}


function copy_btn(e,name)
{
// var urlField = document.querySelector('table');
var urlField = document.querySelector('table[name="'+name+'"]');
//      urlField = document.querySelector("table[name='vtrpm1_20220927_015914_main']");
var range = document.createRange();  
range.selectNode(urlField);
window.getSelection().addRange(range);
document.execCommand('copy');
}          

function save_soft(event)
{
     var datapost,dato;
     datapost=new_FormData('Informacion','post');
     datapost.append('script','save_soft');
          
     //dato=exe_ajax(datapost,'','fn_consulta();',true);   
}

function recaptcha()
{
	if(grecaptcha.getResponse()!==''){return true;}
	else{swal.fire({title:'Advertencia',text:'Marque el Casillero de Verificación',icon:'warning'});return false;}
// 	document.getElementById('recaptcha-anchor-label').innerHTML='Marque este Casillero'
}


function recaptcha_v3(action,js_func)
{
     var dato,token,result;
    //e.preventDefault();
     grecaptcha.ready(function()
     {
          grecaptcha.execute('6LdXALciAAAAAF5nqI5k1YkgQtWDGfflBgG0Oil-', {action: 'registro'}).then(function(token)
          {
               var data = new FormData();
               data.append('action',action);
               data.append('token',token);
               data.append('script','recaptcha_v3');
               
               var xhttp = new XMLHttpRequest();
               xhttp.onreadystatechange = function()
               {if (this.readyState == 4 && this.status == 200)
                    {
                         dato=this.responseText;
                         success=$(dato).find("success").html();
                         action=$(dato).find("action").html();
                         score=$(dato).find("score").html();
                         result=$(dato).find("result").html();
                         
                         console.log(score);
                         console.log(result);
                         
                        //  {eval(js_func);}

                         if(result=="OK"){eval(js_func);}
                         else{swal.fire({title:'Error',text:'Eres Humano ?',icon:'error'});return false;}
                         
                    }
               };
               xhttp.open("POST", _urlinker);
               xhttp.send(data);
          });
    });
    return false;
}


function regi_maes(tabla,codigo='',confirm='')
{
     if(codigo===''){return;}
     if(getOS()=='Android'){confirm=1;}
     
     var timer1=3000;
     var xhref;
     
     
     
     xhref='?scri=regi_maes3&modu='+tabla+'&codigo='+codigo;

     if(confirm==='')
     {window.open(xhref,"_blank");}
     else
     {
          swal.fire({
               icon:'question',
               title: 'Editar Código',
               text:' Editar '+codigo+' ?',
               confirmButtonText:'Editar',
               confirmButtonColor:color1,
               focusCancel:true,
               showCancelButton:true,
               cancelButtonColor: 'darkred',

               timer:timer1
          }).then((result) => 
             {if(result.isConfirmed)
               {
                    window.open(xhref,"_blank")
               }})
          
     }
     
     
     
     
     
}


function set_fecha12(id)
{
//      return;
     var fecha1,fecha2,year,month,day;
     
     if(document.getElementById('fecha1')){fecha1=document.getElementById('fecha1').value;}
     if(document.getElementById('fecha2')){fecha2=document.getElementById('fecha2').value;}
     
     if(fecha1>fecha2)
     {
          var fechax0 = new Date(); 
          var fechax1 = new Date(); 
          var fechax2 = new Date(); 
          
          fechax0.setFullYear(fecha2.substr(0,4), fecha2.substr(5,2), 0);
          year = fechax0.getFullYear();
          month = ''+(fechax0.getMonth() + 1);
          day = '01';
          if (month.length < 2) {month = '0' + month;}
          if (day.length < 2) {day = '0' + day;}
          fechax1=[year, month, day].join('-');
          
          fechax0.setFullYear(fecha1.substr(0,4), fecha1.substr(5,2), 0);
          year = fechax0.getFullYear();
          month = ''+(fechax0.getMonth() + 1);
          day = ''+fechax0.getDate();
          if (month.length < 2) {month = '0' + month;}
          if (day.length < 2) {day = '0' + day;}
          fechax2=[year, month, day].join('-');
          
          if(id=='fecha1'){document.getElementById('fecha2').value=fechax2;}
          if(id=='fecha2'){document.getElementById('fecha1').value=fechax1;}

     }
     
     set_daynomb('fecha1');
     set_daynomb('fecha2');
}


function upld_cele(idfile)
{
     var color1=document.getElementById('color1').innerHTML;
     var color2=document.getElementById('color2').innerHTML;
     var xfile;     
     var data;
     
     //file or number
     console.log(document.getElementById(idfile).type);
     
     if(document.getElementById(idfile).type=='file')
     {
          xfile=document.getElementById(idfile);
          if(xfile.files.length==0)
          {document.getElementById(idfile).click();return;}
          
               for(var idx=0; idx<xfile.files.length; idx++)
               {
                    data=new FormData();
                    data.append('script','upld_cele');
                    data.append('xfile',xfile.files[idx]);
                    exe_ajax(data,'','',false);
               }
          
     }
     else
     {
          xfile=document.getElementById(idfile).value;
          if(xfile.trim().length<49){return;}
                    data=new FormData();
                    data.append('script','upld_cele');
                    data.append('xfile',xfile);
                    exe_ajax(data,'','',false);
     }
          
//      Swal.fire({
//        title: 'Subir Archivos ?',
//        text: document.getElementById(idfile).files.length+' Claves_Acceso',
//        icon: 'warning',
//        focusCancel: true,
//        showCancelButton: true,
//        confirmButtonColor: color1,
//        cancelButtonColor: 'darkred',
//        confirmButtonText: 'SI, Subir!'
//      }).then((result) =>
//      {
//           if (result.isConfirmed){
               
//                if(document.getElementById(idfile).type=='file'){}
//                else
//                {
//                }
// //                location.reload();
//           }
//      })
     
}


function upld_rpis(idfile)
{
     var color1=document.getElementById('color1').innerHTML;
     var color2=document.getElementById('color2').innerHTML;
     var xfile;     
     var data;
     
     //file or number
     console.log(document.getElementById(idfile).type);
     
     if(document.getElementById(idfile).type=='file')
     {
          xfile=document.getElementById(idfile);
          if(xfile.files.length==0)
          {document.getElementById(idfile).click();return;}
          
               for(var idx=0; idx<xfile.files.length; idx++)
               {
                    data=new FormData();
                    data.append('script','upld_rpis');
                    data.append('xfile',xfile.files[idx]);
                    exe_ajax(data,'','',false);
               }
          
     }
//      else
//      {
//           xfile=document.getElementById(idfile).value;
//           if(xfile.trim().length<49){return;}
//                     data=new FormData();
//                     data.append('script','upld_cele');
//                     data.append('xfile',xfile);
//                     exe_ajax(data,'','',false);
//      }
          
//      Swal.fire({
//        title: 'Subir Archivos ?',
//        text: document.getElementById(idfile).files.length+' Claves_Acceso',
//        icon: 'warning',
//        focusCancel: true,
//        showCancelButton: true,
//        confirmButtonColor: color1,
//        cancelButtonColor: 'darkred',
//        confirmButtonText: 'SI, Subir!'
//      }).then((result) =>
//      {
//           if (result.isConfirmed){
               
//                if(document.getElementById(idfile).type=='file'){}
//                else
//                {
//                }
// //                location.reload();
//           }
//      })
     
}
     


function reloadPage(xseconds)
{
     if(!isNumber(xseconds)){xseconds=60*90;}
     if(xseconds==0){xseconds=60*90;}
     clearTimeout(idleTime);
     idleTime = setTimeout(function () {location.reload();}, xseconds*1000);
}          


function down_url(url)
{
     var element = document.createElement('a');
     var filename;
     filename=url.substr(url.lastIndexOf('/')+1);
     //  if(type===undefined){type='xml';}
     {element.setAttribute('href', url);}
     element.setAttribute('download', filename);
     element.style.display = 'none';
     document.body.appendChild(element);
     element.click();
     document.body.removeChild(element);  
}


function Xgen_ats(anio,mes)
{
  var aa,xparam;
  xparam='gen_ats1('+anio+','+mes+')';
//   aa=php_func(xparam,'w');	
  aa=exe_phpf(xparam,'w');	
  return;  
}

// function gen_ats(anio,mes,sixm=0)
function gen_ats(anio,mes,toenti='')
{
     var datapost,dato;
//      datapost=new_FormData('filtros','post');
     datapost= new FormData();
     datapost.append('ats_anio',anio);
     datapost.append('ats_mes',mes);
     datapost.append('ats_toenti',toenti);
//      datapost.append('ats_sixm',sixm);
     datapost.append('script','gen_ats1');
     
//      dato=exe_ajax(datapost,'','fn_consulta();',true);
     dato=exe_ajax(datapost,'','',true);
}



function maximoZindex(from)
{
  var max = 0;
  from.find(">*").each(function(i, e){
    var z = Number($(e).css("z-index"));
    if(z > max) {
      max = z;
    }
  });
  return max;
// console.log("maximo z-index a partir de body", maximoZindex($("body")));
}


function isValidBarcode(value) 
{
  if(value === null){return false;}
       
  // We only allow correct length barcodes
  if (!value.match(/^(\d{8}|\d{12,14})$/)) {
    return false;
  }

  const paddedValue = value.padStart(14, '0');

  let result = 0;
  for (let i = 0; i < paddedValue.length - 1; i += 1) {
    result += parseInt(paddedValue.charAt(i), 10) * ((i % 2 === 0) ? 3 : 1);
  }

  return ((10 - (result % 10)) % 10) === parseInt(paddedValue.charAt(13), 10);
}


function _geolocation()
{
	navigator.geolocation.getCurrentPosition
     (function(location){
// 		alert(12);
          
          brln="\n";
          
          dataloc='';
          dataloc=dataloc+'Lati : '+location.coords.latitude+' '+brln;
          dataloc=dataloc+'Long : '+location.coords.longitude+' '+brln;
          dataloc=dataloc+'Accu : '+location.coords.accuracy+' '+brln;
          dataloc=dataloc+'Alti : '+location.coords.altitude+' '+brln;
          dataloc=dataloc+'Alac : '+location.coords.altitudeAccuracy+' '+brln;
          dataloc=dataloc+'Head : '+location.coords.heading+' '+brln;
          dataloc=dataloc+'Spee : '+location.coords.speed+' '+brln;

          alert(dataloc);
          
		console.log(location.coords.latitude);
		console.log(location.coords.longitude);
		console.log(location.coords.accuracy);
		console.log(location.coords.altitude);
		console.log(location.coords.altitudeAccuracy);
		console.log(location.coords.heading);
		console.log(location.coords.speed);
		

     eol='%0A';
          
     wsapp='0996030568';
     phone='593';
     phone='593'+wsapp;
          
     texto=dataloc;
     texto.replace(brln,eol);
          
     url='';
     url=url+'https://api.whatsapp.com/send/';
     url=url+'?phone='+phone;
     url=url+'&text='+texto;
     
//      url=encodeURIComponent(url);
     
//      window.open(url,'_blank');
          
          
          
		
	});	
}


// function hide_class(clase){cambia_display(clase, 'none');}
// function show_class(clase){cambia_display(clase, 'block');}    
function cambia_display(clase)
{
  var xdisplay;
  const elementos = document.querySelectorAll(`.${clase}`);
  elementos.forEach(elemento => 
                    {
                         if(elemento.style.display=='none'){xdisplay='';} 
                         if(elemento.style.display!='none'){xdisplay='none';}
                         elemento.style.display = xdisplay; 
                    });
}

function Xcambia_display(clase, displayValue)
{
  const elementos = document.querySelectorAll(`.${clase}`);
  elementos.forEach(elemento => {elemento.style.display = displayValue; });
}




function copy2clipboard(element) 
{
            // Obtener el valor del campo de entrada
            const texto = document.getElementById(element).value;
            
//      $ref->setAttribute('onclick',"swal_fire('<msg><icon>info</icon><title>Aviso</title><text>DOCUMENTO YA ESTA AUTORIZADO</text></msg>')");
     
     
            // Usar la API del Portapapeles para copiar el texto
            navigator.clipboard.writeText(texto)
                .then(() => {
//                     alert('Texto copiado al portapapeles: ' + texto);
                    swal_fire('<msg><icon>info</icon><title>Se copio al PortaPapeles</title><text>'+texto+'</text></msg>');
                })
                .catch(err => {
//                     console.error('Error al copiar al portapapeles:', err);
                    swal_fire('<msg><icon>error</icon><title>Error al Copiar</title><text>'+''+'</text></msg>');
                });
}


function set_daynomb(id)
{
     var fecha = new Date(document.getElementById(id).value);
     fecha.setDate(fecha.getDate()+1);
//      var diasSemana = ['Lunes', 'Marter', 'Miércole', 'Jueves', 'Viernes', 'Sábado','Domingo'];
//      var diasSem = ['Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb','Dom'];
     var diasSemana = ['Domingo','Lunes', 'Marter', 'Miércole', 'Jueves', 'Viernes', 'Sábado'];
     var diasSem = ['Dom','Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'];
     var dianume = fecha.getDay();
     var dianomb = diasSem[fecha.getDay()];
     var dianombre = diasSemana[fecha.getDay()];
     
     const opciones = {
         weekday: 'long',  // Nombre completo del día
         year: 'numeric',  // Año completo
         month: 'long',    // Nombre completo del mes
         day: 'numeric'    // Día del mes
     };     
     
//      document.getElementById(id+'_r').innerHTML=fecha;
     document.getElementById(id+'_r').innerHTML=dianomb;
//      document.getElementById(id+'_r').innerHTML=dianume;
     document.getElementById(id+'_ele').title=fecha.toLocaleDateString('es-ES', opciones);

     
//      document.getElementById(id+'_r').innerHTML=dianume;
     
//      if(dianume==0){document.getElementById(id).style.backgroundColor='golden';}
//      if(dianume==1){document.getElementById(id).style.backgroundColor='darkred';}
//      if(dianume==2){document.getElementById(id).style.backgroundColor='pink';}
}



function set_inputdate(id,fecha=0)
{
     var ztype= document.getElementById(id).type;
     var fecval=document.getElementById(id).value;
     let hoy = new Date();
     let fechaFormateada ; 
     let mesFormateado ;
     let fecha0= document.getElementById(id).min;
     let fecha1= document.getElementById(id).defa;
     
     let primerDiaAno = new Date(hoy.getFullYear(),0,1);
     let primerDiaMes = new Date(hoy.getFullYear(), hoy.getMonth(), 1);
     let ultimoDiaMes = new Date(hoy.getFullYear(), hoy.getMonth() + 1, 0);
     let ultimoDiaAno = new Date(hoy.getFullYear(), 11, 31);
     
     let primerMes = new Date(hoy.getFullYear(), 0);
     let mesActual = new Date(hoy.getFullYear(), hoy.getMonth());
     let ultimoMes = new Date(hoy.getFullYear(), 11);
     
     if(fecha==0)
     {
          fechaFormateada=fecha0;
          mesFormateado=fecha0.slice(0,7);
     }
     
     if(fecha==1)
     {
          fechaFormateada = hoy.toISOString().split('T')[0];     
          mesFormateado = mesActual.toISOString().slice(0, 7);
          
          if(fecval==fechaFormateada)
          {fechaFormateada = primerDiaMes.toISOString().split('T')[0];}
          
          if(fecval==primerDiaMes.toISOString().split('T')[0])
          {
               fechaFormateada = primerDiaAno.toISOString().split('T')[0];
               mesFormateado = primerMes.toISOString().slice(0,7);
          }
          
          if(fecval==primerDiaAno.toISOString().split('T')[0])
          {
               fechaFormateada=fecha0;
               mesFormateado=fecha0.slice(0,7);
          }
          
     }
     
     if(fecha==2)
     {
          fechaFormateada = hoy.toISOString().split('T')[0];
          mesFormateado = mesActual.toISOString().slice(0, 7);
          
          if(fecval==fechaFormateada)
          {fechaFormateada = ultimoDiaMes.toISOString().split('T')[0];}
          
          if(fecval==ultimoDiaMes.toISOString().split('T')[0])
          {
               fechaFormateada = ultimoDiaAno.toISOString().split('T')[0];
               mesFormateado = ultimoMes.toISOString().slice(0,7);
          }
          
     }
     
     if(fecha==3)
     {
          fechaFormateada = ultimoDiaAno.toISOString().split('T')[0];
          mesFormateado = ultimoMes.toISOString().slice(0, 7);
     }
     
     if(ztype=='date'){document.getElementById(id).value=fechaFormateada ; }
     if(ztype=='month'){document.getElementById(id).value=mesFormateado; }

//      set_fecha12(id);
}



function mail_docu(docu1,idnum1,email1='')
{
     var input1='text';
     
     Swal.fire({
       title: 'Enviar Documento ?',
       input:'text',
       inputLabel: 'e-Mail', 
       inputPlaceholder: 'email...',          
       inputValue:email1,
       text: 'Enviar Documento',
       icon: 'question',
       focusCancel: true,
       showCancelButton: true,
       confirmButtonColor: color1,
       cancelButtonColor: 'darkred',
       confirmButtonText: 'SI, Enviar!',

//           {if(value){datapost.append('motivo',document.getElementById('swal2-input').value)}
          
          inputValidator: (value) => 
          {if(value){email1=document.getElementById('swal2-input').value}
          else {return 'Debe Especificar e-Mail';}},      

          timer:0
          
     }).then((result) =>
     {
          if (result.isConfirmed){
               var data;
               {
                    data=new FormData();
                    data.append('script','mail_docu3');
                    data.append('docu1',docu1);
                    data.append('idnum1',idnum1);
                    data.append('email1',email1);
                    exe_ajax(data,'','',false);
               }
          }
     })
     
}



function atrz_docu(docu,idnum)
{
     Swal.fire({
       title: 'Autorizar Documento ?',
       text: 'Autorizar Documento',
       icon: 'question',
       focusCancel: true,
       showCancelButton: true,
       confirmButtonColor: color1,
       cancelButtonColor: 'darkred',
       confirmButtonText: 'SI, Autorizar!'
     }).then((result) =>
     {
          if (result.isConfirmed){
               var data;
               {
                    data=new FormData();
                    data.append('script','atrz_docu3');
                    data.append('docu',docu);
                    data.append('idnum',idnum);
//                     data.append('clave1',clave1);
                    exe_ajax(data,'','',false);
                    window.location.reload();
               }
          }
     })
     
}




function copy_docu(docu1,idnum1,docu2,ptoe2)
{
     Swal.fire({
       title: 'Copiar Documento ?',
       text: 'Copiar Documento',
       icon: 'question',
       focusCancel: true,
       showCancelButton: true,
       confirmButtonColor: color1,
       cancelButtonColor: 'darkred',
       confirmButtonText: 'SI, Copiar!'
     }).then((result) =>
     {
          if (result.isConfirmed){
               var data;
//                for(var idx=0; idx<xfile.files.length; idx++)
               {
                    data=new FormData();
                    data.append('script','copy_docu3');
                    data.append('docu1',docu1);
                    data.append('idnum1',idnum1);
                    exe_ajax(data,'','',false);
               }
          }
     })
     
}

function down_ics_jw(ics_file, docu='', nombres='')
{
//        text: 'Recordatorio para  === '+docu+'=== '+' \n\n '+nombres+' ?',
     
     
     Swal.fire({
       title: 'Recordatorio',
       html: ' === '+docu+'=== '+' <br> '+nombres+' ',
       icon: 'question',
       focusCancel: true,
       showCancelButton: true,
       confirmButtonColor: color1,
       cancelButtonColor: 'darkred',
       confirmButtonText: 'SI, Recordar!'
     }).then((result) =>
     {
          if (result.isConfirmed){window.open(ics_file,"_blank");}
     })
     
}




function clie2vtas(docu1,idnum1,docu2,ptoe2)
{
     var xtitle,xtext,xconfirm;
     
     xtitle='Emitir Factura  ?';
     xtext='Emitir Factura  ';
     xconfirm='SI, Facturar';
     
     if(docu2=='FC90')
     {
          xtitle='Emitir NO/Venta  ?';
          xtext='Emitir NO/Venta  ';
          xconfirm='SI, Emitir N/V';
     }
     
     Swal.fire({
       title: xtitle,
       text: xtext,
       icon: 'question',
       focusCancel: true,
       showCancelButton: true,
       confirmButtonColor: color1,
       cancelButtonColor: 'darkred',
       confirmButtonText: xconfirm,
     }).then((result) =>
     {
          if (result.isConfirmed){
               var data;
//                for(var idx=0; idx<xfile.files.length; idx++)
               {
                    data=new FormData();
                    data.append('script','clie2vtas');
                    data.append('docu1',docu1);
                    data.append('idnum1',idnum1);
                    data.append('docu2',docu2);
                    data.append('ptov',ptoe2);
                    exe_ajax(data,'','',false);
               }
          }
     })
     
}


function gene_guia(docu1,idnum1,docu2,ptoe2)
{
     Swal.fire({
       title: 'Emitir Guía ?',
       text: 'Emitir Guía de Remisión',
       icon: 'question',
       focusCancel: true,
       showCancelButton: true,
       confirmButtonColor: color1,
       cancelButtonColor: 'darkred',
       confirmButtonText: 'SI, Emitir GUIA!'
     }).then((result) =>
     {
          if (result.isConfirmed){
               var data;
//                for(var idx=0; idx<xfile.files.length; idx++)
               {
                    data=new FormData();
                    data.append('script','gene_guia');
                    data.append('docu1',docu1);
                    data.append('idnum1',idnum1);
                    data.append('docu2',docu2);
                    data.append('ptov',ptoe2);
                    exe_ajax(data,'','',false);
               }
          }
     })
     
}


function habilitarInput(elemento) 
{
//      alert(1);
  elemento.disabled = false;
  document.getElementById(elemento).removeAttribute("disabled");   
//   elemento.focus(); 
     // Opcional: enfoca el input automáticamente
}

