
window.onbeforeunload = function(event){return confirm("Confirme Recargar la Página");};
window.onload=function(event)
{
     document.getElementById('item').focus();
     document.cookie = "test_numero=456";     
};

function time_now(format=3)
{
     momentoActual = new Date();

     anio = momentoActual.getFullYear();
     mes = momentoActual.getMonth()+1;
     dia = momentoActual.getDate();
     
     hora = momentoActual.getHours();
     minuto = momentoActual.getMinutes();
     segundo = momentoActual.getSeconds(); 
     miliseg = momentoActual.getMilliseconds();

     mes=('0'+mes).slice(-2);
     dia=('0'+dia).slice(-2);
     hora=('0'+hora).slice(-2);
     minuto=('0'+minuto).slice(-2);
     segundo=('0'+segundo).slice(-2);

     if(format==1)
     {total =anio+"-"+mes+"-"+dia;}
     
     if(format==2)
     {total =hora+":"+minuto+":"+segundo;}
     
     if(format==3)
     {total =hora+":"+minuto+":"+segundo+"."+miliseg;}
     
     if(format==4)
     {total =anio+"-"+mes+"-"+dia+"_"+hora+":"+minuto+":"+segundo;}
     
     return total;
     
}


function save_docu()
{
     date_time=time_now(4);
     date_time.replace(":","-");

     screen1=document.getElementById("screen1").innerHTML;
     document.getElementById("screen1").innerHTML='';
     
     script1=document.getElementById("script1").innerHTML;
     document.getElementById("script1").innerHTML='';
     
     docu=document.getElementById("html1");
     blob = new Blob([docu.outerHTML], { type: "text/xml" });
     enlace = document.createElement("a");
     enlace.href = window.URL.createObjectURL(blob);
     enlace.download = "Factura_"+date_time+".html";
     enlace.click();
     
     document.getElementById("screen1").innerHTML=screen1;
//      document.getElementById("script1").innerHTML=script1;
     
}

function calc_total()
{
     item=document.getElementsByClassName('item');
     producto=document.getElementsByClassName('producto');
     cant=document.getElementsByClassName('cant');
     iva=document.getElementsByClassName('iva');
     pvp1=document.getElementsByClassName('pvp1');
     subt=document.getElementsByClassName('subtot');
     
     unds=0;
     total=0;

     tabla=document.getElementById("print_body");
     document.getElementById('print_body').innerHTML="";
     
     for (idx = 0; idx<cant.length; idx++)
     {
          unds=unds+ cant[idx].value;
          subt=(cant[idx].value*pvp1[idx].value);
          total=total+subt;
          document.getElementById('subtot_'+ cant[idx].id.substring(5)).value=subt.toFixed(2);
          
          document.getElementById('ivasn_'+ cant[idx].id.substring(5)).value="-";
          if(parseFloat(iva[idx].value)>0)
          {document.getElementById('ivasn_'+ cant[idx].id.substring(5)).value="I";}

          
          ccolu=0;
          fila=tabla.insertRow();
          
          colu=fila.insertCell(ccolu++);
          colu.innerHTML=idx+1;
          colu.setAttribute("align","center");
//           colu.setAttribute("colspan","10");
          
          colu=fila.insertCell(ccolu++);
          colu.innerHTML=document.getElementById('descri_'+ cant[idx].id.substring(5)).value;
          colu.setAttribute("colspan","10");
          
          ccolu=0;          
          fila=tabla.insertRow();
          
          colu=fila.insertCell(ccolu++);
          
          colu=fila.insertCell(ccolu++);
          colu.innerHTML=document.getElementById('cant_'+ cant[idx].id.substring(5)).value;
          colu.setAttribute("align","right");
          
          colu=fila.insertCell(ccolu++);
          colu.innerHTML=document.getElementById('pvp1_'+ cant[idx].id.substring(5)).value;
          colu.setAttribute("align","right");
          
          colu=fila.insertCell(ccolu++);
          colu.innerHTML=document.getElementById('subtot_'+ cant[idx].id.substring(5)).value;
          colu.setAttribute("align","right");
          
     }    
     document.getElementById('total').value=total.toFixed(2);
     
     document.getElementById('print_enti').innerHTML=document.getElementById('enti').value +" "+ document.getElementById('enti_descri').value;
//      document.getElementById('print_body').innerHTML="";

//      print1();
}

function print1()
{
//      document.getElementById('print_enti').innerHTML=document.getElementById('enti').value +" "+ document.getElementById('enti_descri').value;
//      document.getElementById('print_body').innerHTML="";
     
}

function add_row(value)
{
//      test_file();
     if(!read_docunume()){alert('FACTURA o NOTA/VENTA');return;}

//      console.log(document.cookie);
     
     num_fila=time_now();

     tabla=document.getElementById("body_detalle");
     fila=tabla.insertRow();
     fila.setAttribute("id","row_"+num_fila);

     ccolu=0;
     ///////////////////////////////////
     colu=fila.insertCell(ccolu++);
     input = document.createElement("input");
     input.id = "codigo_"+num_fila;
//      input.setAttribute("list","dl_item");
//      input.setAttribute("onblur","{document.getElementById(\"descri_\"+num_fila).value=document.getElementById(\"item_\"+this.value).getAttribute(\"descri\");}");
     input.value = value;
     input.setAttribute("readonly"," ");
     input.setAttribute("tabindex","-1");
     input.setAttribute("class","item");
     input.setAttribute("style","background: transparent; border:none;");
     colu.appendChild(input);
     
     ///////////////////////////////////
     colu=fila.insertCell(ccolu++);
     input = document.createElement("input");
     input.id = "descri_"+num_fila;
     if(document.getElementById("item_"+value))
     {input.value = document.getElementById("item_"+value).getAttribute("descri");}
     input.setAttribute("readonly"," ");
     input.setAttribute("tabindex","-1");
     input.setAttribute("class","producto");
     input.setAttribute("style","background: transparent; border:none;");
     colu.appendChild(input);
     

     ///////////////////////////////////
     colu=fila.insertCell(ccolu++);
     input = document.createElement("input");
     input.id = "cant_"+num_fila;
     input.type = "number";
     input.value = 1
     input.min = 0;
     input.max = 999;
     input.style = "text-align:right;";
     input.setAttribute("onchange","calc_total()");
     input.setAttribute("class","cant");
//      input.setAttribute("tabindex","-1");
     input.setAttribute("style","background: transparent; border:none; text-align:right;");
     colu.appendChild(input);
     
     ///////////////////////////////////
     colu=fila.insertCell(ccolu++);
     colu.setAttribute("style","display:none;")
     
     ///////////////////////////////////
     colu=fila.insertCell(ccolu++);
     colu.setAttribute("style","display:none;")
     input = document.createElement("input");
     input.id = "iva_"+num_fila;
     input.type = "number";
     if(document.getElementById("item_"+value))
     {input.value = parseFloat(document.getElementById("item_"+value).getAttribute("iva")).toFixed(2);}
     input.style = "text-align:rigth;";
     input.setAttribute("readonly"," ");
//      input.setAttribute("onchange","this.value=parseFloat(this.value).toFixed(2);calc_total();");
     input.setAttribute("class","iva");
     input.setAttribute("tabindex","-1");
     input.setAttribute("style","background: transparent; border:none; text-align:right;");
     colu.appendChild(input);
     
     ///////////////////////////////////
     colu=fila.insertCell(ccolu++);
     colu.setAttribute("align","center")
     input = document.createElement("input");
     input.id = "ivasn_"+num_fila;
     input.setAttribute("readonly"," ");
     input.setAttribute("tabindex","-1");
     input.setAttribute("style","background: transparent; border:none; text-align:center; width:1em;");
     colu.appendChild(input);
     
     ///////////////////////////////////
     colu=fila.insertCell(ccolu++);
     input = document.createElement("input");
     input.id = "pvp1_"+num_fila;
     input.type = "number";
     if(document.getElementById("item_"+value))
     {input.value = parseFloat(document.getElementById("item_"+value).getAttribute("pvp1")).toFixed(2);}
     input.style = "text-align:right;";
     if(parseFloat(input.value)>0)
     {input.setAttribute("readonly"," ");}
     input.setAttribute("onchange","this.value=parseFloat(this.value).toFixed(2);calc_total();");
     input.setAttribute("class","pvp1");
     input.setAttribute("tabindex","-1");
     input.setAttribute("style","background: transparent; border:none; text-align:right;");
     colu.appendChild(input);
     
     
     ///////////////////////////////////
     colu=fila.insertCell(ccolu++);
     input = document.createElement("input");
     input.id = "subtot_"+num_fila;
     input.type = "number";
     if(document.getElementById("item_"+value))
     {input.value = parseFloat(document.getElementById("item_"+value).getAttribute("pvp1")).toFixed(2);}
     input.style = "text-align:right;";
     input.setAttribute("readonly"," ");
     input.setAttribute("class","subtot");
     input.setAttribute("tabindex","-1");
     input.setAttribute("style","background: transparent; border:none; text-align:right;");
     colu.appendChild(input);
     

     ///////////////////////////////////
     colu=fila.insertCell(ccolu++);
     button = document.createElement("button");
     button.id = "btn_"+num_fila;
     button.innerHTML = "Borrar";     
     button.setAttribute("onclick","this.parentElement.parentElement.remove();calc_total();");
     button.setAttribute("tabindex","-1");
     button.setAttribute("style","background: darkred; color:white; font-weight:bold; border:; vertical-align:middle;");
     colu.appendChild(button);
     colu.setAttribute("align","center");
     
     calc_total();
}

function dele_all()
{
     if(confirm("Borrar TODO ?"))
     {document.getElementById("body_detalle").innerHTML="";}
     calc_total();
}



function isValidBarcode(value) 
{
  if(value === null){return;}
       
  // 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 test_file()
{
     const fs = require('fs');
     const path = '/vcrx-ptov/ptov_test.txt';

     try
     {
         // Leer el archivo de forma síncrona
         const data = fs.readFileSync(path, 'utf8');
         console.log(data);
     }
     catch (err)
     {
         console.error('Error al leer el archivo:', err);
     }     
}


function read_docunume()
{
    var input = document.getElementById('docunume');
    var archivo = input.files[0];
    if (archivo) {
        var lector = new FileReader();
        lector.onload = function(e) {
            var contenido = e.target.result;
            mostrarContenido(contenido);
        };
        lector.readAsText(archivo);
    } else {
         document.getElementById('docunume').click();
//         alert('Por favor, selecciona un archivo.');
    }
}

function mostrarContenido(contenido)
{
    var elemento = document.getElementById('numero');
//     elemento.textContent = contenido;
    elemento.value = contenido;
}




